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::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   verifyFormat("if (a)\n"
465                "  g();");
466   verifyFormat("if (a) {\n"
467                "  g()\n"
468                "};");
469   verifyFormat("if (a)\n"
470                "  g();\n"
471                "else\n"
472                "  g();");
473   verifyFormat("if (a) {\n"
474                "  g();\n"
475                "} else\n"
476                "  g();");
477   verifyFormat("if (a)\n"
478                "  g();\n"
479                "else {\n"
480                "  g();\n"
481                "}");
482   verifyFormat("if (a) {\n"
483                "  g();\n"
484                "} else {\n"
485                "  g();\n"
486                "}");
487   verifyFormat("if (a)\n"
488                "  g();\n"
489                "else if (b)\n"
490                "  g();\n"
491                "else\n"
492                "  g();");
493   verifyFormat("if (a) {\n"
494                "  g();\n"
495                "} else if (b)\n"
496                "  g();\n"
497                "else\n"
498                "  g();");
499   verifyFormat("if (a)\n"
500                "  g();\n"
501                "else if (b) {\n"
502                "  g();\n"
503                "} else\n"
504                "  g();");
505   verifyFormat("if (a)\n"
506                "  g();\n"
507                "else if (b)\n"
508                "  g();\n"
509                "else {\n"
510                "  g();\n"
511                "}");
512   verifyFormat("if (a)\n"
513                "  g();\n"
514                "else if (b) {\n"
515                "  g();\n"
516                "} else {\n"
517                "  g();\n"
518                "}");
519   verifyFormat("if (a) {\n"
520                "  g();\n"
521                "} else if (b) {\n"
522                "  g();\n"
523                "} else {\n"
524                "  g();\n"
525                "}");
526 
527   FormatStyle AllowsMergedIf = getLLVMStyle();
528   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
529   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
530       FormatStyle::SIS_WithoutElse;
531   verifyFormat("if (a)\n"
532                "  // comment\n"
533                "  f();",
534                AllowsMergedIf);
535   verifyFormat("{\n"
536                "  if (a)\n"
537                "  label:\n"
538                "    f();\n"
539                "}",
540                AllowsMergedIf);
541   verifyFormat("#define A \\\n"
542                "  if (a)  \\\n"
543                "  label:  \\\n"
544                "    f()",
545                AllowsMergedIf);
546   verifyFormat("if (a)\n"
547                "  ;",
548                AllowsMergedIf);
549   verifyFormat("if (a)\n"
550                "  if (b) return;",
551                AllowsMergedIf);
552 
553   verifyFormat("if (a) // Can't merge this\n"
554                "  f();\n",
555                AllowsMergedIf);
556   verifyFormat("if (a) /* still don't merge */\n"
557                "  f();",
558                AllowsMergedIf);
559   verifyFormat("if (a) { // Never merge this\n"
560                "  f();\n"
561                "}",
562                AllowsMergedIf);
563   verifyFormat("if (a) { /* Never merge this */\n"
564                "  f();\n"
565                "}",
566                AllowsMergedIf);
567 
568   AllowsMergedIf.ColumnLimit = 14;
569   verifyFormat("if (a) return;", AllowsMergedIf);
570   verifyFormat("if (aaaaaaaaa)\n"
571                "  return;",
572                AllowsMergedIf);
573 
574   AllowsMergedIf.ColumnLimit = 13;
575   verifyFormat("if (a)\n  return;", AllowsMergedIf);
576 
577   FormatStyle AllowsMergedIfElse = getLLVMStyle();
578   AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine =
579       FormatStyle::SIS_AllIfsAndElse;
580   verifyFormat("if (a)\n"
581                "  // comment\n"
582                "  f();\n"
583                "else\n"
584                "  // comment\n"
585                "  f();",
586                AllowsMergedIfElse);
587   verifyFormat("{\n"
588                "  if (a)\n"
589                "  label:\n"
590                "    f();\n"
591                "  else\n"
592                "  label:\n"
593                "    f();\n"
594                "}",
595                AllowsMergedIfElse);
596   verifyFormat("if (a)\n"
597                "  ;\n"
598                "else\n"
599                "  ;",
600                AllowsMergedIfElse);
601   verifyFormat("if (a) {\n"
602                "} else {\n"
603                "}",
604                AllowsMergedIfElse);
605   verifyFormat("if (a) return;\n"
606                "else if (b) return;\n"
607                "else return;",
608                AllowsMergedIfElse);
609   verifyFormat("if (a) {\n"
610                "} else return;",
611                AllowsMergedIfElse);
612   verifyFormat("if (a) {\n"
613                "} else if (b) return;\n"
614                "else return;",
615                AllowsMergedIfElse);
616   verifyFormat("if (a) return;\n"
617                "else if (b) {\n"
618                "} else return;",
619                AllowsMergedIfElse);
620   verifyFormat("if (a)\n"
621                "  if (b) return;\n"
622                "  else return;",
623                AllowsMergedIfElse);
624   verifyFormat("if constexpr (a)\n"
625                "  if constexpr (b) return;\n"
626                "  else if constexpr (c) return;\n"
627                "  else return;",
628                AllowsMergedIfElse);
629 }
630 
631 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
632   FormatStyle AllowsMergedIf = getLLVMStyle();
633   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
634   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
635       FormatStyle::SIS_WithoutElse;
636   verifyFormat("if (a)\n"
637                "  f();\n"
638                "else {\n"
639                "  g();\n"
640                "}",
641                AllowsMergedIf);
642   verifyFormat("if (a)\n"
643                "  f();\n"
644                "else\n"
645                "  g();\n",
646                AllowsMergedIf);
647 
648   verifyFormat("if (a) g();", AllowsMergedIf);
649   verifyFormat("if (a) {\n"
650                "  g()\n"
651                "};",
652                AllowsMergedIf);
653   verifyFormat("if (a)\n"
654                "  g();\n"
655                "else\n"
656                "  g();",
657                AllowsMergedIf);
658   verifyFormat("if (a) {\n"
659                "  g();\n"
660                "} else\n"
661                "  g();",
662                AllowsMergedIf);
663   verifyFormat("if (a)\n"
664                "  g();\n"
665                "else {\n"
666                "  g();\n"
667                "}",
668                AllowsMergedIf);
669   verifyFormat("if (a) {\n"
670                "  g();\n"
671                "} else {\n"
672                "  g();\n"
673                "}",
674                AllowsMergedIf);
675   verifyFormat("if (a)\n"
676                "  g();\n"
677                "else if (b)\n"
678                "  g();\n"
679                "else\n"
680                "  g();",
681                AllowsMergedIf);
682   verifyFormat("if (a) {\n"
683                "  g();\n"
684                "} else if (b)\n"
685                "  g();\n"
686                "else\n"
687                "  g();",
688                AllowsMergedIf);
689   verifyFormat("if (a)\n"
690                "  g();\n"
691                "else if (b) {\n"
692                "  g();\n"
693                "} else\n"
694                "  g();",
695                AllowsMergedIf);
696   verifyFormat("if (a)\n"
697                "  g();\n"
698                "else if (b)\n"
699                "  g();\n"
700                "else {\n"
701                "  g();\n"
702                "}",
703                AllowsMergedIf);
704   verifyFormat("if (a)\n"
705                "  g();\n"
706                "else if (b) {\n"
707                "  g();\n"
708                "} else {\n"
709                "  g();\n"
710                "}",
711                AllowsMergedIf);
712   verifyFormat("if (a) {\n"
713                "  g();\n"
714                "} else if (b) {\n"
715                "  g();\n"
716                "} else {\n"
717                "  g();\n"
718                "}",
719                AllowsMergedIf);
720 
721   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
722       FormatStyle::SIS_OnlyFirstIf;
723 
724   verifyFormat("if (a) f();\n"
725                "else {\n"
726                "  g();\n"
727                "}",
728                AllowsMergedIf);
729   verifyFormat("if (a) f();\n"
730                "else {\n"
731                "  if (a) f();\n"
732                "  else {\n"
733                "    g();\n"
734                "  }\n"
735                "  g();\n"
736                "}",
737                AllowsMergedIf);
738 
739   verifyFormat("if (a) g();", AllowsMergedIf);
740   verifyFormat("if (a) {\n"
741                "  g()\n"
742                "};",
743                AllowsMergedIf);
744   verifyFormat("if (a) g();\n"
745                "else\n"
746                "  g();",
747                AllowsMergedIf);
748   verifyFormat("if (a) {\n"
749                "  g();\n"
750                "} else\n"
751                "  g();",
752                AllowsMergedIf);
753   verifyFormat("if (a) g();\n"
754                "else {\n"
755                "  g();\n"
756                "}",
757                AllowsMergedIf);
758   verifyFormat("if (a) {\n"
759                "  g();\n"
760                "} else {\n"
761                "  g();\n"
762                "}",
763                AllowsMergedIf);
764   verifyFormat("if (a) g();\n"
765                "else if (b)\n"
766                "  g();\n"
767                "else\n"
768                "  g();",
769                AllowsMergedIf);
770   verifyFormat("if (a) {\n"
771                "  g();\n"
772                "} else if (b)\n"
773                "  g();\n"
774                "else\n"
775                "  g();",
776                AllowsMergedIf);
777   verifyFormat("if (a) g();\n"
778                "else if (b) {\n"
779                "  g();\n"
780                "} else\n"
781                "  g();",
782                AllowsMergedIf);
783   verifyFormat("if (a) g();\n"
784                "else if (b)\n"
785                "  g();\n"
786                "else {\n"
787                "  g();\n"
788                "}",
789                AllowsMergedIf);
790   verifyFormat("if (a) g();\n"
791                "else if (b) {\n"
792                "  g();\n"
793                "} else {\n"
794                "  g();\n"
795                "}",
796                AllowsMergedIf);
797   verifyFormat("if (a) {\n"
798                "  g();\n"
799                "} else if (b) {\n"
800                "  g();\n"
801                "} else {\n"
802                "  g();\n"
803                "}",
804                AllowsMergedIf);
805 
806   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
807       FormatStyle::SIS_AllIfsAndElse;
808 
809   verifyFormat("if (a) f();\n"
810                "else {\n"
811                "  g();\n"
812                "}",
813                AllowsMergedIf);
814   verifyFormat("if (a) f();\n"
815                "else {\n"
816                "  if (a) f();\n"
817                "  else {\n"
818                "    g();\n"
819                "  }\n"
820                "  g();\n"
821                "}",
822                AllowsMergedIf);
823 
824   verifyFormat("if (a) g();", AllowsMergedIf);
825   verifyFormat("if (a) {\n"
826                "  g()\n"
827                "};",
828                AllowsMergedIf);
829   verifyFormat("if (a) g();\n"
830                "else g();",
831                AllowsMergedIf);
832   verifyFormat("if (a) {\n"
833                "  g();\n"
834                "} else g();",
835                AllowsMergedIf);
836   verifyFormat("if (a) g();\n"
837                "else {\n"
838                "  g();\n"
839                "}",
840                AllowsMergedIf);
841   verifyFormat("if (a) {\n"
842                "  g();\n"
843                "} else {\n"
844                "  g();\n"
845                "}",
846                AllowsMergedIf);
847   verifyFormat("if (a) g();\n"
848                "else if (b) g();\n"
849                "else g();",
850                AllowsMergedIf);
851   verifyFormat("if (a) {\n"
852                "  g();\n"
853                "} else if (b) g();\n"
854                "else g();",
855                AllowsMergedIf);
856   verifyFormat("if (a) g();\n"
857                "else if (b) {\n"
858                "  g();\n"
859                "} else g();",
860                AllowsMergedIf);
861   verifyFormat("if (a) g();\n"
862                "else if (b) g();\n"
863                "else {\n"
864                "  g();\n"
865                "}",
866                AllowsMergedIf);
867   verifyFormat("if (a) g();\n"
868                "else if (b) {\n"
869                "  g();\n"
870                "} else {\n"
871                "  g();\n"
872                "}",
873                AllowsMergedIf);
874   verifyFormat("if (a) {\n"
875                "  g();\n"
876                "} else if (b) {\n"
877                "  g();\n"
878                "} else {\n"
879                "  g();\n"
880                "}",
881                AllowsMergedIf);
882 }
883 
884 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
885   FormatStyle AllowsMergedLoops = getLLVMStyle();
886   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
887   verifyFormat("while (true) continue;", AllowsMergedLoops);
888   verifyFormat("for (;;) continue;", AllowsMergedLoops);
889   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
890   verifyFormat("while (true)\n"
891                "  ;",
892                AllowsMergedLoops);
893   verifyFormat("for (;;)\n"
894                "  ;",
895                AllowsMergedLoops);
896   verifyFormat("for (;;)\n"
897                "  for (;;) continue;",
898                AllowsMergedLoops);
899   verifyFormat("for (;;) // Can't merge this\n"
900                "  continue;",
901                AllowsMergedLoops);
902   verifyFormat("for (;;) /* still don't merge */\n"
903                "  continue;",
904                AllowsMergedLoops);
905   verifyFormat("do a++;\n"
906                "while (true);",
907                AllowsMergedLoops);
908   verifyFormat("do /* Don't merge */\n"
909                "  a++;\n"
910                "while (true);",
911                AllowsMergedLoops);
912   verifyFormat("do // Don't merge\n"
913                "  a++;\n"
914                "while (true);",
915                AllowsMergedLoops);
916   verifyFormat("do\n"
917                "  // Don't merge\n"
918                "  a++;\n"
919                "while (true);",
920                AllowsMergedLoops);
921   // Without braces labels are interpreted differently.
922   verifyFormat("{\n"
923                "  do\n"
924                "  label:\n"
925                "    a++;\n"
926                "  while (true);\n"
927                "}",
928                AllowsMergedLoops);
929 }
930 
931 TEST_F(FormatTest, FormatShortBracedStatements) {
932   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
933   AllowSimpleBracedStatements.ColumnLimit = 40;
934   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
935       FormatStyle::SBS_Always;
936 
937   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
938       FormatStyle::SIS_WithoutElse;
939   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
940 
941   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
942   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
943   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
944 
945   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
946   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
947   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
948   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
949   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
950   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
951   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
952   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
953   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
954   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
955   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
956                AllowSimpleBracedStatements);
957   verifyFormat("if (true) {\n"
958                "  ffffffffffffffffffffffff();\n"
959                "}",
960                AllowSimpleBracedStatements);
961   verifyFormat("if (true) {\n"
962                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
963                "}",
964                AllowSimpleBracedStatements);
965   verifyFormat("if (true) { //\n"
966                "  f();\n"
967                "}",
968                AllowSimpleBracedStatements);
969   verifyFormat("if (true) {\n"
970                "  f();\n"
971                "  f();\n"
972                "}",
973                AllowSimpleBracedStatements);
974   verifyFormat("if (true) {\n"
975                "  f();\n"
976                "} else {\n"
977                "  f();\n"
978                "}",
979                AllowSimpleBracedStatements);
980 
981   verifyFormat("struct A2 {\n"
982                "  int X;\n"
983                "};",
984                AllowSimpleBracedStatements);
985   verifyFormat("typedef struct A2 {\n"
986                "  int X;\n"
987                "} A2_t;",
988                AllowSimpleBracedStatements);
989   verifyFormat("template <int> struct A2 {\n"
990                "  struct B {};\n"
991                "};",
992                AllowSimpleBracedStatements);
993 
994   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
995       FormatStyle::SIS_Never;
996   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
997   verifyFormat("if (true) {\n"
998                "  f();\n"
999                "}",
1000                AllowSimpleBracedStatements);
1001   verifyFormat("if (true) {\n"
1002                "  f();\n"
1003                "} else {\n"
1004                "  f();\n"
1005                "}",
1006                AllowSimpleBracedStatements);
1007 
1008   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1009   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1010   verifyFormat("while (true) {\n"
1011                "  f();\n"
1012                "}",
1013                AllowSimpleBracedStatements);
1014   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1015   verifyFormat("for (;;) {\n"
1016                "  f();\n"
1017                "}",
1018                AllowSimpleBracedStatements);
1019 
1020   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1021       FormatStyle::SIS_WithoutElse;
1022   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1023   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1024       FormatStyle::BWACS_Always;
1025 
1026   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1027   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1028   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1029   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1030   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1031   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1032   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1033   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1034   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1035   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1036   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1037                AllowSimpleBracedStatements);
1038   verifyFormat("if (true)\n"
1039                "{\n"
1040                "  ffffffffffffffffffffffff();\n"
1041                "}",
1042                AllowSimpleBracedStatements);
1043   verifyFormat("if (true)\n"
1044                "{\n"
1045                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1046                "}",
1047                AllowSimpleBracedStatements);
1048   verifyFormat("if (true)\n"
1049                "{ //\n"
1050                "  f();\n"
1051                "}",
1052                AllowSimpleBracedStatements);
1053   verifyFormat("if (true)\n"
1054                "{\n"
1055                "  f();\n"
1056                "  f();\n"
1057                "}",
1058                AllowSimpleBracedStatements);
1059   verifyFormat("if (true)\n"
1060                "{\n"
1061                "  f();\n"
1062                "} else\n"
1063                "{\n"
1064                "  f();\n"
1065                "}",
1066                AllowSimpleBracedStatements);
1067 
1068   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1069       FormatStyle::SIS_Never;
1070   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1071   verifyFormat("if (true)\n"
1072                "{\n"
1073                "  f();\n"
1074                "}",
1075                AllowSimpleBracedStatements);
1076   verifyFormat("if (true)\n"
1077                "{\n"
1078                "  f();\n"
1079                "} else\n"
1080                "{\n"
1081                "  f();\n"
1082                "}",
1083                AllowSimpleBracedStatements);
1084 
1085   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1086   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1087   verifyFormat("while (true)\n"
1088                "{\n"
1089                "  f();\n"
1090                "}",
1091                AllowSimpleBracedStatements);
1092   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1093   verifyFormat("for (;;)\n"
1094                "{\n"
1095                "  f();\n"
1096                "}",
1097                AllowSimpleBracedStatements);
1098 }
1099 
1100 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1101   FormatStyle Style = getLLVMStyleWithColumns(60);
1102   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1103   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1104   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1105   EXPECT_EQ("#define A                                                  \\\n"
1106             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1107             "  {                                                        \\\n"
1108             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1109             "  }\n"
1110             "X;",
1111             format("#define A \\\n"
1112                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1113                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1114                    "   }\n"
1115                    "X;",
1116                    Style));
1117 }
1118 
1119 TEST_F(FormatTest, ParseIfElse) {
1120   verifyFormat("if (true)\n"
1121                "  if (true)\n"
1122                "    if (true)\n"
1123                "      f();\n"
1124                "    else\n"
1125                "      g();\n"
1126                "  else\n"
1127                "    h();\n"
1128                "else\n"
1129                "  i();");
1130   verifyFormat("if (true)\n"
1131                "  if (true)\n"
1132                "    if (true) {\n"
1133                "      if (true)\n"
1134                "        f();\n"
1135                "    } else {\n"
1136                "      g();\n"
1137                "    }\n"
1138                "  else\n"
1139                "    h();\n"
1140                "else {\n"
1141                "  i();\n"
1142                "}");
1143   verifyFormat("if (true)\n"
1144                "  if constexpr (true)\n"
1145                "    if (true) {\n"
1146                "      if constexpr (true)\n"
1147                "        f();\n"
1148                "    } else {\n"
1149                "      g();\n"
1150                "    }\n"
1151                "  else\n"
1152                "    h();\n"
1153                "else {\n"
1154                "  i();\n"
1155                "}");
1156   verifyFormat("if (true)\n"
1157                "  if CONSTEXPR (true)\n"
1158                "    if (true) {\n"
1159                "      if CONSTEXPR (true)\n"
1160                "        f();\n"
1161                "    } else {\n"
1162                "      g();\n"
1163                "    }\n"
1164                "  else\n"
1165                "    h();\n"
1166                "else {\n"
1167                "  i();\n"
1168                "}");
1169   verifyFormat("void f() {\n"
1170                "  if (a) {\n"
1171                "  } else {\n"
1172                "  }\n"
1173                "}");
1174 }
1175 
1176 TEST_F(FormatTest, ElseIf) {
1177   verifyFormat("if (a) {\n} else if (b) {\n}");
1178   verifyFormat("if (a)\n"
1179                "  f();\n"
1180                "else if (b)\n"
1181                "  g();\n"
1182                "else\n"
1183                "  h();");
1184   verifyFormat("if constexpr (a)\n"
1185                "  f();\n"
1186                "else if constexpr (b)\n"
1187                "  g();\n"
1188                "else\n"
1189                "  h();");
1190   verifyFormat("if CONSTEXPR (a)\n"
1191                "  f();\n"
1192                "else if CONSTEXPR (b)\n"
1193                "  g();\n"
1194                "else\n"
1195                "  h();");
1196   verifyFormat("if (a) {\n"
1197                "  f();\n"
1198                "}\n"
1199                "// or else ..\n"
1200                "else {\n"
1201                "  g()\n"
1202                "}");
1203 
1204   verifyFormat("if (a) {\n"
1205                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1206                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1207                "}");
1208   verifyFormat("if (a) {\n"
1209                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1210                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1211                "}");
1212   verifyFormat("if (a) {\n"
1213                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1214                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1215                "}");
1216   verifyFormat("if (a) {\n"
1217                "} else if (\n"
1218                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1219                "}",
1220                getLLVMStyleWithColumns(62));
1221   verifyFormat("if (a) {\n"
1222                "} else if constexpr (\n"
1223                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1224                "}",
1225                getLLVMStyleWithColumns(62));
1226   verifyFormat("if (a) {\n"
1227                "} else if CONSTEXPR (\n"
1228                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1229                "}",
1230                getLLVMStyleWithColumns(62));
1231 }
1232 
1233 TEST_F(FormatTest, FormatsForLoop) {
1234   verifyFormat(
1235       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
1236       "     ++VeryVeryLongLoopVariable)\n"
1237       "  ;");
1238   verifyFormat("for (;;)\n"
1239                "  f();");
1240   verifyFormat("for (;;) {\n}");
1241   verifyFormat("for (;;) {\n"
1242                "  f();\n"
1243                "}");
1244   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
1245 
1246   verifyFormat(
1247       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
1248       "                                          E = UnwrappedLines.end();\n"
1249       "     I != E; ++I) {\n}");
1250 
1251   verifyFormat(
1252       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
1253       "     ++IIIII) {\n}");
1254   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
1255                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
1256                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
1257   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
1258                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
1259                "         E = FD->getDeclsInPrototypeScope().end();\n"
1260                "     I != E; ++I) {\n}");
1261   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
1262                "         I = Container.begin(),\n"
1263                "         E = Container.end();\n"
1264                "     I != E; ++I) {\n}",
1265                getLLVMStyleWithColumns(76));
1266 
1267   verifyFormat(
1268       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
1269       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
1270       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1271       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
1272       "     ++aaaaaaaaaaa) {\n}");
1273   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
1274                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
1275                "     ++i) {\n}");
1276   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
1277                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
1278                "}");
1279   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
1280                "         aaaaaaaaaa);\n"
1281                "     iter; ++iter) {\n"
1282                "}");
1283   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1284                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
1285                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
1286                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
1287 
1288   // These should not be formatted as Objective-C for-in loops.
1289   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
1290   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
1291   verifyFormat("Foo *x;\nfor (x in y) {\n}");
1292   verifyFormat(
1293       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
1294 
1295   FormatStyle NoBinPacking = getLLVMStyle();
1296   NoBinPacking.BinPackParameters = false;
1297   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
1298                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
1299                "                                           aaaaaaaaaaaaaaaa,\n"
1300                "                                           aaaaaaaaaaaaaaaa,\n"
1301                "                                           aaaaaaaaaaaaaaaa);\n"
1302                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
1303                "}",
1304                NoBinPacking);
1305   verifyFormat(
1306       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
1307       "                                          E = UnwrappedLines.end();\n"
1308       "     I != E;\n"
1309       "     ++I) {\n}",
1310       NoBinPacking);
1311 
1312   FormatStyle AlignLeft = getLLVMStyle();
1313   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
1314   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
1315 }
1316 
1317 TEST_F(FormatTest, RangeBasedForLoops) {
1318   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
1319                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
1320   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
1321                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
1322   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
1323                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
1324   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
1325                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
1326 }
1327 
1328 TEST_F(FormatTest, ForEachLoops) {
1329   verifyFormat("void f() {\n"
1330                "  foreach (Item *item, itemlist) {}\n"
1331                "  Q_FOREACH (Item *item, itemlist) {}\n"
1332                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
1333                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
1334                "}");
1335 
1336   FormatStyle Style = getLLVMStyle();
1337   Style.SpaceBeforeParens =
1338       FormatStyle::SBPO_ControlStatementsExceptForEachMacros;
1339   verifyFormat("void f() {\n"
1340                "  foreach(Item *item, itemlist) {}\n"
1341                "  Q_FOREACH(Item *item, itemlist) {}\n"
1342                "  BOOST_FOREACH(Item *item, itemlist) {}\n"
1343                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
1344                "}",
1345                Style);
1346 
1347   // As function-like macros.
1348   verifyFormat("#define foreach(x, y)\n"
1349                "#define Q_FOREACH(x, y)\n"
1350                "#define BOOST_FOREACH(x, y)\n"
1351                "#define UNKNOWN_FOREACH(x, y)\n");
1352 
1353   // Not as function-like macros.
1354   verifyFormat("#define foreach (x, y)\n"
1355                "#define Q_FOREACH (x, y)\n"
1356                "#define BOOST_FOREACH (x, y)\n"
1357                "#define UNKNOWN_FOREACH (x, y)\n");
1358 
1359   // handle microsoft non standard extension
1360   verifyFormat("for each (char c in x->MyStringProperty)");
1361 }
1362 
1363 TEST_F(FormatTest, FormatsWhileLoop) {
1364   verifyFormat("while (true) {\n}");
1365   verifyFormat("while (true)\n"
1366                "  f();");
1367   verifyFormat("while () {\n}");
1368   verifyFormat("while () {\n"
1369                "  f();\n"
1370                "}");
1371 }
1372 
1373 TEST_F(FormatTest, FormatsDoWhile) {
1374   verifyFormat("do {\n"
1375                "  do_something();\n"
1376                "} while (something());");
1377   verifyFormat("do\n"
1378                "  do_something();\n"
1379                "while (something());");
1380 }
1381 
1382 TEST_F(FormatTest, FormatsSwitchStatement) {
1383   verifyFormat("switch (x) {\n"
1384                "case 1:\n"
1385                "  f();\n"
1386                "  break;\n"
1387                "case kFoo:\n"
1388                "case ns::kBar:\n"
1389                "case kBaz:\n"
1390                "  break;\n"
1391                "default:\n"
1392                "  g();\n"
1393                "  break;\n"
1394                "}");
1395   verifyFormat("switch (x) {\n"
1396                "case 1: {\n"
1397                "  f();\n"
1398                "  break;\n"
1399                "}\n"
1400                "case 2: {\n"
1401                "  break;\n"
1402                "}\n"
1403                "}");
1404   verifyFormat("switch (x) {\n"
1405                "case 1: {\n"
1406                "  f();\n"
1407                "  {\n"
1408                "    g();\n"
1409                "    h();\n"
1410                "  }\n"
1411                "  break;\n"
1412                "}\n"
1413                "}");
1414   verifyFormat("switch (x) {\n"
1415                "case 1: {\n"
1416                "  f();\n"
1417                "  if (foo) {\n"
1418                "    g();\n"
1419                "    h();\n"
1420                "  }\n"
1421                "  break;\n"
1422                "}\n"
1423                "}");
1424   verifyFormat("switch (x) {\n"
1425                "case 1: {\n"
1426                "  f();\n"
1427                "  g();\n"
1428                "} break;\n"
1429                "}");
1430   verifyFormat("switch (test)\n"
1431                "  ;");
1432   verifyFormat("switch (x) {\n"
1433                "default: {\n"
1434                "  // Do nothing.\n"
1435                "}\n"
1436                "}");
1437   verifyFormat("switch (x) {\n"
1438                "// comment\n"
1439                "// if 1, do f()\n"
1440                "case 1:\n"
1441                "  f();\n"
1442                "}");
1443   verifyFormat("switch (x) {\n"
1444                "case 1:\n"
1445                "  // Do amazing stuff\n"
1446                "  {\n"
1447                "    f();\n"
1448                "    g();\n"
1449                "  }\n"
1450                "  break;\n"
1451                "}");
1452   verifyFormat("#define A          \\\n"
1453                "  switch (x) {     \\\n"
1454                "  case a:          \\\n"
1455                "    foo = b;       \\\n"
1456                "  }",
1457                getLLVMStyleWithColumns(20));
1458   verifyFormat("#define OPERATION_CASE(name)           \\\n"
1459                "  case OP_name:                        \\\n"
1460                "    return operations::Operation##name\n",
1461                getLLVMStyleWithColumns(40));
1462   verifyFormat("switch (x) {\n"
1463                "case 1:;\n"
1464                "default:;\n"
1465                "  int i;\n"
1466                "}");
1467 
1468   verifyGoogleFormat("switch (x) {\n"
1469                      "  case 1:\n"
1470                      "    f();\n"
1471                      "    break;\n"
1472                      "  case kFoo:\n"
1473                      "  case ns::kBar:\n"
1474                      "  case kBaz:\n"
1475                      "    break;\n"
1476                      "  default:\n"
1477                      "    g();\n"
1478                      "    break;\n"
1479                      "}");
1480   verifyGoogleFormat("switch (x) {\n"
1481                      "  case 1: {\n"
1482                      "    f();\n"
1483                      "    break;\n"
1484                      "  }\n"
1485                      "}");
1486   verifyGoogleFormat("switch (test)\n"
1487                      "  ;");
1488 
1489   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
1490                      "  case OP_name:              \\\n"
1491                      "    return operations::Operation##name\n");
1492   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
1493                      "  // Get the correction operation class.\n"
1494                      "  switch (OpCode) {\n"
1495                      "    CASE(Add);\n"
1496                      "    CASE(Subtract);\n"
1497                      "    default:\n"
1498                      "      return operations::Unknown;\n"
1499                      "  }\n"
1500                      "#undef OPERATION_CASE\n"
1501                      "}");
1502   verifyFormat("DEBUG({\n"
1503                "  switch (x) {\n"
1504                "  case A:\n"
1505                "    f();\n"
1506                "    break;\n"
1507                "    // fallthrough\n"
1508                "  case B:\n"
1509                "    g();\n"
1510                "    break;\n"
1511                "  }\n"
1512                "});");
1513   EXPECT_EQ("DEBUG({\n"
1514             "  switch (x) {\n"
1515             "  case A:\n"
1516             "    f();\n"
1517             "    break;\n"
1518             "  // On B:\n"
1519             "  case B:\n"
1520             "    g();\n"
1521             "    break;\n"
1522             "  }\n"
1523             "});",
1524             format("DEBUG({\n"
1525                    "  switch (x) {\n"
1526                    "  case A:\n"
1527                    "    f();\n"
1528                    "    break;\n"
1529                    "  // On B:\n"
1530                    "  case B:\n"
1531                    "    g();\n"
1532                    "    break;\n"
1533                    "  }\n"
1534                    "});",
1535                    getLLVMStyle()));
1536   EXPECT_EQ("switch (n) {\n"
1537             "case 0: {\n"
1538             "  return false;\n"
1539             "}\n"
1540             "default: {\n"
1541             "  return true;\n"
1542             "}\n"
1543             "}",
1544             format("switch (n)\n"
1545                    "{\n"
1546                    "case 0: {\n"
1547                    "  return false;\n"
1548                    "}\n"
1549                    "default: {\n"
1550                    "  return true;\n"
1551                    "}\n"
1552                    "}",
1553                    getLLVMStyle()));
1554   verifyFormat("switch (a) {\n"
1555                "case (b):\n"
1556                "  return;\n"
1557                "}");
1558 
1559   verifyFormat("switch (a) {\n"
1560                "case some_namespace::\n"
1561                "    some_constant:\n"
1562                "  return;\n"
1563                "}",
1564                getLLVMStyleWithColumns(34));
1565 
1566   FormatStyle Style = getLLVMStyle();
1567   Style.IndentCaseLabels = true;
1568   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1569   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1570   Style.BraceWrapping.AfterCaseLabel = true;
1571   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1572   EXPECT_EQ("switch (n)\n"
1573             "{\n"
1574             "  case 0:\n"
1575             "  {\n"
1576             "    return false;\n"
1577             "  }\n"
1578             "  default:\n"
1579             "  {\n"
1580             "    return true;\n"
1581             "  }\n"
1582             "}",
1583             format("switch (n) {\n"
1584                    "  case 0: {\n"
1585                    "    return false;\n"
1586                    "  }\n"
1587                    "  default: {\n"
1588                    "    return true;\n"
1589                    "  }\n"
1590                    "}",
1591                    Style));
1592   Style.BraceWrapping.AfterCaseLabel = false;
1593   EXPECT_EQ("switch (n)\n"
1594             "{\n"
1595             "  case 0: {\n"
1596             "    return false;\n"
1597             "  }\n"
1598             "  default: {\n"
1599             "    return true;\n"
1600             "  }\n"
1601             "}",
1602             format("switch (n) {\n"
1603                    "  case 0:\n"
1604                    "  {\n"
1605                    "    return false;\n"
1606                    "  }\n"
1607                    "  default:\n"
1608                    "  {\n"
1609                    "    return true;\n"
1610                    "  }\n"
1611                    "}",
1612                    Style));
1613   Style.IndentCaseLabels = false;
1614   Style.IndentCaseBlocks = true;
1615   EXPECT_EQ("switch (n)\n"
1616             "{\n"
1617             "case 0:\n"
1618             "  {\n"
1619             "    return false;\n"
1620             "  }\n"
1621             "case 1:\n"
1622             "  break;\n"
1623             "default:\n"
1624             "  {\n"
1625             "    return true;\n"
1626             "  }\n"
1627             "}",
1628             format("switch (n) {\n"
1629                    "case 0: {\n"
1630                    "  return false;\n"
1631                    "}\n"
1632                    "case 1:\n"
1633                    "  break;\n"
1634                    "default: {\n"
1635                    "  return true;\n"
1636                    "}\n"
1637                    "}",
1638                    Style));
1639   Style.IndentCaseLabels = true;
1640   Style.IndentCaseBlocks = true;
1641   EXPECT_EQ("switch (n)\n"
1642             "{\n"
1643             "  case 0:\n"
1644             "    {\n"
1645             "      return false;\n"
1646             "    }\n"
1647             "  case 1:\n"
1648             "    break;\n"
1649             "  default:\n"
1650             "    {\n"
1651             "      return true;\n"
1652             "    }\n"
1653             "}",
1654             format("switch (n) {\n"
1655                    "case 0: {\n"
1656                    "  return false;\n"
1657                    "}\n"
1658                    "case 1:\n"
1659                    "  break;\n"
1660                    "default: {\n"
1661                    "  return true;\n"
1662                    "}\n"
1663                    "}",
1664                    Style));
1665 }
1666 
1667 TEST_F(FormatTest, CaseRanges) {
1668   verifyFormat("switch (x) {\n"
1669                "case 'A' ... 'Z':\n"
1670                "case 1 ... 5:\n"
1671                "case a ... b:\n"
1672                "  break;\n"
1673                "}");
1674 }
1675 
1676 TEST_F(FormatTest, ShortEnums) {
1677   FormatStyle Style = getLLVMStyle();
1678   Style.AllowShortEnumsOnASingleLine = true;
1679   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
1680   Style.AllowShortEnumsOnASingleLine = false;
1681   verifyFormat("enum\n"
1682                "{\n"
1683                "  A,\n"
1684                "  B,\n"
1685                "  C\n"
1686                "} ShortEnum1, ShortEnum2;",
1687                Style);
1688 }
1689 
1690 TEST_F(FormatTest, ShortCaseLabels) {
1691   FormatStyle Style = getLLVMStyle();
1692   Style.AllowShortCaseLabelsOnASingleLine = true;
1693   verifyFormat("switch (a) {\n"
1694                "case 1: x = 1; break;\n"
1695                "case 2: return;\n"
1696                "case 3:\n"
1697                "case 4:\n"
1698                "case 5: return;\n"
1699                "case 6: // comment\n"
1700                "  return;\n"
1701                "case 7:\n"
1702                "  // comment\n"
1703                "  return;\n"
1704                "case 8:\n"
1705                "  x = 8; // comment\n"
1706                "  break;\n"
1707                "default: y = 1; break;\n"
1708                "}",
1709                Style);
1710   verifyFormat("switch (a) {\n"
1711                "case 0: return; // comment\n"
1712                "case 1: break;  // comment\n"
1713                "case 2: return;\n"
1714                "// comment\n"
1715                "case 3: return;\n"
1716                "// comment 1\n"
1717                "// comment 2\n"
1718                "// comment 3\n"
1719                "case 4: break; /* comment */\n"
1720                "case 5:\n"
1721                "  // comment\n"
1722                "  break;\n"
1723                "case 6: /* comment */ x = 1; break;\n"
1724                "case 7: x = /* comment */ 1; break;\n"
1725                "case 8:\n"
1726                "  x = 1; /* comment */\n"
1727                "  break;\n"
1728                "case 9:\n"
1729                "  break; // comment line 1\n"
1730                "         // comment line 2\n"
1731                "}",
1732                Style);
1733   EXPECT_EQ("switch (a) {\n"
1734             "case 1:\n"
1735             "  x = 8;\n"
1736             "  // fall through\n"
1737             "case 2: x = 8;\n"
1738             "// comment\n"
1739             "case 3:\n"
1740             "  return; /* comment line 1\n"
1741             "           * comment line 2 */\n"
1742             "case 4: i = 8;\n"
1743             "// something else\n"
1744             "#if FOO\n"
1745             "case 5: break;\n"
1746             "#endif\n"
1747             "}",
1748             format("switch (a) {\n"
1749                    "case 1: x = 8;\n"
1750                    "  // fall through\n"
1751                    "case 2:\n"
1752                    "  x = 8;\n"
1753                    "// comment\n"
1754                    "case 3:\n"
1755                    "  return; /* comment line 1\n"
1756                    "           * comment line 2 */\n"
1757                    "case 4:\n"
1758                    "  i = 8;\n"
1759                    "// something else\n"
1760                    "#if FOO\n"
1761                    "case 5: break;\n"
1762                    "#endif\n"
1763                    "}",
1764                    Style));
1765   EXPECT_EQ("switch (a) {\n"
1766             "case 0:\n"
1767             "  return; // long long long long long long long long long long "
1768             "long long comment\n"
1769             "          // line\n"
1770             "}",
1771             format("switch (a) {\n"
1772                    "case 0: return; // long long long long long long long long "
1773                    "long long long long comment line\n"
1774                    "}",
1775                    Style));
1776   EXPECT_EQ("switch (a) {\n"
1777             "case 0:\n"
1778             "  return; /* long long long long long long long long long long "
1779             "long long comment\n"
1780             "             line */\n"
1781             "}",
1782             format("switch (a) {\n"
1783                    "case 0: return; /* long long long long long long long long "
1784                    "long long long long comment line */\n"
1785                    "}",
1786                    Style));
1787   verifyFormat("switch (a) {\n"
1788                "#if FOO\n"
1789                "case 0: return 0;\n"
1790                "#endif\n"
1791                "}",
1792                Style);
1793   verifyFormat("switch (a) {\n"
1794                "case 1: {\n"
1795                "}\n"
1796                "case 2: {\n"
1797                "  return;\n"
1798                "}\n"
1799                "case 3: {\n"
1800                "  x = 1;\n"
1801                "  return;\n"
1802                "}\n"
1803                "case 4:\n"
1804                "  if (x)\n"
1805                "    return;\n"
1806                "}",
1807                Style);
1808   Style.ColumnLimit = 21;
1809   verifyFormat("switch (a) {\n"
1810                "case 1: x = 1; break;\n"
1811                "case 2: return;\n"
1812                "case 3:\n"
1813                "case 4:\n"
1814                "case 5: return;\n"
1815                "default:\n"
1816                "  y = 1;\n"
1817                "  break;\n"
1818                "}",
1819                Style);
1820   Style.ColumnLimit = 80;
1821   Style.AllowShortCaseLabelsOnASingleLine = false;
1822   Style.IndentCaseLabels = true;
1823   EXPECT_EQ("switch (n) {\n"
1824             "  default /*comments*/:\n"
1825             "    return true;\n"
1826             "  case 0:\n"
1827             "    return false;\n"
1828             "}",
1829             format("switch (n) {\n"
1830                    "default/*comments*/:\n"
1831                    "  return true;\n"
1832                    "case 0:\n"
1833                    "  return false;\n"
1834                    "}",
1835                    Style));
1836   Style.AllowShortCaseLabelsOnASingleLine = true;
1837   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1838   Style.BraceWrapping.AfterCaseLabel = true;
1839   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1840   EXPECT_EQ("switch (n)\n"
1841             "{\n"
1842             "  case 0:\n"
1843             "  {\n"
1844             "    return false;\n"
1845             "  }\n"
1846             "  default:\n"
1847             "  {\n"
1848             "    return true;\n"
1849             "  }\n"
1850             "}",
1851             format("switch (n) {\n"
1852                    "  case 0: {\n"
1853                    "    return false;\n"
1854                    "  }\n"
1855                    "  default:\n"
1856                    "  {\n"
1857                    "    return true;\n"
1858                    "  }\n"
1859                    "}",
1860                    Style));
1861 }
1862 
1863 TEST_F(FormatTest, FormatsLabels) {
1864   verifyFormat("void f() {\n"
1865                "  some_code();\n"
1866                "test_label:\n"
1867                "  some_other_code();\n"
1868                "  {\n"
1869                "    some_more_code();\n"
1870                "  another_label:\n"
1871                "    some_more_code();\n"
1872                "  }\n"
1873                "}");
1874   verifyFormat("{\n"
1875                "  some_code();\n"
1876                "test_label:\n"
1877                "  some_other_code();\n"
1878                "}");
1879   verifyFormat("{\n"
1880                "  some_code();\n"
1881                "test_label:;\n"
1882                "  int i = 0;\n"
1883                "}");
1884   FormatStyle Style = getLLVMStyle();
1885   Style.IndentGotoLabels = false;
1886   verifyFormat("void f() {\n"
1887                "  some_code();\n"
1888                "test_label:\n"
1889                "  some_other_code();\n"
1890                "  {\n"
1891                "    some_more_code();\n"
1892                "another_label:\n"
1893                "    some_more_code();\n"
1894                "  }\n"
1895                "}",
1896                Style);
1897   verifyFormat("{\n"
1898                "  some_code();\n"
1899                "test_label:\n"
1900                "  some_other_code();\n"
1901                "}",
1902                Style);
1903   verifyFormat("{\n"
1904                "  some_code();\n"
1905                "test_label:;\n"
1906                "  int i = 0;\n"
1907                "}");
1908 }
1909 
1910 TEST_F(FormatTest, MultiLineControlStatements) {
1911   FormatStyle Style = getLLVMStyle();
1912   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
1913   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
1914   Style.ColumnLimit = 20;
1915   // Short lines should keep opening brace on same line.
1916   EXPECT_EQ("if (foo) {\n"
1917             "  bar();\n"
1918             "}",
1919             format("if(foo){bar();}", Style));
1920   EXPECT_EQ("if (foo) {\n"
1921             "  bar();\n"
1922             "} else {\n"
1923             "  baz();\n"
1924             "}",
1925             format("if(foo){bar();}else{baz();}", Style));
1926   EXPECT_EQ("if (foo && bar) {\n"
1927             "  baz();\n"
1928             "}",
1929             format("if(foo&&bar){baz();}", Style));
1930   EXPECT_EQ("if (foo) {\n"
1931             "  bar();\n"
1932             "} else if (baz) {\n"
1933             "  quux();\n"
1934             "}",
1935             format("if(foo){bar();}else if(baz){quux();}", Style));
1936   EXPECT_EQ(
1937       "if (foo) {\n"
1938       "  bar();\n"
1939       "} else if (baz) {\n"
1940       "  quux();\n"
1941       "} else {\n"
1942       "  foobar();\n"
1943       "}",
1944       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
1945   EXPECT_EQ("for (;;) {\n"
1946             "  foo();\n"
1947             "}",
1948             format("for(;;){foo();}"));
1949   EXPECT_EQ("while (1) {\n"
1950             "  foo();\n"
1951             "}",
1952             format("while(1){foo();}", Style));
1953   EXPECT_EQ("switch (foo) {\n"
1954             "case bar:\n"
1955             "  return;\n"
1956             "}",
1957             format("switch(foo){case bar:return;}", Style));
1958   EXPECT_EQ("try {\n"
1959             "  foo();\n"
1960             "} catch (...) {\n"
1961             "  bar();\n"
1962             "}",
1963             format("try{foo();}catch(...){bar();}", Style));
1964   EXPECT_EQ("do {\n"
1965             "  foo();\n"
1966             "} while (bar &&\n"
1967             "         baz);",
1968             format("do{foo();}while(bar&&baz);", Style));
1969   // Long lines should put opening brace on new line.
1970   EXPECT_EQ("if (foo && bar &&\n"
1971             "    baz)\n"
1972             "{\n"
1973             "  quux();\n"
1974             "}",
1975             format("if(foo&&bar&&baz){quux();}", Style));
1976   EXPECT_EQ("if (foo && bar &&\n"
1977             "    baz)\n"
1978             "{\n"
1979             "  quux();\n"
1980             "}",
1981             format("if (foo && bar &&\n"
1982                    "    baz) {\n"
1983                    "  quux();\n"
1984                    "}",
1985                    Style));
1986   EXPECT_EQ("if (foo) {\n"
1987             "  bar();\n"
1988             "} else if (baz ||\n"
1989             "           quux)\n"
1990             "{\n"
1991             "  foobar();\n"
1992             "}",
1993             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
1994   EXPECT_EQ(
1995       "if (foo) {\n"
1996       "  bar();\n"
1997       "} else if (baz ||\n"
1998       "           quux)\n"
1999       "{\n"
2000       "  foobar();\n"
2001       "} else {\n"
2002       "  barbaz();\n"
2003       "}",
2004       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2005              Style));
2006   EXPECT_EQ("for (int i = 0;\n"
2007             "     i < 10; ++i)\n"
2008             "{\n"
2009             "  foo();\n"
2010             "}",
2011             format("for(int i=0;i<10;++i){foo();}", Style));
2012   EXPECT_EQ("foreach (int i,\n"
2013             "         list)\n"
2014             "{\n"
2015             "  foo();\n"
2016             "}",
2017             format("foreach(int i, list){foo();}", Style));
2018   Style.ColumnLimit =
2019       40; // to concentrate at brace wrapping, not line wrap due to column limit
2020   EXPECT_EQ("foreach (int i, list) {\n"
2021             "  foo();\n"
2022             "}",
2023             format("foreach(int i, list){foo();}", Style));
2024   Style.ColumnLimit =
2025       20; // to concentrate at brace wrapping, not line wrap due to column limit
2026   EXPECT_EQ("while (foo || bar ||\n"
2027             "       baz)\n"
2028             "{\n"
2029             "  quux();\n"
2030             "}",
2031             format("while(foo||bar||baz){quux();}", Style));
2032   EXPECT_EQ("switch (\n"
2033             "    foo = barbaz)\n"
2034             "{\n"
2035             "case quux:\n"
2036             "  return;\n"
2037             "}",
2038             format("switch(foo=barbaz){case quux:return;}", Style));
2039   EXPECT_EQ("try {\n"
2040             "  foo();\n"
2041             "} catch (\n"
2042             "    Exception &bar)\n"
2043             "{\n"
2044             "  baz();\n"
2045             "}",
2046             format("try{foo();}catch(Exception&bar){baz();}", Style));
2047   Style.ColumnLimit =
2048       40; // to concentrate at brace wrapping, not line wrap due to column limit
2049   EXPECT_EQ("try {\n"
2050             "  foo();\n"
2051             "} catch (Exception &bar) {\n"
2052             "  baz();\n"
2053             "}",
2054             format("try{foo();}catch(Exception&bar){baz();}", Style));
2055   Style.ColumnLimit =
2056       20; // to concentrate at brace wrapping, not line wrap due to column limit
2057 
2058   Style.BraceWrapping.BeforeElse = true;
2059   EXPECT_EQ(
2060       "if (foo) {\n"
2061       "  bar();\n"
2062       "}\n"
2063       "else if (baz ||\n"
2064       "         quux)\n"
2065       "{\n"
2066       "  foobar();\n"
2067       "}\n"
2068       "else {\n"
2069       "  barbaz();\n"
2070       "}",
2071       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2072              Style));
2073 
2074   Style.BraceWrapping.BeforeCatch = true;
2075   EXPECT_EQ("try {\n"
2076             "  foo();\n"
2077             "}\n"
2078             "catch (...) {\n"
2079             "  baz();\n"
2080             "}",
2081             format("try{foo();}catch(...){baz();}", Style));
2082 }
2083 
2084 TEST_F(FormatTest, BeforeWhile) {
2085   FormatStyle Style = getLLVMStyle();
2086   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2087 
2088   verifyFormat("do {\n"
2089                "  foo();\n"
2090                "} while (1);",
2091                Style);
2092   Style.BraceWrapping.BeforeWhile = true;
2093   verifyFormat("do {\n"
2094                "  foo();\n"
2095                "}\n"
2096                "while (1);",
2097                Style);
2098 }
2099 
2100 //===----------------------------------------------------------------------===//
2101 // Tests for classes, namespaces, etc.
2102 //===----------------------------------------------------------------------===//
2103 
2104 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
2105   verifyFormat("class A {};");
2106 }
2107 
2108 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
2109   verifyFormat("class A {\n"
2110                "public:\n"
2111                "public: // comment\n"
2112                "protected:\n"
2113                "private:\n"
2114                "  void f() {}\n"
2115                "};");
2116   verifyFormat("export class A {\n"
2117                "public:\n"
2118                "public: // comment\n"
2119                "protected:\n"
2120                "private:\n"
2121                "  void f() {}\n"
2122                "};");
2123   verifyGoogleFormat("class A {\n"
2124                      " public:\n"
2125                      " protected:\n"
2126                      " private:\n"
2127                      "  void f() {}\n"
2128                      "};");
2129   verifyGoogleFormat("export class A {\n"
2130                      " public:\n"
2131                      " protected:\n"
2132                      " private:\n"
2133                      "  void f() {}\n"
2134                      "};");
2135   verifyFormat("class A {\n"
2136                "public slots:\n"
2137                "  void f1() {}\n"
2138                "public Q_SLOTS:\n"
2139                "  void f2() {}\n"
2140                "protected slots:\n"
2141                "  void f3() {}\n"
2142                "protected Q_SLOTS:\n"
2143                "  void f4() {}\n"
2144                "private slots:\n"
2145                "  void f5() {}\n"
2146                "private Q_SLOTS:\n"
2147                "  void f6() {}\n"
2148                "signals:\n"
2149                "  void g1();\n"
2150                "Q_SIGNALS:\n"
2151                "  void g2();\n"
2152                "};");
2153 
2154   // Don't interpret 'signals' the wrong way.
2155   verifyFormat("signals.set();");
2156   verifyFormat("for (Signals signals : f()) {\n}");
2157   verifyFormat("{\n"
2158                "  signals.set(); // This needs indentation.\n"
2159                "}");
2160   verifyFormat("void f() {\n"
2161                "label:\n"
2162                "  signals.baz();\n"
2163                "}");
2164 }
2165 
2166 TEST_F(FormatTest, SeparatesLogicalBlocks) {
2167   EXPECT_EQ("class A {\n"
2168             "public:\n"
2169             "  void f();\n"
2170             "\n"
2171             "private:\n"
2172             "  void g() {}\n"
2173             "  // test\n"
2174             "protected:\n"
2175             "  int h;\n"
2176             "};",
2177             format("class A {\n"
2178                    "public:\n"
2179                    "void f();\n"
2180                    "private:\n"
2181                    "void g() {}\n"
2182                    "// test\n"
2183                    "protected:\n"
2184                    "int h;\n"
2185                    "};"));
2186   EXPECT_EQ("class A {\n"
2187             "protected:\n"
2188             "public:\n"
2189             "  void f();\n"
2190             "};",
2191             format("class A {\n"
2192                    "protected:\n"
2193                    "\n"
2194                    "public:\n"
2195                    "\n"
2196                    "  void f();\n"
2197                    "};"));
2198 
2199   // Even ensure proper spacing inside macros.
2200   EXPECT_EQ("#define B     \\\n"
2201             "  class A {   \\\n"
2202             "   protected: \\\n"
2203             "   public:    \\\n"
2204             "    void f(); \\\n"
2205             "  };",
2206             format("#define B     \\\n"
2207                    "  class A {   \\\n"
2208                    "   protected: \\\n"
2209                    "              \\\n"
2210                    "   public:    \\\n"
2211                    "              \\\n"
2212                    "    void f(); \\\n"
2213                    "  };",
2214                    getGoogleStyle()));
2215   // But don't remove empty lines after macros ending in access specifiers.
2216   EXPECT_EQ("#define A private:\n"
2217             "\n"
2218             "int i;",
2219             format("#define A         private:\n"
2220                    "\n"
2221                    "int              i;"));
2222 }
2223 
2224 TEST_F(FormatTest, FormatsClasses) {
2225   verifyFormat("class A : public B {};");
2226   verifyFormat("class A : public ::B {};");
2227 
2228   verifyFormat(
2229       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
2230       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
2231   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
2232                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
2233                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
2234   verifyFormat(
2235       "class A : public B, public C, public D, public E, public F {};");
2236   verifyFormat("class AAAAAAAAAAAA : public B,\n"
2237                "                     public C,\n"
2238                "                     public D,\n"
2239                "                     public E,\n"
2240                "                     public F,\n"
2241                "                     public G {};");
2242 
2243   verifyFormat("class\n"
2244                "    ReallyReallyLongClassName {\n"
2245                "  int i;\n"
2246                "};",
2247                getLLVMStyleWithColumns(32));
2248   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
2249                "                           aaaaaaaaaaaaaaaa> {};");
2250   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
2251                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
2252                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
2253   verifyFormat("template <class R, class C>\n"
2254                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
2255                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
2256   verifyFormat("class ::A::B {};");
2257 }
2258 
2259 TEST_F(FormatTest, BreakInheritanceStyle) {
2260   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
2261   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
2262       FormatStyle::BILS_BeforeComma;
2263   verifyFormat("class MyClass : public X {};",
2264                StyleWithInheritanceBreakBeforeComma);
2265   verifyFormat("class MyClass\n"
2266                "    : public X\n"
2267                "    , public Y {};",
2268                StyleWithInheritanceBreakBeforeComma);
2269   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
2270                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
2271                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
2272                StyleWithInheritanceBreakBeforeComma);
2273   verifyFormat("struct aaaaaaaaaaaaa\n"
2274                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
2275                "          aaaaaaaaaaaaaaaa> {};",
2276                StyleWithInheritanceBreakBeforeComma);
2277 
2278   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
2279   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
2280       FormatStyle::BILS_AfterColon;
2281   verifyFormat("class MyClass : public X {};",
2282                StyleWithInheritanceBreakAfterColon);
2283   verifyFormat("class MyClass : public X, public Y {};",
2284                StyleWithInheritanceBreakAfterColon);
2285   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
2286                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
2287                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
2288                StyleWithInheritanceBreakAfterColon);
2289   verifyFormat("struct aaaaaaaaaaaaa :\n"
2290                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
2291                "        aaaaaaaaaaaaaaaa> {};",
2292                StyleWithInheritanceBreakAfterColon);
2293 
2294   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
2295   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
2296       FormatStyle::BILS_AfterComma;
2297   verifyFormat("class MyClass : public X {};",
2298                StyleWithInheritanceBreakAfterComma);
2299   verifyFormat("class MyClass : public X,\n"
2300                "                public Y {};",
2301                StyleWithInheritanceBreakAfterComma);
2302   verifyFormat(
2303       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
2304       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
2305       "{};",
2306       StyleWithInheritanceBreakAfterComma);
2307   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
2308                "                           aaaaaaaaaaaaaaaa> {};",
2309                StyleWithInheritanceBreakAfterComma);
2310   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
2311                "    : public OnceBreak,\n"
2312                "      public AlwaysBreak,\n"
2313                "      EvenBasesFitInOneLine {};",
2314                StyleWithInheritanceBreakAfterComma);
2315 }
2316 
2317 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
2318   verifyFormat("class A {\n} a, b;");
2319   verifyFormat("struct A {\n} a, b;");
2320   verifyFormat("union A {\n} a;");
2321 }
2322 
2323 TEST_F(FormatTest, FormatsEnum) {
2324   verifyFormat("enum {\n"
2325                "  Zero,\n"
2326                "  One = 1,\n"
2327                "  Two = One + 1,\n"
2328                "  Three = (One + Two),\n"
2329                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2330                "  Five = (One, Two, Three, Four, 5)\n"
2331                "};");
2332   verifyGoogleFormat("enum {\n"
2333                      "  Zero,\n"
2334                      "  One = 1,\n"
2335                      "  Two = One + 1,\n"
2336                      "  Three = (One + Two),\n"
2337                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2338                      "  Five = (One, Two, Three, Four, 5)\n"
2339                      "};");
2340   verifyFormat("enum Enum {};");
2341   verifyFormat("enum {};");
2342   verifyFormat("enum X E {} d;");
2343   verifyFormat("enum __attribute__((...)) E {} d;");
2344   verifyFormat("enum __declspec__((...)) E {} d;");
2345   verifyFormat("enum {\n"
2346                "  Bar = Foo<int, int>::value\n"
2347                "};",
2348                getLLVMStyleWithColumns(30));
2349 
2350   verifyFormat("enum ShortEnum { A, B, C };");
2351   verifyGoogleFormat("enum ShortEnum { A, B, C };");
2352 
2353   EXPECT_EQ("enum KeepEmptyLines {\n"
2354             "  ONE,\n"
2355             "\n"
2356             "  TWO,\n"
2357             "\n"
2358             "  THREE\n"
2359             "}",
2360             format("enum KeepEmptyLines {\n"
2361                    "  ONE,\n"
2362                    "\n"
2363                    "  TWO,\n"
2364                    "\n"
2365                    "\n"
2366                    "  THREE\n"
2367                    "}"));
2368   verifyFormat("enum E { // comment\n"
2369                "  ONE,\n"
2370                "  TWO\n"
2371                "};\n"
2372                "int i;");
2373 
2374   FormatStyle EightIndent = getLLVMStyle();
2375   EightIndent.IndentWidth = 8;
2376   verifyFormat("enum {\n"
2377                "        VOID,\n"
2378                "        CHAR,\n"
2379                "        SHORT,\n"
2380                "        INT,\n"
2381                "        LONG,\n"
2382                "        SIGNED,\n"
2383                "        UNSIGNED,\n"
2384                "        BOOL,\n"
2385                "        FLOAT,\n"
2386                "        DOUBLE,\n"
2387                "        COMPLEX\n"
2388                "};",
2389                EightIndent);
2390 
2391   // Not enums.
2392   verifyFormat("enum X f() {\n"
2393                "  a();\n"
2394                "  return 42;\n"
2395                "}");
2396   verifyFormat("enum X Type::f() {\n"
2397                "  a();\n"
2398                "  return 42;\n"
2399                "}");
2400   verifyFormat("enum ::X f() {\n"
2401                "  a();\n"
2402                "  return 42;\n"
2403                "}");
2404   verifyFormat("enum ns::X f() {\n"
2405                "  a();\n"
2406                "  return 42;\n"
2407                "}");
2408 }
2409 
2410 TEST_F(FormatTest, FormatsEnumsWithErrors) {
2411   verifyFormat("enum Type {\n"
2412                "  One = 0; // These semicolons should be commas.\n"
2413                "  Two = 1;\n"
2414                "};");
2415   verifyFormat("namespace n {\n"
2416                "enum Type {\n"
2417                "  One,\n"
2418                "  Two, // missing };\n"
2419                "  int i;\n"
2420                "}\n"
2421                "void g() {}");
2422 }
2423 
2424 TEST_F(FormatTest, FormatsEnumStruct) {
2425   verifyFormat("enum struct {\n"
2426                "  Zero,\n"
2427                "  One = 1,\n"
2428                "  Two = One + 1,\n"
2429                "  Three = (One + Two),\n"
2430                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2431                "  Five = (One, Two, Three, Four, 5)\n"
2432                "};");
2433   verifyFormat("enum struct Enum {};");
2434   verifyFormat("enum struct {};");
2435   verifyFormat("enum struct X E {} d;");
2436   verifyFormat("enum struct __attribute__((...)) E {} d;");
2437   verifyFormat("enum struct __declspec__((...)) E {} d;");
2438   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
2439 }
2440 
2441 TEST_F(FormatTest, FormatsEnumClass) {
2442   verifyFormat("enum class {\n"
2443                "  Zero,\n"
2444                "  One = 1,\n"
2445                "  Two = One + 1,\n"
2446                "  Three = (One + Two),\n"
2447                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2448                "  Five = (One, Two, Three, Four, 5)\n"
2449                "};");
2450   verifyFormat("enum class Enum {};");
2451   verifyFormat("enum class {};");
2452   verifyFormat("enum class X E {} d;");
2453   verifyFormat("enum class __attribute__((...)) E {} d;");
2454   verifyFormat("enum class __declspec__((...)) E {} d;");
2455   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
2456 }
2457 
2458 TEST_F(FormatTest, FormatsEnumTypes) {
2459   verifyFormat("enum X : int {\n"
2460                "  A, // Force multiple lines.\n"
2461                "  B\n"
2462                "};");
2463   verifyFormat("enum X : int { A, B };");
2464   verifyFormat("enum X : std::uint32_t { A, B };");
2465 }
2466 
2467 TEST_F(FormatTest, FormatsTypedefEnum) {
2468   FormatStyle Style = getLLVMStyle();
2469   Style.ColumnLimit = 40;
2470   verifyFormat("typedef enum {} EmptyEnum;");
2471   verifyFormat("typedef enum { A, B, C } ShortEnum;");
2472   verifyFormat("typedef enum {\n"
2473                "  ZERO = 0,\n"
2474                "  ONE = 1,\n"
2475                "  TWO = 2,\n"
2476                "  THREE = 3\n"
2477                "} LongEnum;",
2478                Style);
2479   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2480   Style.BraceWrapping.AfterEnum = true;
2481   verifyFormat("typedef enum {} EmptyEnum;");
2482   verifyFormat("typedef enum { A, B, C } ShortEnum;");
2483   verifyFormat("typedef enum\n"
2484                "{\n"
2485                "  ZERO = 0,\n"
2486                "  ONE = 1,\n"
2487                "  TWO = 2,\n"
2488                "  THREE = 3\n"
2489                "} LongEnum;",
2490                Style);
2491 }
2492 
2493 TEST_F(FormatTest, FormatsNSEnums) {
2494   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
2495   verifyGoogleFormat(
2496       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
2497   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
2498                      "  // Information about someDecentlyLongValue.\n"
2499                      "  someDecentlyLongValue,\n"
2500                      "  // Information about anotherDecentlyLongValue.\n"
2501                      "  anotherDecentlyLongValue,\n"
2502                      "  // Information about aThirdDecentlyLongValue.\n"
2503                      "  aThirdDecentlyLongValue\n"
2504                      "};");
2505   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
2506                      "  // Information about someDecentlyLongValue.\n"
2507                      "  someDecentlyLongValue,\n"
2508                      "  // Information about anotherDecentlyLongValue.\n"
2509                      "  anotherDecentlyLongValue,\n"
2510                      "  // Information about aThirdDecentlyLongValue.\n"
2511                      "  aThirdDecentlyLongValue\n"
2512                      "};");
2513   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
2514                      "  a = 1,\n"
2515                      "  b = 2,\n"
2516                      "  c = 3,\n"
2517                      "};");
2518   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
2519                      "  a = 1,\n"
2520                      "  b = 2,\n"
2521                      "  c = 3,\n"
2522                      "};");
2523   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
2524                      "  a = 1,\n"
2525                      "  b = 2,\n"
2526                      "  c = 3,\n"
2527                      "};");
2528   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
2529                      "  a = 1,\n"
2530                      "  b = 2,\n"
2531                      "  c = 3,\n"
2532                      "};");
2533 }
2534 
2535 TEST_F(FormatTest, FormatsBitfields) {
2536   verifyFormat("struct Bitfields {\n"
2537                "  unsigned sClass : 8;\n"
2538                "  unsigned ValueKind : 2;\n"
2539                "};");
2540   verifyFormat("struct A {\n"
2541                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
2542                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
2543                "};");
2544   verifyFormat("struct MyStruct {\n"
2545                "  uchar data;\n"
2546                "  uchar : 8;\n"
2547                "  uchar : 8;\n"
2548                "  uchar other;\n"
2549                "};");
2550   FormatStyle Style = getLLVMStyle();
2551   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
2552   verifyFormat("struct Bitfields {\n"
2553                "  unsigned sClass:8;\n"
2554                "  unsigned ValueKind:2;\n"
2555                "  uchar other;\n"
2556                "};",
2557                Style);
2558   verifyFormat("struct A {\n"
2559                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
2560                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
2561                "};",
2562                Style);
2563   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
2564   verifyFormat("struct Bitfields {\n"
2565                "  unsigned sClass :8;\n"
2566                "  unsigned ValueKind :2;\n"
2567                "  uchar other;\n"
2568                "};",
2569                Style);
2570   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
2571   verifyFormat("struct Bitfields {\n"
2572                "  unsigned sClass: 8;\n"
2573                "  unsigned ValueKind: 2;\n"
2574                "  uchar other;\n"
2575                "};",
2576                Style);
2577 }
2578 
2579 TEST_F(FormatTest, FormatsNamespaces) {
2580   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
2581   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
2582 
2583   verifyFormat("namespace some_namespace {\n"
2584                "class A {};\n"
2585                "void f() { f(); }\n"
2586                "}",
2587                LLVMWithNoNamespaceFix);
2588   verifyFormat("namespace N::inline D {\n"
2589                "class A {};\n"
2590                "void f() { f(); }\n"
2591                "}",
2592                LLVMWithNoNamespaceFix);
2593   verifyFormat("namespace N::inline D::E {\n"
2594                "class A {};\n"
2595                "void f() { f(); }\n"
2596                "}",
2597                LLVMWithNoNamespaceFix);
2598   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
2599                "class A {};\n"
2600                "void f() { f(); }\n"
2601                "}",
2602                LLVMWithNoNamespaceFix);
2603   verifyFormat("/* something */ namespace some_namespace {\n"
2604                "class A {};\n"
2605                "void f() { f(); }\n"
2606                "}",
2607                LLVMWithNoNamespaceFix);
2608   verifyFormat("namespace {\n"
2609                "class A {};\n"
2610                "void f() { f(); }\n"
2611                "}",
2612                LLVMWithNoNamespaceFix);
2613   verifyFormat("/* something */ namespace {\n"
2614                "class A {};\n"
2615                "void f() { f(); }\n"
2616                "}",
2617                LLVMWithNoNamespaceFix);
2618   verifyFormat("inline namespace X {\n"
2619                "class A {};\n"
2620                "void f() { f(); }\n"
2621                "}",
2622                LLVMWithNoNamespaceFix);
2623   verifyFormat("/* something */ inline namespace X {\n"
2624                "class A {};\n"
2625                "void f() { f(); }\n"
2626                "}",
2627                LLVMWithNoNamespaceFix);
2628   verifyFormat("export namespace X {\n"
2629                "class A {};\n"
2630                "void f() { f(); }\n"
2631                "}",
2632                LLVMWithNoNamespaceFix);
2633   verifyFormat("using namespace some_namespace;\n"
2634                "class A {};\n"
2635                "void f() { f(); }",
2636                LLVMWithNoNamespaceFix);
2637 
2638   // This code is more common than we thought; if we
2639   // layout this correctly the semicolon will go into
2640   // its own line, which is undesirable.
2641   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
2642   verifyFormat("namespace {\n"
2643                "class A {};\n"
2644                "};",
2645                LLVMWithNoNamespaceFix);
2646 
2647   verifyFormat("namespace {\n"
2648                "int SomeVariable = 0; // comment\n"
2649                "} // namespace",
2650                LLVMWithNoNamespaceFix);
2651   EXPECT_EQ("#ifndef HEADER_GUARD\n"
2652             "#define HEADER_GUARD\n"
2653             "namespace my_namespace {\n"
2654             "int i;\n"
2655             "} // my_namespace\n"
2656             "#endif // HEADER_GUARD",
2657             format("#ifndef HEADER_GUARD\n"
2658                    " #define HEADER_GUARD\n"
2659                    "   namespace my_namespace {\n"
2660                    "int i;\n"
2661                    "}    // my_namespace\n"
2662                    "#endif    // HEADER_GUARD",
2663                    LLVMWithNoNamespaceFix));
2664 
2665   EXPECT_EQ("namespace A::B {\n"
2666             "class C {};\n"
2667             "}",
2668             format("namespace A::B {\n"
2669                    "class C {};\n"
2670                    "}",
2671                    LLVMWithNoNamespaceFix));
2672 
2673   FormatStyle Style = getLLVMStyle();
2674   Style.NamespaceIndentation = FormatStyle::NI_All;
2675   EXPECT_EQ("namespace out {\n"
2676             "  int i;\n"
2677             "  namespace in {\n"
2678             "    int i;\n"
2679             "  } // namespace in\n"
2680             "} // namespace out",
2681             format("namespace out {\n"
2682                    "int i;\n"
2683                    "namespace in {\n"
2684                    "int i;\n"
2685                    "} // namespace in\n"
2686                    "} // namespace out",
2687                    Style));
2688 
2689   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2690   EXPECT_EQ("namespace out {\n"
2691             "int i;\n"
2692             "namespace in {\n"
2693             "  int i;\n"
2694             "} // namespace in\n"
2695             "} // namespace out",
2696             format("namespace out {\n"
2697                    "int i;\n"
2698                    "namespace in {\n"
2699                    "int i;\n"
2700                    "} // namespace in\n"
2701                    "} // namespace out",
2702                    Style));
2703 }
2704 
2705 TEST_F(FormatTest, NamespaceMacros) {
2706   FormatStyle Style = getLLVMStyle();
2707   Style.NamespaceMacros.push_back("TESTSUITE");
2708 
2709   verifyFormat("TESTSUITE(A) {\n"
2710                "int foo();\n"
2711                "} // TESTSUITE(A)",
2712                Style);
2713 
2714   verifyFormat("TESTSUITE(A, B) {\n"
2715                "int foo();\n"
2716                "} // TESTSUITE(A)",
2717                Style);
2718 
2719   // Properly indent according to NamespaceIndentation style
2720   Style.NamespaceIndentation = FormatStyle::NI_All;
2721   verifyFormat("TESTSUITE(A) {\n"
2722                "  int foo();\n"
2723                "} // TESTSUITE(A)",
2724                Style);
2725   verifyFormat("TESTSUITE(A) {\n"
2726                "  namespace B {\n"
2727                "    int foo();\n"
2728                "  } // namespace B\n"
2729                "} // TESTSUITE(A)",
2730                Style);
2731   verifyFormat("namespace A {\n"
2732                "  TESTSUITE(B) {\n"
2733                "    int foo();\n"
2734                "  } // TESTSUITE(B)\n"
2735                "} // namespace A",
2736                Style);
2737 
2738   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2739   verifyFormat("TESTSUITE(A) {\n"
2740                "TESTSUITE(B) {\n"
2741                "  int foo();\n"
2742                "} // TESTSUITE(B)\n"
2743                "} // TESTSUITE(A)",
2744                Style);
2745   verifyFormat("TESTSUITE(A) {\n"
2746                "namespace B {\n"
2747                "  int foo();\n"
2748                "} // namespace B\n"
2749                "} // TESTSUITE(A)",
2750                Style);
2751   verifyFormat("namespace A {\n"
2752                "TESTSUITE(B) {\n"
2753                "  int foo();\n"
2754                "} // TESTSUITE(B)\n"
2755                "} // namespace A",
2756                Style);
2757 
2758   // Properly merge namespace-macros blocks in CompactNamespaces mode
2759   Style.NamespaceIndentation = FormatStyle::NI_None;
2760   Style.CompactNamespaces = true;
2761   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
2762                "}} // TESTSUITE(A::B)",
2763                Style);
2764 
2765   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2766             "}} // TESTSUITE(out::in)",
2767             format("TESTSUITE(out) {\n"
2768                    "TESTSUITE(in) {\n"
2769                    "} // TESTSUITE(in)\n"
2770                    "} // TESTSUITE(out)",
2771                    Style));
2772 
2773   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2774             "}} // TESTSUITE(out::in)",
2775             format("TESTSUITE(out) {\n"
2776                    "TESTSUITE(in) {\n"
2777                    "} // TESTSUITE(in)\n"
2778                    "} // TESTSUITE(out)",
2779                    Style));
2780 
2781   // Do not merge different namespaces/macros
2782   EXPECT_EQ("namespace out {\n"
2783             "TESTSUITE(in) {\n"
2784             "} // TESTSUITE(in)\n"
2785             "} // namespace out",
2786             format("namespace out {\n"
2787                    "TESTSUITE(in) {\n"
2788                    "} // TESTSUITE(in)\n"
2789                    "} // namespace out",
2790                    Style));
2791   EXPECT_EQ("TESTSUITE(out) {\n"
2792             "namespace in {\n"
2793             "} // namespace in\n"
2794             "} // TESTSUITE(out)",
2795             format("TESTSUITE(out) {\n"
2796                    "namespace in {\n"
2797                    "} // namespace in\n"
2798                    "} // TESTSUITE(out)",
2799                    Style));
2800   Style.NamespaceMacros.push_back("FOOBAR");
2801   EXPECT_EQ("TESTSUITE(out) {\n"
2802             "FOOBAR(in) {\n"
2803             "} // FOOBAR(in)\n"
2804             "} // TESTSUITE(out)",
2805             format("TESTSUITE(out) {\n"
2806                    "FOOBAR(in) {\n"
2807                    "} // FOOBAR(in)\n"
2808                    "} // TESTSUITE(out)",
2809                    Style));
2810 }
2811 
2812 TEST_F(FormatTest, FormatsCompactNamespaces) {
2813   FormatStyle Style = getLLVMStyle();
2814   Style.CompactNamespaces = true;
2815   Style.NamespaceMacros.push_back("TESTSUITE");
2816 
2817   verifyFormat("namespace A { namespace B {\n"
2818                "}} // namespace A::B",
2819                Style);
2820 
2821   EXPECT_EQ("namespace out { namespace in {\n"
2822             "}} // namespace out::in",
2823             format("namespace out {\n"
2824                    "namespace in {\n"
2825                    "} // namespace in\n"
2826                    "} // namespace out",
2827                    Style));
2828 
2829   // Only namespaces which have both consecutive opening and end get compacted
2830   EXPECT_EQ("namespace out {\n"
2831             "namespace in1 {\n"
2832             "} // namespace in1\n"
2833             "namespace in2 {\n"
2834             "} // namespace in2\n"
2835             "} // namespace out",
2836             format("namespace out {\n"
2837                    "namespace in1 {\n"
2838                    "} // namespace in1\n"
2839                    "namespace in2 {\n"
2840                    "} // namespace in2\n"
2841                    "} // namespace out",
2842                    Style));
2843 
2844   EXPECT_EQ("namespace out {\n"
2845             "int i;\n"
2846             "namespace in {\n"
2847             "int j;\n"
2848             "} // namespace in\n"
2849             "int k;\n"
2850             "} // namespace out",
2851             format("namespace out { int i;\n"
2852                    "namespace in { int j; } // namespace in\n"
2853                    "int k; } // namespace out",
2854                    Style));
2855 
2856   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
2857             "}}} // namespace A::B::C\n",
2858             format("namespace A { namespace B {\n"
2859                    "namespace C {\n"
2860                    "}} // namespace B::C\n"
2861                    "} // namespace A\n",
2862                    Style));
2863 
2864   Style.ColumnLimit = 40;
2865   EXPECT_EQ("namespace aaaaaaaaaa {\n"
2866             "namespace bbbbbbbbbb {\n"
2867             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
2868             format("namespace aaaaaaaaaa {\n"
2869                    "namespace bbbbbbbbbb {\n"
2870                    "} // namespace bbbbbbbbbb\n"
2871                    "} // namespace aaaaaaaaaa",
2872                    Style));
2873 
2874   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
2875             "namespace cccccc {\n"
2876             "}}} // namespace aaaaaa::bbbbbb::cccccc",
2877             format("namespace aaaaaa {\n"
2878                    "namespace bbbbbb {\n"
2879                    "namespace cccccc {\n"
2880                    "} // namespace cccccc\n"
2881                    "} // namespace bbbbbb\n"
2882                    "} // namespace aaaaaa",
2883                    Style));
2884   Style.ColumnLimit = 80;
2885 
2886   // Extra semicolon after 'inner' closing brace prevents merging
2887   EXPECT_EQ("namespace out { namespace in {\n"
2888             "}; } // namespace out::in",
2889             format("namespace out {\n"
2890                    "namespace in {\n"
2891                    "}; // namespace in\n"
2892                    "} // namespace out",
2893                    Style));
2894 
2895   // Extra semicolon after 'outer' closing brace is conserved
2896   EXPECT_EQ("namespace out { namespace in {\n"
2897             "}}; // namespace out::in",
2898             format("namespace out {\n"
2899                    "namespace in {\n"
2900                    "} // namespace in\n"
2901                    "}; // namespace out",
2902                    Style));
2903 
2904   Style.NamespaceIndentation = FormatStyle::NI_All;
2905   EXPECT_EQ("namespace out { namespace in {\n"
2906             "  int i;\n"
2907             "}} // namespace out::in",
2908             format("namespace out {\n"
2909                    "namespace in {\n"
2910                    "int i;\n"
2911                    "} // namespace in\n"
2912                    "} // namespace out",
2913                    Style));
2914   EXPECT_EQ("namespace out { namespace mid {\n"
2915             "  namespace in {\n"
2916             "    int j;\n"
2917             "  } // namespace in\n"
2918             "  int k;\n"
2919             "}} // namespace out::mid",
2920             format("namespace out { namespace mid {\n"
2921                    "namespace in { int j; } // namespace in\n"
2922                    "int k; }} // namespace out::mid",
2923                    Style));
2924 
2925   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2926   EXPECT_EQ("namespace out { namespace in {\n"
2927             "  int i;\n"
2928             "}} // namespace out::in",
2929             format("namespace out {\n"
2930                    "namespace in {\n"
2931                    "int i;\n"
2932                    "} // namespace in\n"
2933                    "} // namespace out",
2934                    Style));
2935   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
2936             "  int i;\n"
2937             "}}} // namespace out::mid::in",
2938             format("namespace out {\n"
2939                    "namespace mid {\n"
2940                    "namespace in {\n"
2941                    "int i;\n"
2942                    "} // namespace in\n"
2943                    "} // namespace mid\n"
2944                    "} // namespace out",
2945                    Style));
2946 }
2947 
2948 TEST_F(FormatTest, FormatsExternC) {
2949   verifyFormat("extern \"C\" {\nint a;");
2950   verifyFormat("extern \"C\" {}");
2951   verifyFormat("extern \"C\" {\n"
2952                "int foo();\n"
2953                "}");
2954   verifyFormat("extern \"C\" int foo() {}");
2955   verifyFormat("extern \"C\" int foo();");
2956   verifyFormat("extern \"C\" int foo() {\n"
2957                "  int i = 42;\n"
2958                "  return i;\n"
2959                "}");
2960 
2961   FormatStyle Style = getLLVMStyle();
2962   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2963   Style.BraceWrapping.AfterFunction = true;
2964   verifyFormat("extern \"C\" int foo() {}", Style);
2965   verifyFormat("extern \"C\" int foo();", Style);
2966   verifyFormat("extern \"C\" int foo()\n"
2967                "{\n"
2968                "  int i = 42;\n"
2969                "  return i;\n"
2970                "}",
2971                Style);
2972 
2973   Style.BraceWrapping.AfterExternBlock = true;
2974   Style.BraceWrapping.SplitEmptyRecord = false;
2975   verifyFormat("extern \"C\"\n"
2976                "{}",
2977                Style);
2978   verifyFormat("extern \"C\"\n"
2979                "{\n"
2980                "  int foo();\n"
2981                "}",
2982                Style);
2983 }
2984 
2985 TEST_F(FormatTest, IndentExternBlockStyle) {
2986   FormatStyle Style = getLLVMStyle();
2987   Style.IndentWidth = 2;
2988 
2989   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
2990   verifyFormat("extern \"C\" { /*9*/\n}", Style);
2991   verifyFormat("extern \"C\" {\n"
2992                "  int foo10();\n"
2993                "}",
2994                Style);
2995 
2996   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
2997   verifyFormat("extern \"C\" { /*11*/\n}", Style);
2998   verifyFormat("extern \"C\" {\n"
2999                "int foo12();\n"
3000                "}",
3001                Style);
3002 
3003   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
3004   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3005   Style.BraceWrapping.AfterExternBlock = true;
3006   verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
3007   verifyFormat("extern \"C\"\n{\n"
3008                "  int foo14();\n"
3009                "}",
3010                Style);
3011 
3012   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
3013   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3014   Style.BraceWrapping.AfterExternBlock = false;
3015   verifyFormat("extern \"C\" { /*15*/\n}", Style);
3016   verifyFormat("extern \"C\" {\n"
3017                "int foo16();\n"
3018                "}",
3019                Style);
3020 }
3021 
3022 TEST_F(FormatTest, FormatsInlineASM) {
3023   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
3024   verifyFormat("asm(\"nop\" ::: \"memory\");");
3025   verifyFormat(
3026       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
3027       "    \"cpuid\\n\\t\"\n"
3028       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
3029       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
3030       "    : \"a\"(value));");
3031   EXPECT_EQ(
3032       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
3033       "  __asm {\n"
3034       "        mov     edx,[that] // vtable in edx\n"
3035       "        mov     eax,methodIndex\n"
3036       "        call    [edx][eax*4] // stdcall\n"
3037       "  }\n"
3038       "}",
3039       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
3040              "    __asm {\n"
3041              "        mov     edx,[that] // vtable in edx\n"
3042              "        mov     eax,methodIndex\n"
3043              "        call    [edx][eax*4] // stdcall\n"
3044              "    }\n"
3045              "}"));
3046   EXPECT_EQ("_asm {\n"
3047             "  xor eax, eax;\n"
3048             "  cpuid;\n"
3049             "}",
3050             format("_asm {\n"
3051                    "  xor eax, eax;\n"
3052                    "  cpuid;\n"
3053                    "}"));
3054   verifyFormat("void function() {\n"
3055                "  // comment\n"
3056                "  asm(\"\");\n"
3057                "}");
3058   EXPECT_EQ("__asm {\n"
3059             "}\n"
3060             "int i;",
3061             format("__asm   {\n"
3062                    "}\n"
3063                    "int   i;"));
3064 }
3065 
3066 TEST_F(FormatTest, FormatTryCatch) {
3067   verifyFormat("try {\n"
3068                "  throw a * b;\n"
3069                "} catch (int a) {\n"
3070                "  // Do nothing.\n"
3071                "} catch (...) {\n"
3072                "  exit(42);\n"
3073                "}");
3074 
3075   // Function-level try statements.
3076   verifyFormat("int f() try { return 4; } catch (...) {\n"
3077                "  return 5;\n"
3078                "}");
3079   verifyFormat("class A {\n"
3080                "  int a;\n"
3081                "  A() try : a(0) {\n"
3082                "  } catch (...) {\n"
3083                "    throw;\n"
3084                "  }\n"
3085                "};\n");
3086   verifyFormat("class A {\n"
3087                "  int a;\n"
3088                "  A() try : a(0), b{1} {\n"
3089                "  } catch (...) {\n"
3090                "    throw;\n"
3091                "  }\n"
3092                "};\n");
3093   verifyFormat("class A {\n"
3094                "  int a;\n"
3095                "  A() try : a(0), b{1}, c{2} {\n"
3096                "  } catch (...) {\n"
3097                "    throw;\n"
3098                "  }\n"
3099                "};\n");
3100   verifyFormat("class A {\n"
3101                "  int a;\n"
3102                "  A() try : a(0), b{1}, c{2} {\n"
3103                "    { // New scope.\n"
3104                "    }\n"
3105                "  } catch (...) {\n"
3106                "    throw;\n"
3107                "  }\n"
3108                "};\n");
3109 
3110   // Incomplete try-catch blocks.
3111   verifyIncompleteFormat("try {} catch (");
3112 }
3113 
3114 TEST_F(FormatTest, FormatTryAsAVariable) {
3115   verifyFormat("int try;");
3116   verifyFormat("int try, size;");
3117   verifyFormat("try = foo();");
3118   verifyFormat("if (try < size) {\n  return true;\n}");
3119 
3120   verifyFormat("int catch;");
3121   verifyFormat("int catch, size;");
3122   verifyFormat("catch = foo();");
3123   verifyFormat("if (catch < size) {\n  return true;\n}");
3124 
3125   FormatStyle Style = getLLVMStyle();
3126   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3127   Style.BraceWrapping.AfterFunction = true;
3128   Style.BraceWrapping.BeforeCatch = true;
3129   verifyFormat("try {\n"
3130                "  int bar = 1;\n"
3131                "}\n"
3132                "catch (...) {\n"
3133                "  int bar = 1;\n"
3134                "}",
3135                Style);
3136   verifyFormat("#if NO_EX\n"
3137                "try\n"
3138                "#endif\n"
3139                "{\n"
3140                "}\n"
3141                "#if NO_EX\n"
3142                "catch (...) {\n"
3143                "}",
3144                Style);
3145   verifyFormat("try /* abc */ {\n"
3146                "  int bar = 1;\n"
3147                "}\n"
3148                "catch (...) {\n"
3149                "  int bar = 1;\n"
3150                "}",
3151                Style);
3152   verifyFormat("try\n"
3153                "// abc\n"
3154                "{\n"
3155                "  int bar = 1;\n"
3156                "}\n"
3157                "catch (...) {\n"
3158                "  int bar = 1;\n"
3159                "}",
3160                Style);
3161 }
3162 
3163 TEST_F(FormatTest, FormatSEHTryCatch) {
3164   verifyFormat("__try {\n"
3165                "  int a = b * c;\n"
3166                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
3167                "  // Do nothing.\n"
3168                "}");
3169 
3170   verifyFormat("__try {\n"
3171                "  int a = b * c;\n"
3172                "} __finally {\n"
3173                "  // Do nothing.\n"
3174                "}");
3175 
3176   verifyFormat("DEBUG({\n"
3177                "  __try {\n"
3178                "  } __finally {\n"
3179                "  }\n"
3180                "});\n");
3181 }
3182 
3183 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
3184   verifyFormat("try {\n"
3185                "  f();\n"
3186                "} catch {\n"
3187                "  g();\n"
3188                "}");
3189   verifyFormat("try {\n"
3190                "  f();\n"
3191                "} catch (A a) MACRO(x) {\n"
3192                "  g();\n"
3193                "} catch (B b) MACRO(x) {\n"
3194                "  g();\n"
3195                "}");
3196 }
3197 
3198 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
3199   FormatStyle Style = getLLVMStyle();
3200   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
3201                           FormatStyle::BS_WebKit}) {
3202     Style.BreakBeforeBraces = BraceStyle;
3203     verifyFormat("try {\n"
3204                  "  // something\n"
3205                  "} catch (...) {\n"
3206                  "  // something\n"
3207                  "}",
3208                  Style);
3209   }
3210   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
3211   verifyFormat("try {\n"
3212                "  // something\n"
3213                "}\n"
3214                "catch (...) {\n"
3215                "  // something\n"
3216                "}",
3217                Style);
3218   verifyFormat("__try {\n"
3219                "  // something\n"
3220                "}\n"
3221                "__finally {\n"
3222                "  // something\n"
3223                "}",
3224                Style);
3225   verifyFormat("@try {\n"
3226                "  // something\n"
3227                "}\n"
3228                "@finally {\n"
3229                "  // something\n"
3230                "}",
3231                Style);
3232   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
3233   verifyFormat("try\n"
3234                "{\n"
3235                "  // something\n"
3236                "}\n"
3237                "catch (...)\n"
3238                "{\n"
3239                "  // something\n"
3240                "}",
3241                Style);
3242   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
3243   verifyFormat("try\n"
3244                "  {\n"
3245                "  // something white\n"
3246                "  }\n"
3247                "catch (...)\n"
3248                "  {\n"
3249                "  // something white\n"
3250                "  }",
3251                Style);
3252   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
3253   verifyFormat("try\n"
3254                "  {\n"
3255                "    // something\n"
3256                "  }\n"
3257                "catch (...)\n"
3258                "  {\n"
3259                "    // something\n"
3260                "  }",
3261                Style);
3262   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3263   Style.BraceWrapping.BeforeCatch = true;
3264   verifyFormat("try {\n"
3265                "  // something\n"
3266                "}\n"
3267                "catch (...) {\n"
3268                "  // something\n"
3269                "}",
3270                Style);
3271 }
3272 
3273 TEST_F(FormatTest, StaticInitializers) {
3274   verifyFormat("static SomeClass SC = {1, 'a'};");
3275 
3276   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
3277                "    100000000, "
3278                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
3279 
3280   // Here, everything other than the "}" would fit on a line.
3281   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
3282                "    10000000000000000000000000};");
3283   EXPECT_EQ("S s = {a,\n"
3284             "\n"
3285             "       b};",
3286             format("S s = {\n"
3287                    "  a,\n"
3288                    "\n"
3289                    "  b\n"
3290                    "};"));
3291 
3292   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
3293   // line. However, the formatting looks a bit off and this probably doesn't
3294   // happen often in practice.
3295   verifyFormat("static int Variable[1] = {\n"
3296                "    {1000000000000000000000000000000000000}};",
3297                getLLVMStyleWithColumns(40));
3298 }
3299 
3300 TEST_F(FormatTest, DesignatedInitializers) {
3301   verifyFormat("const struct A a = {.a = 1, .b = 2};");
3302   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
3303                "                    .bbbbbbbbbb = 2,\n"
3304                "                    .cccccccccc = 3,\n"
3305                "                    .dddddddddd = 4,\n"
3306                "                    .eeeeeeeeee = 5};");
3307   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
3308                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
3309                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
3310                "    .ccccccccccccccccccccccccccc = 3,\n"
3311                "    .ddddddddddddddddddddddddddd = 4,\n"
3312                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
3313 
3314   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
3315 
3316   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
3317   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
3318                "                    [2] = bbbbbbbbbb,\n"
3319                "                    [3] = cccccccccc,\n"
3320                "                    [4] = dddddddddd,\n"
3321                "                    [5] = eeeeeeeeee};");
3322   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
3323                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3324                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
3325                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
3326                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
3327                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
3328 }
3329 
3330 TEST_F(FormatTest, NestedStaticInitializers) {
3331   verifyFormat("static A x = {{{}}};\n");
3332   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
3333                "               {init1, init2, init3, init4}}};",
3334                getLLVMStyleWithColumns(50));
3335 
3336   verifyFormat("somes Status::global_reps[3] = {\n"
3337                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
3338                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
3339                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
3340                getLLVMStyleWithColumns(60));
3341   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
3342                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
3343                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
3344                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
3345   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
3346                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
3347                "rect.fTop}};");
3348 
3349   verifyFormat(
3350       "SomeArrayOfSomeType a = {\n"
3351       "    {{1, 2, 3},\n"
3352       "     {1, 2, 3},\n"
3353       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
3354       "      333333333333333333333333333333},\n"
3355       "     {1, 2, 3},\n"
3356       "     {1, 2, 3}}};");
3357   verifyFormat(
3358       "SomeArrayOfSomeType a = {\n"
3359       "    {{1, 2, 3}},\n"
3360       "    {{1, 2, 3}},\n"
3361       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
3362       "      333333333333333333333333333333}},\n"
3363       "    {{1, 2, 3}},\n"
3364       "    {{1, 2, 3}}};");
3365 
3366   verifyFormat("struct {\n"
3367                "  unsigned bit;\n"
3368                "  const char *const name;\n"
3369                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
3370                "                 {kOsWin, \"Windows\"},\n"
3371                "                 {kOsLinux, \"Linux\"},\n"
3372                "                 {kOsCrOS, \"Chrome OS\"}};");
3373   verifyFormat("struct {\n"
3374                "  unsigned bit;\n"
3375                "  const char *const name;\n"
3376                "} kBitsToOs[] = {\n"
3377                "    {kOsMac, \"Mac\"},\n"
3378                "    {kOsWin, \"Windows\"},\n"
3379                "    {kOsLinux, \"Linux\"},\n"
3380                "    {kOsCrOS, \"Chrome OS\"},\n"
3381                "};");
3382 }
3383 
3384 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
3385   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3386                "                      \\\n"
3387                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
3388 }
3389 
3390 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
3391   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
3392                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
3393 
3394   // Do break defaulted and deleted functions.
3395   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
3396                "    default;",
3397                getLLVMStyleWithColumns(40));
3398   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
3399                "    delete;",
3400                getLLVMStyleWithColumns(40));
3401 }
3402 
3403 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
3404   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
3405                getLLVMStyleWithColumns(40));
3406   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
3407                getLLVMStyleWithColumns(40));
3408   EXPECT_EQ("#define Q                              \\\n"
3409             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
3410             "  \"aaaaaaaa.cpp\"",
3411             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
3412                    getLLVMStyleWithColumns(40)));
3413 }
3414 
3415 TEST_F(FormatTest, UnderstandsLinePPDirective) {
3416   EXPECT_EQ("# 123 \"A string literal\"",
3417             format("   #     123    \"A string literal\""));
3418 }
3419 
3420 TEST_F(FormatTest, LayoutUnknownPPDirective) {
3421   EXPECT_EQ("#;", format("#;"));
3422   verifyFormat("#\n;\n;\n;");
3423 }
3424 
3425 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
3426   EXPECT_EQ("#line 42 \"test\"\n",
3427             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
3428   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
3429                                     getLLVMStyleWithColumns(12)));
3430 }
3431 
3432 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
3433   EXPECT_EQ("#line 42 \"test\"",
3434             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
3435   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
3436 }
3437 
3438 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
3439   verifyFormat("#define A \\x20");
3440   verifyFormat("#define A \\ x20");
3441   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
3442   verifyFormat("#define A ''");
3443   verifyFormat("#define A ''qqq");
3444   verifyFormat("#define A `qqq");
3445   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
3446   EXPECT_EQ("const char *c = STRINGIFY(\n"
3447             "\\na : b);",
3448             format("const char * c = STRINGIFY(\n"
3449                    "\\na : b);"));
3450 
3451   verifyFormat("a\r\\");
3452   verifyFormat("a\v\\");
3453   verifyFormat("a\f\\");
3454 }
3455 
3456 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
3457   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
3458   style.IndentWidth = 4;
3459   style.PPIndentWidth = 1;
3460 
3461   style.IndentPPDirectives = FormatStyle::PPDIS_None;
3462   verifyFormat("#ifdef __linux__\n"
3463                "void foo() {\n"
3464                "    int x = 0;\n"
3465                "}\n"
3466                "#define FOO\n"
3467                "#endif\n"
3468                "void bar() {\n"
3469                "    int y = 0;\n"
3470                "}\n",
3471                style);
3472 
3473   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
3474   verifyFormat("#ifdef __linux__\n"
3475                "void foo() {\n"
3476                "    int x = 0;\n"
3477                "}\n"
3478                "# define FOO foo\n"
3479                "#endif\n"
3480                "void bar() {\n"
3481                "    int y = 0;\n"
3482                "}\n",
3483                style);
3484 
3485   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
3486   verifyFormat("#ifdef __linux__\n"
3487                "void foo() {\n"
3488                "    int x = 0;\n"
3489                "}\n"
3490                " #define FOO foo\n"
3491                "#endif\n"
3492                "void bar() {\n"
3493                "    int y = 0;\n"
3494                "}\n",
3495                style);
3496 }
3497 
3498 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
3499   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
3500   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
3501   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
3502   // FIXME: We never break before the macro name.
3503   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
3504 
3505   verifyFormat("#define A A\n#define A A");
3506   verifyFormat("#define A(X) A\n#define A A");
3507 
3508   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
3509   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
3510 }
3511 
3512 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
3513   EXPECT_EQ("// somecomment\n"
3514             "#include \"a.h\"\n"
3515             "#define A(  \\\n"
3516             "    A, B)\n"
3517             "#include \"b.h\"\n"
3518             "// somecomment\n",
3519             format("  // somecomment\n"
3520                    "  #include \"a.h\"\n"
3521                    "#define A(A,\\\n"
3522                    "    B)\n"
3523                    "    #include \"b.h\"\n"
3524                    " // somecomment\n",
3525                    getLLVMStyleWithColumns(13)));
3526 }
3527 
3528 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
3529 
3530 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
3531   EXPECT_EQ("#define A    \\\n"
3532             "  c;         \\\n"
3533             "  e;\n"
3534             "f;",
3535             format("#define A c; e;\n"
3536                    "f;",
3537                    getLLVMStyleWithColumns(14)));
3538 }
3539 
3540 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
3541 
3542 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
3543   EXPECT_EQ("int x,\n"
3544             "#define A\n"
3545             "    y;",
3546             format("int x,\n#define A\ny;"));
3547 }
3548 
3549 TEST_F(FormatTest, HashInMacroDefinition) {
3550   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
3551   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
3552   verifyFormat("#define A  \\\n"
3553                "  {        \\\n"
3554                "    f(#c); \\\n"
3555                "  }",
3556                getLLVMStyleWithColumns(11));
3557 
3558   verifyFormat("#define A(X)         \\\n"
3559                "  void function##X()",
3560                getLLVMStyleWithColumns(22));
3561 
3562   verifyFormat("#define A(a, b, c)   \\\n"
3563                "  void a##b##c()",
3564                getLLVMStyleWithColumns(22));
3565 
3566   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
3567 }
3568 
3569 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
3570   EXPECT_EQ("#define A (x)", format("#define A (x)"));
3571   EXPECT_EQ("#define A(x)", format("#define A(x)"));
3572 
3573   FormatStyle Style = getLLVMStyle();
3574   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
3575   verifyFormat("#define true ((foo)1)", Style);
3576   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
3577   verifyFormat("#define false((foo)0)", Style);
3578 }
3579 
3580 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
3581   EXPECT_EQ("#define A b;", format("#define A \\\n"
3582                                    "          \\\n"
3583                                    "  b;",
3584                                    getLLVMStyleWithColumns(25)));
3585   EXPECT_EQ("#define A \\\n"
3586             "          \\\n"
3587             "  a;      \\\n"
3588             "  b;",
3589             format("#define A \\\n"
3590                    "          \\\n"
3591                    "  a;      \\\n"
3592                    "  b;",
3593                    getLLVMStyleWithColumns(11)));
3594   EXPECT_EQ("#define A \\\n"
3595             "  a;      \\\n"
3596             "          \\\n"
3597             "  b;",
3598             format("#define A \\\n"
3599                    "  a;      \\\n"
3600                    "          \\\n"
3601                    "  b;",
3602                    getLLVMStyleWithColumns(11)));
3603 }
3604 
3605 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
3606   verifyIncompleteFormat("#define A :");
3607   verifyFormat("#define SOMECASES  \\\n"
3608                "  case 1:          \\\n"
3609                "  case 2\n",
3610                getLLVMStyleWithColumns(20));
3611   verifyFormat("#define MACRO(a) \\\n"
3612                "  if (a)         \\\n"
3613                "    f();         \\\n"
3614                "  else           \\\n"
3615                "    g()",
3616                getLLVMStyleWithColumns(18));
3617   verifyFormat("#define A template <typename T>");
3618   verifyIncompleteFormat("#define STR(x) #x\n"
3619                          "f(STR(this_is_a_string_literal{));");
3620   verifyFormat("#pragma omp threadprivate( \\\n"
3621                "    y)), // expected-warning",
3622                getLLVMStyleWithColumns(28));
3623   verifyFormat("#d, = };");
3624   verifyFormat("#if \"a");
3625   verifyIncompleteFormat("({\n"
3626                          "#define b     \\\n"
3627                          "  }           \\\n"
3628                          "  a\n"
3629                          "a",
3630                          getLLVMStyleWithColumns(15));
3631   verifyFormat("#define A     \\\n"
3632                "  {           \\\n"
3633                "    {\n"
3634                "#define B     \\\n"
3635                "  }           \\\n"
3636                "  }",
3637                getLLVMStyleWithColumns(15));
3638   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
3639   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
3640   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
3641   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
3642 }
3643 
3644 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
3645   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
3646   EXPECT_EQ("class A : public QObject {\n"
3647             "  Q_OBJECT\n"
3648             "\n"
3649             "  A() {}\n"
3650             "};",
3651             format("class A  :  public QObject {\n"
3652                    "     Q_OBJECT\n"
3653                    "\n"
3654                    "  A() {\n}\n"
3655                    "}  ;"));
3656   EXPECT_EQ("MACRO\n"
3657             "/*static*/ int i;",
3658             format("MACRO\n"
3659                    " /*static*/ int   i;"));
3660   EXPECT_EQ("SOME_MACRO\n"
3661             "namespace {\n"
3662             "void f();\n"
3663             "} // namespace",
3664             format("SOME_MACRO\n"
3665                    "  namespace    {\n"
3666                    "void   f(  );\n"
3667                    "} // namespace"));
3668   // Only if the identifier contains at least 5 characters.
3669   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
3670   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
3671   // Only if everything is upper case.
3672   EXPECT_EQ("class A : public QObject {\n"
3673             "  Q_Object A() {}\n"
3674             "};",
3675             format("class A  :  public QObject {\n"
3676                    "     Q_Object\n"
3677                    "  A() {\n}\n"
3678                    "}  ;"));
3679 
3680   // Only if the next line can actually start an unwrapped line.
3681   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
3682             format("SOME_WEIRD_LOG_MACRO\n"
3683                    "<< SomeThing;"));
3684 
3685   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
3686                "(n, buffers))\n",
3687                getChromiumStyle(FormatStyle::LK_Cpp));
3688 
3689   // See PR41483
3690   EXPECT_EQ("/**/ FOO(a)\n"
3691             "FOO(b)",
3692             format("/**/ FOO(a)\n"
3693                    "FOO(b)"));
3694 }
3695 
3696 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
3697   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3698             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3699             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3700             "class X {};\n"
3701             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3702             "int *createScopDetectionPass() { return 0; }",
3703             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3704                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3705                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3706                    "  class X {};\n"
3707                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3708                    "  int *createScopDetectionPass() { return 0; }"));
3709   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
3710   // braces, so that inner block is indented one level more.
3711   EXPECT_EQ("int q() {\n"
3712             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3713             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3714             "  IPC_END_MESSAGE_MAP()\n"
3715             "}",
3716             format("int q() {\n"
3717                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3718                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3719                    "  IPC_END_MESSAGE_MAP()\n"
3720                    "}"));
3721 
3722   // Same inside macros.
3723   EXPECT_EQ("#define LIST(L) \\\n"
3724             "  L(A)          \\\n"
3725             "  L(B)          \\\n"
3726             "  L(C)",
3727             format("#define LIST(L) \\\n"
3728                    "  L(A) \\\n"
3729                    "  L(B) \\\n"
3730                    "  L(C)",
3731                    getGoogleStyle()));
3732 
3733   // These must not be recognized as macros.
3734   EXPECT_EQ("int q() {\n"
3735             "  f(x);\n"
3736             "  f(x) {}\n"
3737             "  f(x)->g();\n"
3738             "  f(x)->*g();\n"
3739             "  f(x).g();\n"
3740             "  f(x) = x;\n"
3741             "  f(x) += x;\n"
3742             "  f(x) -= x;\n"
3743             "  f(x) *= x;\n"
3744             "  f(x) /= x;\n"
3745             "  f(x) %= x;\n"
3746             "  f(x) &= x;\n"
3747             "  f(x) |= x;\n"
3748             "  f(x) ^= x;\n"
3749             "  f(x) >>= x;\n"
3750             "  f(x) <<= x;\n"
3751             "  f(x)[y].z();\n"
3752             "  LOG(INFO) << x;\n"
3753             "  ifstream(x) >> x;\n"
3754             "}\n",
3755             format("int q() {\n"
3756                    "  f(x)\n;\n"
3757                    "  f(x)\n {}\n"
3758                    "  f(x)\n->g();\n"
3759                    "  f(x)\n->*g();\n"
3760                    "  f(x)\n.g();\n"
3761                    "  f(x)\n = x;\n"
3762                    "  f(x)\n += x;\n"
3763                    "  f(x)\n -= x;\n"
3764                    "  f(x)\n *= x;\n"
3765                    "  f(x)\n /= x;\n"
3766                    "  f(x)\n %= x;\n"
3767                    "  f(x)\n &= x;\n"
3768                    "  f(x)\n |= x;\n"
3769                    "  f(x)\n ^= x;\n"
3770                    "  f(x)\n >>= x;\n"
3771                    "  f(x)\n <<= x;\n"
3772                    "  f(x)\n[y].z();\n"
3773                    "  LOG(INFO)\n << x;\n"
3774                    "  ifstream(x)\n >> x;\n"
3775                    "}\n"));
3776   EXPECT_EQ("int q() {\n"
3777             "  F(x)\n"
3778             "  if (1) {\n"
3779             "  }\n"
3780             "  F(x)\n"
3781             "  while (1) {\n"
3782             "  }\n"
3783             "  F(x)\n"
3784             "  G(x);\n"
3785             "  F(x)\n"
3786             "  try {\n"
3787             "    Q();\n"
3788             "  } catch (...) {\n"
3789             "  }\n"
3790             "}\n",
3791             format("int q() {\n"
3792                    "F(x)\n"
3793                    "if (1) {}\n"
3794                    "F(x)\n"
3795                    "while (1) {}\n"
3796                    "F(x)\n"
3797                    "G(x);\n"
3798                    "F(x)\n"
3799                    "try { Q(); } catch (...) {}\n"
3800                    "}\n"));
3801   EXPECT_EQ("class A {\n"
3802             "  A() : t(0) {}\n"
3803             "  A(int i) noexcept() : {}\n"
3804             "  A(X x)\n" // FIXME: function-level try blocks are broken.
3805             "  try : t(0) {\n"
3806             "  } catch (...) {\n"
3807             "  }\n"
3808             "};",
3809             format("class A {\n"
3810                    "  A()\n : t(0) {}\n"
3811                    "  A(int i)\n noexcept() : {}\n"
3812                    "  A(X x)\n"
3813                    "  try : t(0) {} catch (...) {}\n"
3814                    "};"));
3815   FormatStyle Style = getLLVMStyle();
3816   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3817   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
3818   Style.BraceWrapping.AfterFunction = true;
3819   EXPECT_EQ("void f()\n"
3820             "try\n"
3821             "{\n"
3822             "}",
3823             format("void f() try {\n"
3824                    "}",
3825                    Style));
3826   EXPECT_EQ("class SomeClass {\n"
3827             "public:\n"
3828             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3829             "};",
3830             format("class SomeClass {\n"
3831                    "public:\n"
3832                    "  SomeClass()\n"
3833                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3834                    "};"));
3835   EXPECT_EQ("class SomeClass {\n"
3836             "public:\n"
3837             "  SomeClass()\n"
3838             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3839             "};",
3840             format("class SomeClass {\n"
3841                    "public:\n"
3842                    "  SomeClass()\n"
3843                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3844                    "};",
3845                    getLLVMStyleWithColumns(40)));
3846 
3847   verifyFormat("MACRO(>)");
3848 
3849   // Some macros contain an implicit semicolon.
3850   Style = getLLVMStyle();
3851   Style.StatementMacros.push_back("FOO");
3852   verifyFormat("FOO(a) int b = 0;");
3853   verifyFormat("FOO(a)\n"
3854                "int b = 0;",
3855                Style);
3856   verifyFormat("FOO(a);\n"
3857                "int b = 0;",
3858                Style);
3859   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
3860                "int b = 0;",
3861                Style);
3862   verifyFormat("FOO()\n"
3863                "int b = 0;",
3864                Style);
3865   verifyFormat("FOO\n"
3866                "int b = 0;",
3867                Style);
3868   verifyFormat("void f() {\n"
3869                "  FOO(a)\n"
3870                "  return a;\n"
3871                "}",
3872                Style);
3873   verifyFormat("FOO(a)\n"
3874                "FOO(b)",
3875                Style);
3876   verifyFormat("int a = 0;\n"
3877                "FOO(b)\n"
3878                "int c = 0;",
3879                Style);
3880   verifyFormat("int a = 0;\n"
3881                "int x = FOO(a)\n"
3882                "int b = 0;",
3883                Style);
3884   verifyFormat("void foo(int a) { FOO(a) }\n"
3885                "uint32_t bar() {}",
3886                Style);
3887 }
3888 
3889 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
3890   verifyFormat("#define A \\\n"
3891                "  f({     \\\n"
3892                "    g();  \\\n"
3893                "  });",
3894                getLLVMStyleWithColumns(11));
3895 }
3896 
3897 TEST_F(FormatTest, IndentPreprocessorDirectives) {
3898   FormatStyle Style = getLLVMStyle();
3899   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
3900   Style.ColumnLimit = 40;
3901   verifyFormat("#ifdef _WIN32\n"
3902                "#define A 0\n"
3903                "#ifdef VAR2\n"
3904                "#define B 1\n"
3905                "#include <someheader.h>\n"
3906                "#define MACRO                          \\\n"
3907                "  some_very_long_func_aaaaaaaaaa();\n"
3908                "#endif\n"
3909                "#else\n"
3910                "#define A 1\n"
3911                "#endif",
3912                Style);
3913   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
3914   verifyFormat("#ifdef _WIN32\n"
3915                "#  define A 0\n"
3916                "#  ifdef VAR2\n"
3917                "#    define B 1\n"
3918                "#    include <someheader.h>\n"
3919                "#    define MACRO                      \\\n"
3920                "      some_very_long_func_aaaaaaaaaa();\n"
3921                "#  endif\n"
3922                "#else\n"
3923                "#  define A 1\n"
3924                "#endif",
3925                Style);
3926   verifyFormat("#if A\n"
3927                "#  define MACRO                        \\\n"
3928                "    void a(int x) {                    \\\n"
3929                "      b();                             \\\n"
3930                "      c();                             \\\n"
3931                "      d();                             \\\n"
3932                "      e();                             \\\n"
3933                "      f();                             \\\n"
3934                "    }\n"
3935                "#endif",
3936                Style);
3937   // Comments before include guard.
3938   verifyFormat("// file comment\n"
3939                "// file comment\n"
3940                "#ifndef HEADER_H\n"
3941                "#define HEADER_H\n"
3942                "code();\n"
3943                "#endif",
3944                Style);
3945   // Test with include guards.
3946   verifyFormat("#ifndef HEADER_H\n"
3947                "#define HEADER_H\n"
3948                "code();\n"
3949                "#endif",
3950                Style);
3951   // Include guards must have a #define with the same variable immediately
3952   // after #ifndef.
3953   verifyFormat("#ifndef NOT_GUARD\n"
3954                "#  define FOO\n"
3955                "code();\n"
3956                "#endif",
3957                Style);
3958 
3959   // Include guards must cover the entire file.
3960   verifyFormat("code();\n"
3961                "code();\n"
3962                "#ifndef NOT_GUARD\n"
3963                "#  define NOT_GUARD\n"
3964                "code();\n"
3965                "#endif",
3966                Style);
3967   verifyFormat("#ifndef NOT_GUARD\n"
3968                "#  define NOT_GUARD\n"
3969                "code();\n"
3970                "#endif\n"
3971                "code();",
3972                Style);
3973   // Test with trailing blank lines.
3974   verifyFormat("#ifndef HEADER_H\n"
3975                "#define HEADER_H\n"
3976                "code();\n"
3977                "#endif\n",
3978                Style);
3979   // Include guards don't have #else.
3980   verifyFormat("#ifndef NOT_GUARD\n"
3981                "#  define NOT_GUARD\n"
3982                "code();\n"
3983                "#else\n"
3984                "#endif",
3985                Style);
3986   verifyFormat("#ifndef NOT_GUARD\n"
3987                "#  define NOT_GUARD\n"
3988                "code();\n"
3989                "#elif FOO\n"
3990                "#endif",
3991                Style);
3992   // Non-identifier #define after potential include guard.
3993   verifyFormat("#ifndef FOO\n"
3994                "#  define 1\n"
3995                "#endif\n",
3996                Style);
3997   // #if closes past last non-preprocessor line.
3998   verifyFormat("#ifndef FOO\n"
3999                "#define FOO\n"
4000                "#if 1\n"
4001                "int i;\n"
4002                "#  define A 0\n"
4003                "#endif\n"
4004                "#endif\n",
4005                Style);
4006   // Don't crash if there is an #elif directive without a condition.
4007   verifyFormat("#if 1\n"
4008                "int x;\n"
4009                "#elif\n"
4010                "int y;\n"
4011                "#else\n"
4012                "int z;\n"
4013                "#endif",
4014                Style);
4015   // FIXME: This doesn't handle the case where there's code between the
4016   // #ifndef and #define but all other conditions hold. This is because when
4017   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
4018   // previous code line yet, so we can't detect it.
4019   EXPECT_EQ("#ifndef NOT_GUARD\n"
4020             "code();\n"
4021             "#define NOT_GUARD\n"
4022             "code();\n"
4023             "#endif",
4024             format("#ifndef NOT_GUARD\n"
4025                    "code();\n"
4026                    "#  define NOT_GUARD\n"
4027                    "code();\n"
4028                    "#endif",
4029                    Style));
4030   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
4031   // be outside an include guard. Examples are #pragma once and
4032   // #pragma GCC diagnostic, or anything else that does not change the meaning
4033   // of the file if it's included multiple times.
4034   EXPECT_EQ("#ifdef WIN32\n"
4035             "#  pragma once\n"
4036             "#endif\n"
4037             "#ifndef HEADER_H\n"
4038             "#  define HEADER_H\n"
4039             "code();\n"
4040             "#endif",
4041             format("#ifdef WIN32\n"
4042                    "#  pragma once\n"
4043                    "#endif\n"
4044                    "#ifndef HEADER_H\n"
4045                    "#define HEADER_H\n"
4046                    "code();\n"
4047                    "#endif",
4048                    Style));
4049   // FIXME: This does not detect when there is a single non-preprocessor line
4050   // in front of an include-guard-like structure where other conditions hold
4051   // because ScopedLineState hides the line.
4052   EXPECT_EQ("code();\n"
4053             "#ifndef HEADER_H\n"
4054             "#define HEADER_H\n"
4055             "code();\n"
4056             "#endif",
4057             format("code();\n"
4058                    "#ifndef HEADER_H\n"
4059                    "#  define HEADER_H\n"
4060                    "code();\n"
4061                    "#endif",
4062                    Style));
4063   // Keep comments aligned with #, otherwise indent comments normally. These
4064   // tests cannot use verifyFormat because messUp manipulates leading
4065   // whitespace.
4066   {
4067     const char *Expected = ""
4068                            "void f() {\n"
4069                            "#if 1\n"
4070                            "// Preprocessor aligned.\n"
4071                            "#  define A 0\n"
4072                            "  // Code. Separated by blank line.\n"
4073                            "\n"
4074                            "#  define B 0\n"
4075                            "  // Code. Not aligned with #\n"
4076                            "#  define C 0\n"
4077                            "#endif";
4078     const char *ToFormat = ""
4079                            "void f() {\n"
4080                            "#if 1\n"
4081                            "// Preprocessor aligned.\n"
4082                            "#  define A 0\n"
4083                            "// Code. Separated by blank line.\n"
4084                            "\n"
4085                            "#  define B 0\n"
4086                            "   // Code. Not aligned with #\n"
4087                            "#  define C 0\n"
4088                            "#endif";
4089     EXPECT_EQ(Expected, format(ToFormat, Style));
4090     EXPECT_EQ(Expected, format(Expected, Style));
4091   }
4092   // Keep block quotes aligned.
4093   {
4094     const char *Expected = ""
4095                            "void f() {\n"
4096                            "#if 1\n"
4097                            "/* Preprocessor aligned. */\n"
4098                            "#  define A 0\n"
4099                            "  /* Code. Separated by blank line. */\n"
4100                            "\n"
4101                            "#  define B 0\n"
4102                            "  /* Code. Not aligned with # */\n"
4103                            "#  define C 0\n"
4104                            "#endif";
4105     const char *ToFormat = ""
4106                            "void f() {\n"
4107                            "#if 1\n"
4108                            "/* Preprocessor aligned. */\n"
4109                            "#  define A 0\n"
4110                            "/* Code. Separated by blank line. */\n"
4111                            "\n"
4112                            "#  define B 0\n"
4113                            "   /* Code. Not aligned with # */\n"
4114                            "#  define C 0\n"
4115                            "#endif";
4116     EXPECT_EQ(Expected, format(ToFormat, Style));
4117     EXPECT_EQ(Expected, format(Expected, Style));
4118   }
4119   // Keep comments aligned with un-indented directives.
4120   {
4121     const char *Expected = ""
4122                            "void f() {\n"
4123                            "// Preprocessor aligned.\n"
4124                            "#define A 0\n"
4125                            "  // Code. Separated by blank line.\n"
4126                            "\n"
4127                            "#define B 0\n"
4128                            "  // Code. Not aligned with #\n"
4129                            "#define C 0\n";
4130     const char *ToFormat = ""
4131                            "void f() {\n"
4132                            "// Preprocessor aligned.\n"
4133                            "#define A 0\n"
4134                            "// Code. Separated by blank line.\n"
4135                            "\n"
4136                            "#define B 0\n"
4137                            "   // Code. Not aligned with #\n"
4138                            "#define C 0\n";
4139     EXPECT_EQ(Expected, format(ToFormat, Style));
4140     EXPECT_EQ(Expected, format(Expected, Style));
4141   }
4142   // Test AfterHash with tabs.
4143   {
4144     FormatStyle Tabbed = Style;
4145     Tabbed.UseTab = FormatStyle::UT_Always;
4146     Tabbed.IndentWidth = 8;
4147     Tabbed.TabWidth = 8;
4148     verifyFormat("#ifdef _WIN32\n"
4149                  "#\tdefine A 0\n"
4150                  "#\tifdef VAR2\n"
4151                  "#\t\tdefine B 1\n"
4152                  "#\t\tinclude <someheader.h>\n"
4153                  "#\t\tdefine MACRO          \\\n"
4154                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
4155                  "#\tendif\n"
4156                  "#else\n"
4157                  "#\tdefine A 1\n"
4158                  "#endif",
4159                  Tabbed);
4160   }
4161 
4162   // Regression test: Multiline-macro inside include guards.
4163   verifyFormat("#ifndef HEADER_H\n"
4164                "#define HEADER_H\n"
4165                "#define A()        \\\n"
4166                "  int i;           \\\n"
4167                "  int j;\n"
4168                "#endif // HEADER_H",
4169                getLLVMStyleWithColumns(20));
4170 
4171   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4172   // Basic before hash indent tests
4173   verifyFormat("#ifdef _WIN32\n"
4174                "  #define A 0\n"
4175                "  #ifdef VAR2\n"
4176                "    #define B 1\n"
4177                "    #include <someheader.h>\n"
4178                "    #define MACRO                      \\\n"
4179                "      some_very_long_func_aaaaaaaaaa();\n"
4180                "  #endif\n"
4181                "#else\n"
4182                "  #define A 1\n"
4183                "#endif",
4184                Style);
4185   verifyFormat("#if A\n"
4186                "  #define MACRO                        \\\n"
4187                "    void a(int x) {                    \\\n"
4188                "      b();                             \\\n"
4189                "      c();                             \\\n"
4190                "      d();                             \\\n"
4191                "      e();                             \\\n"
4192                "      f();                             \\\n"
4193                "    }\n"
4194                "#endif",
4195                Style);
4196   // Keep comments aligned with indented directives. These
4197   // tests cannot use verifyFormat because messUp manipulates leading
4198   // whitespace.
4199   {
4200     const char *Expected = "void f() {\n"
4201                            "// Aligned to preprocessor.\n"
4202                            "#if 1\n"
4203                            "  // Aligned to code.\n"
4204                            "  int a;\n"
4205                            "  #if 1\n"
4206                            "    // Aligned to preprocessor.\n"
4207                            "    #define A 0\n"
4208                            "  // Aligned to code.\n"
4209                            "  int b;\n"
4210                            "  #endif\n"
4211                            "#endif\n"
4212                            "}";
4213     const char *ToFormat = "void f() {\n"
4214                            "// Aligned to preprocessor.\n"
4215                            "#if 1\n"
4216                            "// Aligned to code.\n"
4217                            "int a;\n"
4218                            "#if 1\n"
4219                            "// Aligned to preprocessor.\n"
4220                            "#define A 0\n"
4221                            "// Aligned to code.\n"
4222                            "int b;\n"
4223                            "#endif\n"
4224                            "#endif\n"
4225                            "}";
4226     EXPECT_EQ(Expected, format(ToFormat, Style));
4227     EXPECT_EQ(Expected, format(Expected, Style));
4228   }
4229   {
4230     const char *Expected = "void f() {\n"
4231                            "/* Aligned to preprocessor. */\n"
4232                            "#if 1\n"
4233                            "  /* Aligned to code. */\n"
4234                            "  int a;\n"
4235                            "  #if 1\n"
4236                            "    /* Aligned to preprocessor. */\n"
4237                            "    #define A 0\n"
4238                            "  /* Aligned to code. */\n"
4239                            "  int b;\n"
4240                            "  #endif\n"
4241                            "#endif\n"
4242                            "}";
4243     const char *ToFormat = "void f() {\n"
4244                            "/* Aligned to preprocessor. */\n"
4245                            "#if 1\n"
4246                            "/* Aligned to code. */\n"
4247                            "int a;\n"
4248                            "#if 1\n"
4249                            "/* Aligned to preprocessor. */\n"
4250                            "#define A 0\n"
4251                            "/* Aligned to code. */\n"
4252                            "int b;\n"
4253                            "#endif\n"
4254                            "#endif\n"
4255                            "}";
4256     EXPECT_EQ(Expected, format(ToFormat, Style));
4257     EXPECT_EQ(Expected, format(Expected, Style));
4258   }
4259 
4260   // Test single comment before preprocessor
4261   verifyFormat("// Comment\n"
4262                "\n"
4263                "#if 1\n"
4264                "#endif",
4265                Style);
4266 }
4267 
4268 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
4269   verifyFormat("{\n  { a #c; }\n}");
4270 }
4271 
4272 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
4273   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
4274             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
4275   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
4276             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
4277 }
4278 
4279 TEST_F(FormatTest, EscapedNewlines) {
4280   FormatStyle Narrow = getLLVMStyleWithColumns(11);
4281   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
4282             format("#define A \\\nint i;\\\n  int j;", Narrow));
4283   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
4284   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
4285   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
4286   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
4287 
4288   FormatStyle AlignLeft = getLLVMStyle();
4289   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
4290   EXPECT_EQ("#define MACRO(x) \\\n"
4291             "private:         \\\n"
4292             "  int x(int a);\n",
4293             format("#define MACRO(x) \\\n"
4294                    "private:         \\\n"
4295                    "  int x(int a);\n",
4296                    AlignLeft));
4297 
4298   // CRLF line endings
4299   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
4300             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
4301   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
4302   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
4303   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
4304   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
4305   EXPECT_EQ("#define MACRO(x) \\\r\n"
4306             "private:         \\\r\n"
4307             "  int x(int a);\r\n",
4308             format("#define MACRO(x) \\\r\n"
4309                    "private:         \\\r\n"
4310                    "  int x(int a);\r\n",
4311                    AlignLeft));
4312 
4313   FormatStyle DontAlign = getLLVMStyle();
4314   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
4315   DontAlign.MaxEmptyLinesToKeep = 3;
4316   // FIXME: can't use verifyFormat here because the newline before
4317   // "public:" is not inserted the first time it's reformatted
4318   EXPECT_EQ("#define A \\\n"
4319             "  class Foo { \\\n"
4320             "    void bar(); \\\n"
4321             "\\\n"
4322             "\\\n"
4323             "\\\n"
4324             "  public: \\\n"
4325             "    void baz(); \\\n"
4326             "  };",
4327             format("#define A \\\n"
4328                    "  class Foo { \\\n"
4329                    "    void bar(); \\\n"
4330                    "\\\n"
4331                    "\\\n"
4332                    "\\\n"
4333                    "  public: \\\n"
4334                    "    void baz(); \\\n"
4335                    "  };",
4336                    DontAlign));
4337 }
4338 
4339 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
4340   verifyFormat("#define A \\\n"
4341                "  int v(  \\\n"
4342                "      a); \\\n"
4343                "  int i;",
4344                getLLVMStyleWithColumns(11));
4345 }
4346 
4347 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
4348   EXPECT_EQ(
4349       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4350       "                      \\\n"
4351       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
4352       "\n"
4353       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
4354       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
4355       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
4356              "\\\n"
4357              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
4358              "  \n"
4359              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
4360              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
4361 }
4362 
4363 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
4364   EXPECT_EQ("int\n"
4365             "#define A\n"
4366             "    a;",
4367             format("int\n#define A\na;"));
4368   verifyFormat("functionCallTo(\n"
4369                "    someOtherFunction(\n"
4370                "        withSomeParameters, whichInSequence,\n"
4371                "        areLongerThanALine(andAnotherCall,\n"
4372                "#define A B\n"
4373                "                           withMoreParamters,\n"
4374                "                           whichStronglyInfluenceTheLayout),\n"
4375                "        andMoreParameters),\n"
4376                "    trailing);",
4377                getLLVMStyleWithColumns(69));
4378   verifyFormat("Foo::Foo()\n"
4379                "#ifdef BAR\n"
4380                "    : baz(0)\n"
4381                "#endif\n"
4382                "{\n"
4383                "}");
4384   verifyFormat("void f() {\n"
4385                "  if (true)\n"
4386                "#ifdef A\n"
4387                "    f(42);\n"
4388                "  x();\n"
4389                "#else\n"
4390                "    g();\n"
4391                "  x();\n"
4392                "#endif\n"
4393                "}");
4394   verifyFormat("void f(param1, param2,\n"
4395                "       param3,\n"
4396                "#ifdef A\n"
4397                "       param4(param5,\n"
4398                "#ifdef A1\n"
4399                "              param6,\n"
4400                "#ifdef A2\n"
4401                "              param7),\n"
4402                "#else\n"
4403                "              param8),\n"
4404                "       param9,\n"
4405                "#endif\n"
4406                "       param10,\n"
4407                "#endif\n"
4408                "       param11)\n"
4409                "#else\n"
4410                "       param12)\n"
4411                "#endif\n"
4412                "{\n"
4413                "  x();\n"
4414                "}",
4415                getLLVMStyleWithColumns(28));
4416   verifyFormat("#if 1\n"
4417                "int i;");
4418   verifyFormat("#if 1\n"
4419                "#endif\n"
4420                "#if 1\n"
4421                "#else\n"
4422                "#endif\n");
4423   verifyFormat("DEBUG({\n"
4424                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4425                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
4426                "});\n"
4427                "#if a\n"
4428                "#else\n"
4429                "#endif");
4430 
4431   verifyIncompleteFormat("void f(\n"
4432                          "#if A\n"
4433                          ");\n"
4434                          "#else\n"
4435                          "#endif");
4436 }
4437 
4438 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
4439   verifyFormat("#endif\n"
4440                "#if B");
4441 }
4442 
4443 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
4444   FormatStyle SingleLine = getLLVMStyle();
4445   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
4446   verifyFormat("#if 0\n"
4447                "#elif 1\n"
4448                "#endif\n"
4449                "void foo() {\n"
4450                "  if (test) foo2();\n"
4451                "}",
4452                SingleLine);
4453 }
4454 
4455 TEST_F(FormatTest, LayoutBlockInsideParens) {
4456   verifyFormat("functionCall({ int i; });");
4457   verifyFormat("functionCall({\n"
4458                "  int i;\n"
4459                "  int j;\n"
4460                "});");
4461   verifyFormat("functionCall(\n"
4462                "    {\n"
4463                "      int i;\n"
4464                "      int j;\n"
4465                "    },\n"
4466                "    aaaa, bbbb, cccc);");
4467   verifyFormat("functionA(functionB({\n"
4468                "            int i;\n"
4469                "            int j;\n"
4470                "          }),\n"
4471                "          aaaa, bbbb, cccc);");
4472   verifyFormat("functionCall(\n"
4473                "    {\n"
4474                "      int i;\n"
4475                "      int j;\n"
4476                "    },\n"
4477                "    aaaa, bbbb, // comment\n"
4478                "    cccc);");
4479   verifyFormat("functionA(functionB({\n"
4480                "            int i;\n"
4481                "            int j;\n"
4482                "          }),\n"
4483                "          aaaa, bbbb, // comment\n"
4484                "          cccc);");
4485   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
4486   verifyFormat("functionCall(aaaa, bbbb, {\n"
4487                "  int i;\n"
4488                "  int j;\n"
4489                "});");
4490   verifyFormat(
4491       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
4492       "    {\n"
4493       "      int i; // break\n"
4494       "    },\n"
4495       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4496       "                                     ccccccccccccccccc));");
4497   verifyFormat("DEBUG({\n"
4498                "  if (a)\n"
4499                "    f();\n"
4500                "});");
4501 }
4502 
4503 TEST_F(FormatTest, LayoutBlockInsideStatement) {
4504   EXPECT_EQ("SOME_MACRO { int i; }\n"
4505             "int i;",
4506             format("  SOME_MACRO  {int i;}  int i;"));
4507 }
4508 
4509 TEST_F(FormatTest, LayoutNestedBlocks) {
4510   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
4511                "  struct s {\n"
4512                "    int i;\n"
4513                "  };\n"
4514                "  s kBitsToOs[] = {{10}};\n"
4515                "  for (int i = 0; i < 10; ++i)\n"
4516                "    return;\n"
4517                "}");
4518   verifyFormat("call(parameter, {\n"
4519                "  something();\n"
4520                "  // Comment using all columns.\n"
4521                "  somethingelse();\n"
4522                "});",
4523                getLLVMStyleWithColumns(40));
4524   verifyFormat("DEBUG( //\n"
4525                "    { f(); }, a);");
4526   verifyFormat("DEBUG( //\n"
4527                "    {\n"
4528                "      f(); //\n"
4529                "    },\n"
4530                "    a);");
4531 
4532   EXPECT_EQ("call(parameter, {\n"
4533             "  something();\n"
4534             "  // Comment too\n"
4535             "  // looooooooooong.\n"
4536             "  somethingElse();\n"
4537             "});",
4538             format("call(parameter, {\n"
4539                    "  something();\n"
4540                    "  // Comment too looooooooooong.\n"
4541                    "  somethingElse();\n"
4542                    "});",
4543                    getLLVMStyleWithColumns(29)));
4544   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
4545   EXPECT_EQ("DEBUG({ // comment\n"
4546             "  int i;\n"
4547             "});",
4548             format("DEBUG({ // comment\n"
4549                    "int  i;\n"
4550                    "});"));
4551   EXPECT_EQ("DEBUG({\n"
4552             "  int i;\n"
4553             "\n"
4554             "  // comment\n"
4555             "  int j;\n"
4556             "});",
4557             format("DEBUG({\n"
4558                    "  int  i;\n"
4559                    "\n"
4560                    "  // comment\n"
4561                    "  int  j;\n"
4562                    "});"));
4563 
4564   verifyFormat("DEBUG({\n"
4565                "  if (a)\n"
4566                "    return;\n"
4567                "});");
4568   verifyGoogleFormat("DEBUG({\n"
4569                      "  if (a) return;\n"
4570                      "});");
4571   FormatStyle Style = getGoogleStyle();
4572   Style.ColumnLimit = 45;
4573   verifyFormat("Debug(\n"
4574                "    aaaaa,\n"
4575                "    {\n"
4576                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
4577                "    },\n"
4578                "    a);",
4579                Style);
4580 
4581   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
4582 
4583   verifyNoCrash("^{v^{a}}");
4584 }
4585 
4586 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
4587   EXPECT_EQ("#define MACRO()                     \\\n"
4588             "  Debug(aaa, /* force line break */ \\\n"
4589             "        {                           \\\n"
4590             "          int i;                    \\\n"
4591             "          int j;                    \\\n"
4592             "        })",
4593             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
4594                    "          {  int   i;  int  j;   })",
4595                    getGoogleStyle()));
4596 
4597   EXPECT_EQ("#define A                                       \\\n"
4598             "  [] {                                          \\\n"
4599             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
4600             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
4601             "  }",
4602             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
4603                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
4604                    getGoogleStyle()));
4605 }
4606 
4607 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
4608   EXPECT_EQ("{}", format("{}"));
4609   verifyFormat("enum E {};");
4610   verifyFormat("enum E {}");
4611   FormatStyle Style = getLLVMStyle();
4612   Style.SpaceInEmptyBlock = true;
4613   EXPECT_EQ("void f() { }", format("void f() {}", Style));
4614   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
4615   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
4616 }
4617 
4618 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
4619   FormatStyle Style = getLLVMStyle();
4620   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
4621   Style.MacroBlockEnd = "^[A-Z_]+_END$";
4622   verifyFormat("FOO_BEGIN\n"
4623                "  FOO_ENTRY\n"
4624                "FOO_END",
4625                Style);
4626   verifyFormat("FOO_BEGIN\n"
4627                "  NESTED_FOO_BEGIN\n"
4628                "    NESTED_FOO_ENTRY\n"
4629                "  NESTED_FOO_END\n"
4630                "FOO_END",
4631                Style);
4632   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
4633                "  int x;\n"
4634                "  x = 1;\n"
4635                "FOO_END(Baz)",
4636                Style);
4637 }
4638 
4639 //===----------------------------------------------------------------------===//
4640 // Line break tests.
4641 //===----------------------------------------------------------------------===//
4642 
4643 TEST_F(FormatTest, PreventConfusingIndents) {
4644   verifyFormat(
4645       "void f() {\n"
4646       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
4647       "                         parameter, parameter, parameter)),\n"
4648       "                     SecondLongCall(parameter));\n"
4649       "}");
4650   verifyFormat(
4651       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4652       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4653       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4654       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
4655   verifyFormat(
4656       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4657       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
4658       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
4659       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
4660   verifyFormat(
4661       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
4662       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
4663       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
4664       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
4665   verifyFormat("int a = bbbb && ccc &&\n"
4666                "        fffff(\n"
4667                "#define A Just forcing a new line\n"
4668                "            ddd);");
4669 }
4670 
4671 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
4672   verifyFormat(
4673       "bool aaaaaaa =\n"
4674       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
4675       "    bbbbbbbb();");
4676   verifyFormat(
4677       "bool aaaaaaa =\n"
4678       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
4679       "    bbbbbbbb();");
4680 
4681   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4682                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
4683                "    ccccccccc == ddddddddddd;");
4684   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4685                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
4686                "    ccccccccc == ddddddddddd;");
4687   verifyFormat(
4688       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
4689       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
4690       "    ccccccccc == ddddddddddd;");
4691 
4692   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4693                "                 aaaaaa) &&\n"
4694                "         bbbbbb && cccccc;");
4695   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4696                "                 aaaaaa) >>\n"
4697                "         bbbbbb;");
4698   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
4699                "    SourceMgr.getSpellingColumnNumber(\n"
4700                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
4701                "    1);");
4702 
4703   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4704                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
4705                "    cccccc) {\n}");
4706   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4707                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4708                "              cccccc) {\n}");
4709   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4710                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4711                "              cccccc) {\n}");
4712   verifyFormat("b = a &&\n"
4713                "    // Comment\n"
4714                "    b.c && d;");
4715 
4716   // If the LHS of a comparison is not a binary expression itself, the
4717   // additional linebreak confuses many people.
4718   verifyFormat(
4719       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4720       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
4721       "}");
4722   verifyFormat(
4723       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4724       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4725       "}");
4726   verifyFormat(
4727       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
4728       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4729       "}");
4730   verifyFormat(
4731       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4732       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
4733       "}");
4734   // Even explicit parentheses stress the precedence enough to make the
4735   // additional break unnecessary.
4736   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4737                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4738                "}");
4739   // This cases is borderline, but with the indentation it is still readable.
4740   verifyFormat(
4741       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4742       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4743       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
4744       "}",
4745       getLLVMStyleWithColumns(75));
4746 
4747   // If the LHS is a binary expression, we should still use the additional break
4748   // as otherwise the formatting hides the operator precedence.
4749   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4750                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4751                "    5) {\n"
4752                "}");
4753   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4754                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
4755                "    5) {\n"
4756                "}");
4757 
4758   FormatStyle OnePerLine = getLLVMStyle();
4759   OnePerLine.BinPackParameters = false;
4760   verifyFormat(
4761       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4762       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4763       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
4764       OnePerLine);
4765 
4766   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
4767                "                .aaa(aaaaaaaaaaaaa) *\n"
4768                "            aaaaaaa +\n"
4769                "        aaaaaaa;",
4770                getLLVMStyleWithColumns(40));
4771 }
4772 
4773 TEST_F(FormatTest, ExpressionIndentation) {
4774   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4775                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4776                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4777                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4778                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
4779                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
4780                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4781                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
4782                "                 ccccccccccccccccccccccccccccccccccccccccc;");
4783   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4784                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4785                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4786                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4787   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4788                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4789                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4790                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4791   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4792                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4793                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4794                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4795   verifyFormat("if () {\n"
4796                "} else if (aaaaa && bbbbb > // break\n"
4797                "                        ccccc) {\n"
4798                "}");
4799   verifyFormat("if () {\n"
4800                "} else if constexpr (aaaaa && bbbbb > // break\n"
4801                "                                  ccccc) {\n"
4802                "}");
4803   verifyFormat("if () {\n"
4804                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
4805                "                                  ccccc) {\n"
4806                "}");
4807   verifyFormat("if () {\n"
4808                "} else if (aaaaa &&\n"
4809                "           bbbbb > // break\n"
4810                "               ccccc &&\n"
4811                "           ddddd) {\n"
4812                "}");
4813 
4814   // Presence of a trailing comment used to change indentation of b.
4815   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
4816                "       b;\n"
4817                "return aaaaaaaaaaaaaaaaaaa +\n"
4818                "       b; //",
4819                getLLVMStyleWithColumns(30));
4820 }
4821 
4822 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
4823   // Not sure what the best system is here. Like this, the LHS can be found
4824   // immediately above an operator (everything with the same or a higher
4825   // indent). The RHS is aligned right of the operator and so compasses
4826   // everything until something with the same indent as the operator is found.
4827   // FIXME: Is this a good system?
4828   FormatStyle Style = getLLVMStyle();
4829   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4830   verifyFormat(
4831       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4832       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4833       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4834       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4835       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4836       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4837       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4838       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4839       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
4840       Style);
4841   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4842                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4843                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4844                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4845                Style);
4846   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4847                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4848                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4849                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4850                Style);
4851   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4852                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4853                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4854                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4855                Style);
4856   verifyFormat("if () {\n"
4857                "} else if (aaaaa\n"
4858                "           && bbbbb // break\n"
4859                "                  > ccccc) {\n"
4860                "}",
4861                Style);
4862   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4863                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4864                Style);
4865   verifyFormat("return (a)\n"
4866                "       // comment\n"
4867                "       + b;",
4868                Style);
4869   verifyFormat(
4870       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4871       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4872       "             + cc;",
4873       Style);
4874 
4875   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4876                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4877                Style);
4878 
4879   // Forced by comments.
4880   verifyFormat(
4881       "unsigned ContentSize =\n"
4882       "    sizeof(int16_t)   // DWARF ARange version number\n"
4883       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4884       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4885       "    + sizeof(int8_t); // Segment Size (in bytes)");
4886 
4887   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4888                "       == boost::fusion::at_c<1>(iiii).second;",
4889                Style);
4890 
4891   Style.ColumnLimit = 60;
4892   verifyFormat("zzzzzzzzzz\n"
4893                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4894                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4895                Style);
4896 
4897   Style.ColumnLimit = 80;
4898   Style.IndentWidth = 4;
4899   Style.TabWidth = 4;
4900   Style.UseTab = FormatStyle::UT_Always;
4901   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4902   Style.AlignOperands = FormatStyle::OAS_DontAlign;
4903   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
4904             "\t&& (someOtherLongishConditionPart1\n"
4905             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
4906             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
4907                    "(someOtherLongishConditionPart1 || "
4908                    "someOtherEvenLongerNestedConditionPart2);",
4909                    Style));
4910 }
4911 
4912 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
4913   FormatStyle Style = getLLVMStyle();
4914   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4915   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
4916 
4917   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4918                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4919                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4920                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4921                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4922                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4923                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4924                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4925                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
4926                Style);
4927   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4928                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4929                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4930                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4931                Style);
4932   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4933                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4934                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4935                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4936                Style);
4937   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4938                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4939                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4940                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4941                Style);
4942   verifyFormat("if () {\n"
4943                "} else if (aaaaa\n"
4944                "           && bbbbb // break\n"
4945                "                  > ccccc) {\n"
4946                "}",
4947                Style);
4948   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4949                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4950                Style);
4951   verifyFormat("return (a)\n"
4952                "     // comment\n"
4953                "     + b;",
4954                Style);
4955   verifyFormat(
4956       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4957       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4958       "           + cc;",
4959       Style);
4960   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
4961                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
4962                "                        : 3333333333333333;",
4963                Style);
4964   verifyFormat(
4965       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
4966       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
4967       "                                             : eeeeeeeeeeeeeeeeee)\n"
4968       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
4969       "                        : 3333333333333333;",
4970       Style);
4971   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4972                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4973                Style);
4974 
4975   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4976                "    == boost::fusion::at_c<1>(iiii).second;",
4977                Style);
4978 
4979   Style.ColumnLimit = 60;
4980   verifyFormat("zzzzzzzzzzzzz\n"
4981                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4982                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4983                Style);
4984 
4985   // Forced by comments.
4986   Style.ColumnLimit = 80;
4987   verifyFormat(
4988       "unsigned ContentSize\n"
4989       "    = sizeof(int16_t) // DWARF ARange version number\n"
4990       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4991       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4992       "    + sizeof(int8_t); // Segment Size (in bytes)",
4993       Style);
4994 
4995   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4996   verifyFormat(
4997       "unsigned ContentSize =\n"
4998       "    sizeof(int16_t)   // DWARF ARange version number\n"
4999       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5000       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5001       "    + sizeof(int8_t); // Segment Size (in bytes)",
5002       Style);
5003 
5004   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
5005   verifyFormat(
5006       "unsigned ContentSize =\n"
5007       "    sizeof(int16_t)   // DWARF ARange version number\n"
5008       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5009       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5010       "    + sizeof(int8_t); // Segment Size (in bytes)",
5011       Style);
5012 }
5013 
5014 TEST_F(FormatTest, EnforcedOperatorWraps) {
5015   // Here we'd like to wrap after the || operators, but a comment is forcing an
5016   // earlier wrap.
5017   verifyFormat("bool x = aaaaa //\n"
5018                "         || bbbbb\n"
5019                "         //\n"
5020                "         || cccc;");
5021 }
5022 
5023 TEST_F(FormatTest, NoOperandAlignment) {
5024   FormatStyle Style = getLLVMStyle();
5025   Style.AlignOperands = FormatStyle::OAS_DontAlign;
5026   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
5027                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5028                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5029                Style);
5030   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5031   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5032                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5033                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5034                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5035                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5036                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5037                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5038                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5039                "        > ccccccccccccccccccccccccccccccccccccccccc;",
5040                Style);
5041 
5042   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5043                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5044                "    + cc;",
5045                Style);
5046   verifyFormat("int a = aa\n"
5047                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5048                "        * cccccccccccccccccccccccccccccccccccc;\n",
5049                Style);
5050 
5051   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5052   verifyFormat("return (a > b\n"
5053                "    // comment1\n"
5054                "    // comment2\n"
5055                "    || c);",
5056                Style);
5057 }
5058 
5059 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
5060   FormatStyle Style = getLLVMStyle();
5061   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5062   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5063                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5064                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5065                Style);
5066 }
5067 
5068 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
5069   FormatStyle Style = getLLVMStyle();
5070   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5071   Style.BinPackArguments = false;
5072   Style.ColumnLimit = 40;
5073   verifyFormat("void test() {\n"
5074                "  someFunction(\n"
5075                "      this + argument + is + quite\n"
5076                "      + long + so + it + gets + wrapped\n"
5077                "      + but + remains + bin - packed);\n"
5078                "}",
5079                Style);
5080   verifyFormat("void test() {\n"
5081                "  someFunction(arg1,\n"
5082                "               this + argument + is\n"
5083                "                   + quite + long + so\n"
5084                "                   + it + gets + wrapped\n"
5085                "                   + but + remains + bin\n"
5086                "                   - packed,\n"
5087                "               arg3);\n"
5088                "}",
5089                Style);
5090   verifyFormat("void test() {\n"
5091                "  someFunction(\n"
5092                "      arg1,\n"
5093                "      this + argument + has\n"
5094                "          + anotherFunc(nested,\n"
5095                "                        calls + whose\n"
5096                "                            + arguments\n"
5097                "                            + are + also\n"
5098                "                            + wrapped,\n"
5099                "                        in + addition)\n"
5100                "          + to + being + bin - packed,\n"
5101                "      arg3);\n"
5102                "}",
5103                Style);
5104 
5105   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
5106   verifyFormat("void test() {\n"
5107                "  someFunction(\n"
5108                "      arg1,\n"
5109                "      this + argument + has +\n"
5110                "          anotherFunc(nested,\n"
5111                "                      calls + whose +\n"
5112                "                          arguments +\n"
5113                "                          are + also +\n"
5114                "                          wrapped,\n"
5115                "                      in + addition) +\n"
5116                "          to + being + bin - packed,\n"
5117                "      arg3);\n"
5118                "}",
5119                Style);
5120 }
5121 
5122 TEST_F(FormatTest, ConstructorInitializers) {
5123   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
5124   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
5125                getLLVMStyleWithColumns(45));
5126   verifyFormat("Constructor()\n"
5127                "    : Inttializer(FitsOnTheLine) {}",
5128                getLLVMStyleWithColumns(44));
5129   verifyFormat("Constructor()\n"
5130                "    : Inttializer(FitsOnTheLine) {}",
5131                getLLVMStyleWithColumns(43));
5132 
5133   verifyFormat("template <typename T>\n"
5134                "Constructor() : Initializer(FitsOnTheLine) {}",
5135                getLLVMStyleWithColumns(45));
5136 
5137   verifyFormat(
5138       "SomeClass::Constructor()\n"
5139       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
5140 
5141   verifyFormat(
5142       "SomeClass::Constructor()\n"
5143       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5144       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
5145   verifyFormat(
5146       "SomeClass::Constructor()\n"
5147       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5148       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
5149   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5150                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5151                "    : aaaaaaaaaa(aaaaaa) {}");
5152 
5153   verifyFormat("Constructor()\n"
5154                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5155                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5156                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5157                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
5158 
5159   verifyFormat("Constructor()\n"
5160                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5161                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5162 
5163   verifyFormat("Constructor(int Parameter = 0)\n"
5164                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
5165                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
5166   verifyFormat("Constructor()\n"
5167                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
5168                "}",
5169                getLLVMStyleWithColumns(60));
5170   verifyFormat("Constructor()\n"
5171                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5172                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
5173 
5174   // Here a line could be saved by splitting the second initializer onto two
5175   // lines, but that is not desirable.
5176   verifyFormat("Constructor()\n"
5177                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
5178                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
5179                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5180 
5181   FormatStyle OnePerLine = getLLVMStyle();
5182   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5183   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
5184   verifyFormat("SomeClass::Constructor()\n"
5185                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5186                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5187                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5188                OnePerLine);
5189   verifyFormat("SomeClass::Constructor()\n"
5190                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
5191                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5192                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5193                OnePerLine);
5194   verifyFormat("MyClass::MyClass(int var)\n"
5195                "    : some_var_(var),            // 4 space indent\n"
5196                "      some_other_var_(var + 1) { // lined up\n"
5197                "}",
5198                OnePerLine);
5199   verifyFormat("Constructor()\n"
5200                "    : aaaaa(aaaaaa),\n"
5201                "      aaaaa(aaaaaa),\n"
5202                "      aaaaa(aaaaaa),\n"
5203                "      aaaaa(aaaaaa),\n"
5204                "      aaaaa(aaaaaa) {}",
5205                OnePerLine);
5206   verifyFormat("Constructor()\n"
5207                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
5208                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
5209                OnePerLine);
5210   OnePerLine.BinPackParameters = false;
5211   verifyFormat(
5212       "Constructor()\n"
5213       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5214       "          aaaaaaaaaaa().aaa(),\n"
5215       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5216       OnePerLine);
5217   OnePerLine.ColumnLimit = 60;
5218   verifyFormat("Constructor()\n"
5219                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
5220                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
5221                OnePerLine);
5222 
5223   EXPECT_EQ("Constructor()\n"
5224             "    : // Comment forcing unwanted break.\n"
5225             "      aaaa(aaaa) {}",
5226             format("Constructor() :\n"
5227                    "    // Comment forcing unwanted break.\n"
5228                    "    aaaa(aaaa) {}"));
5229 }
5230 
5231 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
5232   FormatStyle Style = getLLVMStyle();
5233   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
5234   Style.ColumnLimit = 60;
5235   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5236   Style.AllowAllConstructorInitializersOnNextLine = true;
5237   Style.BinPackParameters = false;
5238 
5239   for (int i = 0; i < 4; ++i) {
5240     // Test all combinations of parameters that should not have an effect.
5241     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
5242     Style.AllowAllArgumentsOnNextLine = i & 2;
5243 
5244     Style.AllowAllConstructorInitializersOnNextLine = true;
5245     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
5246     verifyFormat("Constructor()\n"
5247                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
5248                  Style);
5249     verifyFormat("Constructor() : a(a), b(b) {}", Style);
5250 
5251     Style.AllowAllConstructorInitializersOnNextLine = false;
5252     verifyFormat("Constructor()\n"
5253                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
5254                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
5255                  Style);
5256     verifyFormat("Constructor() : a(a), b(b) {}", Style);
5257 
5258     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
5259     Style.AllowAllConstructorInitializersOnNextLine = true;
5260     verifyFormat("Constructor()\n"
5261                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
5262                  Style);
5263 
5264     Style.AllowAllConstructorInitializersOnNextLine = false;
5265     verifyFormat("Constructor()\n"
5266                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
5267                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
5268                  Style);
5269 
5270     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
5271     Style.AllowAllConstructorInitializersOnNextLine = true;
5272     verifyFormat("Constructor() :\n"
5273                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
5274                  Style);
5275 
5276     Style.AllowAllConstructorInitializersOnNextLine = false;
5277     verifyFormat("Constructor() :\n"
5278                  "    aaaaaaaaaaaaaaaaaa(a),\n"
5279                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
5280                  Style);
5281   }
5282 
5283   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
5284   // AllowAllConstructorInitializersOnNextLine in all
5285   // BreakConstructorInitializers modes
5286   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
5287   Style.AllowAllParametersOfDeclarationOnNextLine = true;
5288   Style.AllowAllConstructorInitializersOnNextLine = false;
5289   verifyFormat("SomeClassWithALongName::Constructor(\n"
5290                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
5291                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
5292                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
5293                Style);
5294 
5295   Style.AllowAllConstructorInitializersOnNextLine = true;
5296   verifyFormat("SomeClassWithALongName::Constructor(\n"
5297                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
5298                "    int bbbbbbbbbbbbb,\n"
5299                "    int cccccccccccccccc)\n"
5300                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
5301                Style);
5302 
5303   Style.AllowAllParametersOfDeclarationOnNextLine = false;
5304   Style.AllowAllConstructorInitializersOnNextLine = false;
5305   verifyFormat("SomeClassWithALongName::Constructor(\n"
5306                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
5307                "    int bbbbbbbbbbbbb)\n"
5308                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
5309                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
5310                Style);
5311 
5312   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
5313 
5314   Style.AllowAllParametersOfDeclarationOnNextLine = true;
5315   verifyFormat("SomeClassWithALongName::Constructor(\n"
5316                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
5317                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
5318                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
5319                Style);
5320 
5321   Style.AllowAllConstructorInitializersOnNextLine = true;
5322   verifyFormat("SomeClassWithALongName::Constructor(\n"
5323                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
5324                "    int bbbbbbbbbbbbb,\n"
5325                "    int cccccccccccccccc)\n"
5326                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
5327                Style);
5328 
5329   Style.AllowAllParametersOfDeclarationOnNextLine = false;
5330   Style.AllowAllConstructorInitializersOnNextLine = false;
5331   verifyFormat("SomeClassWithALongName::Constructor(\n"
5332                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
5333                "    int bbbbbbbbbbbbb)\n"
5334                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
5335                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
5336                Style);
5337 
5338   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
5339   Style.AllowAllParametersOfDeclarationOnNextLine = true;
5340   verifyFormat("SomeClassWithALongName::Constructor(\n"
5341                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
5342                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
5343                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
5344                Style);
5345 
5346   Style.AllowAllConstructorInitializersOnNextLine = true;
5347   verifyFormat("SomeClassWithALongName::Constructor(\n"
5348                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
5349                "    int bbbbbbbbbbbbb,\n"
5350                "    int cccccccccccccccc) :\n"
5351                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
5352                Style);
5353 
5354   Style.AllowAllParametersOfDeclarationOnNextLine = false;
5355   Style.AllowAllConstructorInitializersOnNextLine = false;
5356   verifyFormat("SomeClassWithALongName::Constructor(\n"
5357                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
5358                "    int bbbbbbbbbbbbb) :\n"
5359                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
5360                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
5361                Style);
5362 }
5363 
5364 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
5365   FormatStyle Style = getLLVMStyle();
5366   Style.ColumnLimit = 60;
5367   Style.BinPackArguments = false;
5368   for (int i = 0; i < 4; ++i) {
5369     // Test all combinations of parameters that should not have an effect.
5370     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
5371     Style.AllowAllConstructorInitializersOnNextLine = i & 2;
5372 
5373     Style.AllowAllArgumentsOnNextLine = true;
5374     verifyFormat("void foo() {\n"
5375                  "  FunctionCallWithReallyLongName(\n"
5376                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
5377                  "}",
5378                  Style);
5379     Style.AllowAllArgumentsOnNextLine = false;
5380     verifyFormat("void foo() {\n"
5381                  "  FunctionCallWithReallyLongName(\n"
5382                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5383                  "      bbbbbbbbbbbb);\n"
5384                  "}",
5385                  Style);
5386 
5387     Style.AllowAllArgumentsOnNextLine = true;
5388     verifyFormat("void foo() {\n"
5389                  "  auto VariableWithReallyLongName = {\n"
5390                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
5391                  "}",
5392                  Style);
5393     Style.AllowAllArgumentsOnNextLine = false;
5394     verifyFormat("void foo() {\n"
5395                  "  auto VariableWithReallyLongName = {\n"
5396                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5397                  "      bbbbbbbbbbbb};\n"
5398                  "}",
5399                  Style);
5400   }
5401 
5402   // This parameter should not affect declarations.
5403   Style.BinPackParameters = false;
5404   Style.AllowAllArgumentsOnNextLine = false;
5405   Style.AllowAllParametersOfDeclarationOnNextLine = true;
5406   verifyFormat("void FunctionCallWithReallyLongName(\n"
5407                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
5408                Style);
5409   Style.AllowAllParametersOfDeclarationOnNextLine = false;
5410   verifyFormat("void FunctionCallWithReallyLongName(\n"
5411                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
5412                "    int bbbbbbbbbbbb);",
5413                Style);
5414 }
5415 
5416 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
5417   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
5418   // and BAS_Align.
5419   auto Style = getLLVMStyle();
5420   Style.ColumnLimit = 35;
5421   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
5422                     "void functionDecl(int A, int B, int C);";
5423   Style.AllowAllArgumentsOnNextLine = false;
5424   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5425   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5426                       "    paramC);\n"
5427                       "void functionDecl(int A, int B,\n"
5428                       "    int C);"),
5429             format(Input, Style));
5430   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5431   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5432                       "             paramC);\n"
5433                       "void functionDecl(int A, int B,\n"
5434                       "                  int C);"),
5435             format(Input, Style));
5436   // However, BAS_AlwaysBreak should take precedence over
5437   // AllowAllArgumentsOnNextLine.
5438   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5439   EXPECT_EQ(StringRef("functionCall(\n"
5440                       "    paramA, paramB, paramC);\n"
5441                       "void functionDecl(\n"
5442                       "    int A, int B, int C);"),
5443             format(Input, Style));
5444 
5445   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
5446   // first argument.
5447   Style.AllowAllArgumentsOnNextLine = true;
5448   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5449   EXPECT_EQ(StringRef("functionCall(\n"
5450                       "    paramA, paramB, paramC);\n"
5451                       "void functionDecl(\n"
5452                       "    int A, int B, int C);"),
5453             format(Input, Style));
5454   // It wouldn't fit on one line with aligned parameters so this setting
5455   // doesn't change anything for BAS_Align.
5456   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5457   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5458                       "             paramC);\n"
5459                       "void functionDecl(int A, int B,\n"
5460                       "                  int C);"),
5461             format(Input, Style));
5462   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5463   EXPECT_EQ(StringRef("functionCall(\n"
5464                       "    paramA, paramB, paramC);\n"
5465                       "void functionDecl(\n"
5466                       "    int A, int B, int C);"),
5467             format(Input, Style));
5468 }
5469 
5470 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
5471   FormatStyle Style = getLLVMStyle();
5472   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
5473 
5474   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
5475   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
5476                getStyleWithColumns(Style, 45));
5477   verifyFormat("Constructor() :\n"
5478                "    Initializer(FitsOnTheLine) {}",
5479                getStyleWithColumns(Style, 44));
5480   verifyFormat("Constructor() :\n"
5481                "    Initializer(FitsOnTheLine) {}",
5482                getStyleWithColumns(Style, 43));
5483 
5484   verifyFormat("template <typename T>\n"
5485                "Constructor() : Initializer(FitsOnTheLine) {}",
5486                getStyleWithColumns(Style, 50));
5487   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5488   verifyFormat(
5489       "SomeClass::Constructor() :\n"
5490       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5491       Style);
5492 
5493   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
5494   verifyFormat(
5495       "SomeClass::Constructor() :\n"
5496       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5497       Style);
5498 
5499   verifyFormat(
5500       "SomeClass::Constructor() :\n"
5501       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5502       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5503       Style);
5504   verifyFormat(
5505       "SomeClass::Constructor() :\n"
5506       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5507       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5508       Style);
5509   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5510                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
5511                "    aaaaaaaaaa(aaaaaa) {}",
5512                Style);
5513 
5514   verifyFormat("Constructor() :\n"
5515                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5516                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5517                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5518                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
5519                Style);
5520 
5521   verifyFormat("Constructor() :\n"
5522                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5523                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5524                Style);
5525 
5526   verifyFormat("Constructor(int Parameter = 0) :\n"
5527                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
5528                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
5529                Style);
5530   verifyFormat("Constructor() :\n"
5531                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
5532                "}",
5533                getStyleWithColumns(Style, 60));
5534   verifyFormat("Constructor() :\n"
5535                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5536                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
5537                Style);
5538 
5539   // Here a line could be saved by splitting the second initializer onto two
5540   // lines, but that is not desirable.
5541   verifyFormat("Constructor() :\n"
5542                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
5543                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
5544                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5545                Style);
5546 
5547   FormatStyle OnePerLine = Style;
5548   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5549   OnePerLine.AllowAllConstructorInitializersOnNextLine = false;
5550   verifyFormat("SomeClass::Constructor() :\n"
5551                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5552                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5553                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5554                OnePerLine);
5555   verifyFormat("SomeClass::Constructor() :\n"
5556                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
5557                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5558                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5559                OnePerLine);
5560   verifyFormat("MyClass::MyClass(int var) :\n"
5561                "    some_var_(var),            // 4 space indent\n"
5562                "    some_other_var_(var + 1) { // lined up\n"
5563                "}",
5564                OnePerLine);
5565   verifyFormat("Constructor() :\n"
5566                "    aaaaa(aaaaaa),\n"
5567                "    aaaaa(aaaaaa),\n"
5568                "    aaaaa(aaaaaa),\n"
5569                "    aaaaa(aaaaaa),\n"
5570                "    aaaaa(aaaaaa) {}",
5571                OnePerLine);
5572   verifyFormat("Constructor() :\n"
5573                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
5574                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
5575                OnePerLine);
5576   OnePerLine.BinPackParameters = false;
5577   verifyFormat("Constructor() :\n"
5578                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5579                "        aaaaaaaaaaa().aaa(),\n"
5580                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5581                OnePerLine);
5582   OnePerLine.ColumnLimit = 60;
5583   verifyFormat("Constructor() :\n"
5584                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
5585                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
5586                OnePerLine);
5587 
5588   EXPECT_EQ("Constructor() :\n"
5589             "    // Comment forcing unwanted break.\n"
5590             "    aaaa(aaaa) {}",
5591             format("Constructor() :\n"
5592                    "    // Comment forcing unwanted break.\n"
5593                    "    aaaa(aaaa) {}",
5594                    Style));
5595 
5596   Style.ColumnLimit = 0;
5597   verifyFormat("SomeClass::Constructor() :\n"
5598                "    a(a) {}",
5599                Style);
5600   verifyFormat("SomeClass::Constructor() noexcept :\n"
5601                "    a(a) {}",
5602                Style);
5603   verifyFormat("SomeClass::Constructor() :\n"
5604                "    a(a), b(b), c(c) {}",
5605                Style);
5606   verifyFormat("SomeClass::Constructor() :\n"
5607                "    a(a) {\n"
5608                "  foo();\n"
5609                "  bar();\n"
5610                "}",
5611                Style);
5612 
5613   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
5614   verifyFormat("SomeClass::Constructor() :\n"
5615                "    a(a), b(b), c(c) {\n"
5616                "}",
5617                Style);
5618   verifyFormat("SomeClass::Constructor() :\n"
5619                "    a(a) {\n"
5620                "}",
5621                Style);
5622 
5623   Style.ColumnLimit = 80;
5624   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
5625   Style.ConstructorInitializerIndentWidth = 2;
5626   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
5627   verifyFormat("SomeClass::Constructor() :\n"
5628                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5629                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
5630                Style);
5631 
5632   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
5633   // well
5634   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
5635   verifyFormat(
5636       "class SomeClass\n"
5637       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5638       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5639       Style);
5640   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
5641   verifyFormat(
5642       "class SomeClass\n"
5643       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5644       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5645       Style);
5646   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
5647   verifyFormat(
5648       "class SomeClass :\n"
5649       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5650       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5651       Style);
5652   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
5653   verifyFormat(
5654       "class SomeClass\n"
5655       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5656       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5657       Style);
5658 }
5659 
5660 #ifndef EXPENSIVE_CHECKS
5661 // Expensive checks enables libstdc++ checking which includes validating the
5662 // state of ranges used in std::priority_queue - this blows out the
5663 // runtime/scalability of the function and makes this test unacceptably slow.
5664 TEST_F(FormatTest, MemoizationTests) {
5665   // This breaks if the memoization lookup does not take \c Indent and
5666   // \c LastSpace into account.
5667   verifyFormat(
5668       "extern CFRunLoopTimerRef\n"
5669       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
5670       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
5671       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
5672       "                     CFRunLoopTimerContext *context) {}");
5673 
5674   // Deep nesting somewhat works around our memoization.
5675   verifyFormat(
5676       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5677       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5678       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5679       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5680       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
5681       getLLVMStyleWithColumns(65));
5682   verifyFormat(
5683       "aaaaa(\n"
5684       "    aaaaa,\n"
5685       "    aaaaa(\n"
5686       "        aaaaa,\n"
5687       "        aaaaa(\n"
5688       "            aaaaa,\n"
5689       "            aaaaa(\n"
5690       "                aaaaa,\n"
5691       "                aaaaa(\n"
5692       "                    aaaaa,\n"
5693       "                    aaaaa(\n"
5694       "                        aaaaa,\n"
5695       "                        aaaaa(\n"
5696       "                            aaaaa,\n"
5697       "                            aaaaa(\n"
5698       "                                aaaaa,\n"
5699       "                                aaaaa(\n"
5700       "                                    aaaaa,\n"
5701       "                                    aaaaa(\n"
5702       "                                        aaaaa,\n"
5703       "                                        aaaaa(\n"
5704       "                                            aaaaa,\n"
5705       "                                            aaaaa(\n"
5706       "                                                aaaaa,\n"
5707       "                                                aaaaa))))))))))));",
5708       getLLVMStyleWithColumns(65));
5709   verifyFormat(
5710       "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"
5711       "                                  a),\n"
5712       "                                a),\n"
5713       "                              a),\n"
5714       "                            a),\n"
5715       "                          a),\n"
5716       "                        a),\n"
5717       "                      a),\n"
5718       "                    a),\n"
5719       "                  a),\n"
5720       "                a),\n"
5721       "              a),\n"
5722       "            a),\n"
5723       "          a),\n"
5724       "        a),\n"
5725       "      a),\n"
5726       "    a),\n"
5727       "  a)",
5728       getLLVMStyleWithColumns(65));
5729 
5730   // This test takes VERY long when memoization is broken.
5731   FormatStyle OnePerLine = getLLVMStyle();
5732   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5733   OnePerLine.BinPackParameters = false;
5734   std::string input = "Constructor()\n"
5735                       "    : aaaa(a,\n";
5736   for (unsigned i = 0, e = 80; i != e; ++i) {
5737     input += "           a,\n";
5738   }
5739   input += "           a) {}";
5740   verifyFormat(input, OnePerLine);
5741 }
5742 #endif
5743 
5744 TEST_F(FormatTest, BreaksAsHighAsPossible) {
5745   verifyFormat(
5746       "void f() {\n"
5747       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
5748       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
5749       "    f();\n"
5750       "}");
5751   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
5752                "    Intervals[i - 1].getRange().getLast()) {\n}");
5753 }
5754 
5755 TEST_F(FormatTest, BreaksFunctionDeclarations) {
5756   // Principially, we break function declarations in a certain order:
5757   // 1) break amongst arguments.
5758   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
5759                "                              Cccccccccccccc cccccccccccccc);");
5760   verifyFormat("template <class TemplateIt>\n"
5761                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
5762                "                            TemplateIt *stop) {}");
5763 
5764   // 2) break after return type.
5765   verifyFormat(
5766       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5767       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
5768       getGoogleStyle());
5769 
5770   // 3) break after (.
5771   verifyFormat(
5772       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
5773       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
5774       getGoogleStyle());
5775 
5776   // 4) break before after nested name specifiers.
5777   verifyFormat(
5778       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5779       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
5780       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
5781       getGoogleStyle());
5782 
5783   // However, there are exceptions, if a sufficient amount of lines can be
5784   // saved.
5785   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
5786   // more adjusting.
5787   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5788                "                                  Cccccccccccccc cccccccccc,\n"
5789                "                                  Cccccccccccccc cccccccccc,\n"
5790                "                                  Cccccccccccccc cccccccccc,\n"
5791                "                                  Cccccccccccccc cccccccccc);");
5792   verifyFormat(
5793       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5794       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5795       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5796       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
5797       getGoogleStyle());
5798   verifyFormat(
5799       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5800       "                                          Cccccccccccccc cccccccccc,\n"
5801       "                                          Cccccccccccccc cccccccccc,\n"
5802       "                                          Cccccccccccccc cccccccccc,\n"
5803       "                                          Cccccccccccccc cccccccccc,\n"
5804       "                                          Cccccccccccccc cccccccccc,\n"
5805       "                                          Cccccccccccccc cccccccccc);");
5806   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5807                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5808                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5809                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5810                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
5811 
5812   // Break after multi-line parameters.
5813   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5814                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5815                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5816                "    bbbb bbbb);");
5817   verifyFormat("void SomeLoooooooooooongFunction(\n"
5818                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
5819                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5820                "    int bbbbbbbbbbbbb);");
5821 
5822   // Treat overloaded operators like other functions.
5823   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5824                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
5825   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5826                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
5827   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5828                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
5829   verifyGoogleFormat(
5830       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
5831       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5832   verifyGoogleFormat(
5833       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
5834       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5835   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5836                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5837   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
5838                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5839   verifyGoogleFormat(
5840       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
5841       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5842       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
5843   verifyGoogleFormat("template <typename T>\n"
5844                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5845                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
5846                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
5847 
5848   FormatStyle Style = getLLVMStyle();
5849   Style.PointerAlignment = FormatStyle::PAS_Left;
5850   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5851                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
5852                Style);
5853   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
5854                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5855                Style);
5856 }
5857 
5858 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
5859   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
5860   // Prefer keeping `::` followed by `operator` together.
5861   EXPECT_EQ("const aaaa::bbbbbbb &\n"
5862             "ccccccccc::operator++() {\n"
5863             "  stuff();\n"
5864             "}",
5865             format("const aaaa::bbbbbbb\n"
5866                    "&ccccccccc::operator++() { stuff(); }",
5867                    getLLVMStyleWithColumns(40)));
5868 }
5869 
5870 TEST_F(FormatTest, TrailingReturnType) {
5871   verifyFormat("auto foo() -> int;\n");
5872   // correct trailing return type spacing
5873   verifyFormat("auto operator->() -> int;\n");
5874   verifyFormat("auto operator++(int) -> int;\n");
5875 
5876   verifyFormat("struct S {\n"
5877                "  auto bar() const -> int;\n"
5878                "};");
5879   verifyFormat("template <size_t Order, typename T>\n"
5880                "auto load_img(const std::string &filename)\n"
5881                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
5882   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
5883                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
5884   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
5885   verifyFormat("template <typename T>\n"
5886                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
5887                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
5888 
5889   // Not trailing return types.
5890   verifyFormat("void f() { auto a = b->c(); }");
5891 }
5892 
5893 TEST_F(FormatTest, DeductionGuides) {
5894   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
5895   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
5896   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
5897   verifyFormat(
5898       "template <class... T>\n"
5899       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
5900   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
5901   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
5902   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
5903   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
5904   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
5905   verifyFormat("template <class T> x() -> x<1>;");
5906   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
5907 
5908   // Ensure not deduction guides.
5909   verifyFormat("c()->f<int>();");
5910   verifyFormat("x()->foo<1>;");
5911   verifyFormat("x = p->foo<3>();");
5912   verifyFormat("x()->x<1>();");
5913   verifyFormat("x()->x<1>;");
5914 }
5915 
5916 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
5917   // Avoid breaking before trailing 'const' or other trailing annotations, if
5918   // they are not function-like.
5919   FormatStyle Style = getGoogleStyle();
5920   Style.ColumnLimit = 47;
5921   verifyFormat("void someLongFunction(\n"
5922                "    int someLoooooooooooooongParameter) const {\n}",
5923                getLLVMStyleWithColumns(47));
5924   verifyFormat("LoooooongReturnType\n"
5925                "someLoooooooongFunction() const {}",
5926                getLLVMStyleWithColumns(47));
5927   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
5928                "    const {}",
5929                Style);
5930   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5931                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
5932   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5933                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
5934   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5935                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
5936   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
5937                "                   aaaaaaaaaaa aaaaa) const override;");
5938   verifyGoogleFormat(
5939       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5940       "    const override;");
5941 
5942   // Even if the first parameter has to be wrapped.
5943   verifyFormat("void someLongFunction(\n"
5944                "    int someLongParameter) const {}",
5945                getLLVMStyleWithColumns(46));
5946   verifyFormat("void someLongFunction(\n"
5947                "    int someLongParameter) const {}",
5948                Style);
5949   verifyFormat("void someLongFunction(\n"
5950                "    int someLongParameter) override {}",
5951                Style);
5952   verifyFormat("void someLongFunction(\n"
5953                "    int someLongParameter) OVERRIDE {}",
5954                Style);
5955   verifyFormat("void someLongFunction(\n"
5956                "    int someLongParameter) final {}",
5957                Style);
5958   verifyFormat("void someLongFunction(\n"
5959                "    int someLongParameter) FINAL {}",
5960                Style);
5961   verifyFormat("void someLongFunction(\n"
5962                "    int parameter) const override {}",
5963                Style);
5964 
5965   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
5966   verifyFormat("void someLongFunction(\n"
5967                "    int someLongParameter) const\n"
5968                "{\n"
5969                "}",
5970                Style);
5971 
5972   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
5973   verifyFormat("void someLongFunction(\n"
5974                "    int someLongParameter) const\n"
5975                "  {\n"
5976                "  }",
5977                Style);
5978 
5979   // Unless these are unknown annotations.
5980   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
5981                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5982                "    LONG_AND_UGLY_ANNOTATION;");
5983 
5984   // Breaking before function-like trailing annotations is fine to keep them
5985   // close to their arguments.
5986   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5987                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5988   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5989                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5990   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5991                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
5992   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
5993                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
5994   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
5995 
5996   verifyFormat(
5997       "void aaaaaaaaaaaaaaaaaa()\n"
5998       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
5999       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
6000   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6001                "    __attribute__((unused));");
6002   verifyGoogleFormat(
6003       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6004       "    GUARDED_BY(aaaaaaaaaaaa);");
6005   verifyGoogleFormat(
6006       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6007       "    GUARDED_BY(aaaaaaaaaaaa);");
6008   verifyGoogleFormat(
6009       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6010       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6011   verifyGoogleFormat(
6012       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6013       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
6014 }
6015 
6016 TEST_F(FormatTest, FunctionAnnotations) {
6017   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6018                "int OldFunction(const string &parameter) {}");
6019   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6020                "string OldFunction(const string &parameter) {}");
6021   verifyFormat("template <typename T>\n"
6022                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6023                "string OldFunction(const string &parameter) {}");
6024 
6025   // Not function annotations.
6026   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6027                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
6028   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
6029                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
6030   verifyFormat("MACRO(abc).function() // wrap\n"
6031                "    << abc;");
6032   verifyFormat("MACRO(abc)->function() // wrap\n"
6033                "    << abc;");
6034   verifyFormat("MACRO(abc)::function() // wrap\n"
6035                "    << abc;");
6036 }
6037 
6038 TEST_F(FormatTest, BreaksDesireably) {
6039   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6040                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6041                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
6042   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6043                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
6044                "}");
6045 
6046   verifyFormat(
6047       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6048       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6049 
6050   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6051                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6052                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6053 
6054   verifyFormat(
6055       "aaaaaaaa(aaaaaaaaaaaaa,\n"
6056       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6057       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
6058       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6059       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
6060 
6061   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6062                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6063 
6064   verifyFormat(
6065       "void f() {\n"
6066       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
6067       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
6068       "}");
6069   verifyFormat(
6070       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6071       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6072   verifyFormat(
6073       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6074       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6075   verifyFormat(
6076       "aaaaaa(aaa,\n"
6077       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6078       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6079       "       aaaa);");
6080   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6081                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6082                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6083 
6084   // Indent consistently independent of call expression and unary operator.
6085   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6086                "    dddddddddddddddddddddddddddddd));");
6087   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6088                "    dddddddddddddddddddddddddddddd));");
6089   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
6090                "    dddddddddddddddddddddddddddddd));");
6091 
6092   // This test case breaks on an incorrect memoization, i.e. an optimization not
6093   // taking into account the StopAt value.
6094   verifyFormat(
6095       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6096       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6097       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6098       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6099 
6100   verifyFormat("{\n  {\n    {\n"
6101                "      Annotation.SpaceRequiredBefore =\n"
6102                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
6103                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
6104                "    }\n  }\n}");
6105 
6106   // Break on an outer level if there was a break on an inner level.
6107   EXPECT_EQ("f(g(h(a, // comment\n"
6108             "      b, c),\n"
6109             "    d, e),\n"
6110             "  x, y);",
6111             format("f(g(h(a, // comment\n"
6112                    "    b, c), d, e), x, y);"));
6113 
6114   // Prefer breaking similar line breaks.
6115   verifyFormat(
6116       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
6117       "                             NSTrackingMouseEnteredAndExited |\n"
6118       "                             NSTrackingActiveAlways;");
6119 }
6120 
6121 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
6122   FormatStyle NoBinPacking = getGoogleStyle();
6123   NoBinPacking.BinPackParameters = false;
6124   NoBinPacking.BinPackArguments = true;
6125   verifyFormat("void f() {\n"
6126                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
6127                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
6128                "}",
6129                NoBinPacking);
6130   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
6131                "       int aaaaaaaaaaaaaaaaaaaa,\n"
6132                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6133                NoBinPacking);
6134 
6135   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
6136   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6137                "                        vector<int> bbbbbbbbbbbbbbb);",
6138                NoBinPacking);
6139   // FIXME: This behavior difference is probably not wanted. However, currently
6140   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
6141   // template arguments from BreakBeforeParameter being set because of the
6142   // one-per-line formatting.
6143   verifyFormat(
6144       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
6145       "                                             aaaaaaaaaa> aaaaaaaaaa);",
6146       NoBinPacking);
6147   verifyFormat(
6148       "void fffffffffff(\n"
6149       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
6150       "        aaaaaaaaaa);");
6151 }
6152 
6153 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
6154   FormatStyle NoBinPacking = getGoogleStyle();
6155   NoBinPacking.BinPackParameters = false;
6156   NoBinPacking.BinPackArguments = false;
6157   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
6158                "  aaaaaaaaaaaaaaaaaaaa,\n"
6159                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
6160                NoBinPacking);
6161   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
6162                "        aaaaaaaaaaaaa,\n"
6163                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
6164                NoBinPacking);
6165   verifyFormat(
6166       "aaaaaaaa(aaaaaaaaaaaaa,\n"
6167       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6168       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
6169       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6170       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
6171       NoBinPacking);
6172   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
6173                "    .aaaaaaaaaaaaaaaaaa();",
6174                NoBinPacking);
6175   verifyFormat("void f() {\n"
6176                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6177                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
6178                "}",
6179                NoBinPacking);
6180 
6181   verifyFormat(
6182       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6183       "             aaaaaaaaaaaa,\n"
6184       "             aaaaaaaaaaaa);",
6185       NoBinPacking);
6186   verifyFormat(
6187       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
6188       "                               ddddddddddddddddddddddddddddd),\n"
6189       "             test);",
6190       NoBinPacking);
6191 
6192   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
6193                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
6194                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
6195                "    aaaaaaaaaaaaaaaaaa;",
6196                NoBinPacking);
6197   verifyFormat("a(\"a\"\n"
6198                "  \"a\",\n"
6199                "  a);");
6200 
6201   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
6202   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
6203                "                aaaaaaaaa,\n"
6204                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6205                NoBinPacking);
6206   verifyFormat(
6207       "void f() {\n"
6208       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
6209       "      .aaaaaaa();\n"
6210       "}",
6211       NoBinPacking);
6212   verifyFormat(
6213       "template <class SomeType, class SomeOtherType>\n"
6214       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
6215       NoBinPacking);
6216 }
6217 
6218 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
6219   FormatStyle Style = getLLVMStyleWithColumns(15);
6220   Style.ExperimentalAutoDetectBinPacking = true;
6221   EXPECT_EQ("aaa(aaaa,\n"
6222             "    aaaa,\n"
6223             "    aaaa);\n"
6224             "aaa(aaaa,\n"
6225             "    aaaa,\n"
6226             "    aaaa);",
6227             format("aaa(aaaa,\n" // one-per-line
6228                    "  aaaa,\n"
6229                    "    aaaa  );\n"
6230                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
6231                    Style));
6232   EXPECT_EQ("aaa(aaaa, aaaa,\n"
6233             "    aaaa);\n"
6234             "aaa(aaaa, aaaa,\n"
6235             "    aaaa);",
6236             format("aaa(aaaa,  aaaa,\n" // bin-packed
6237                    "    aaaa  );\n"
6238                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
6239                    Style));
6240 }
6241 
6242 TEST_F(FormatTest, FormatsBuilderPattern) {
6243   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
6244                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
6245                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
6246                "    .StartsWith(\".init\", ORDER_INIT)\n"
6247                "    .StartsWith(\".fini\", ORDER_FINI)\n"
6248                "    .StartsWith(\".hash\", ORDER_HASH)\n"
6249                "    .Default(ORDER_TEXT);\n");
6250 
6251   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
6252                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
6253   verifyFormat("aaaaaaa->aaaaaaa\n"
6254                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6255                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6256                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
6257   verifyFormat(
6258       "aaaaaaa->aaaaaaa\n"
6259       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6260       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
6261   verifyFormat(
6262       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
6263       "    aaaaaaaaaaaaaa);");
6264   verifyFormat(
6265       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
6266       "    aaaaaa->aaaaaaaaaaaa()\n"
6267       "        ->aaaaaaaaaaaaaaaa(\n"
6268       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6269       "        ->aaaaaaaaaaaaaaaaa();");
6270   verifyGoogleFormat(
6271       "void f() {\n"
6272       "  someo->Add((new util::filetools::Handler(dir))\n"
6273       "                 ->OnEvent1(NewPermanentCallback(\n"
6274       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
6275       "                 ->OnEvent2(NewPermanentCallback(\n"
6276       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
6277       "                 ->OnEvent3(NewPermanentCallback(\n"
6278       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
6279       "                 ->OnEvent5(NewPermanentCallback(\n"
6280       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
6281       "                 ->OnEvent6(NewPermanentCallback(\n"
6282       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
6283       "}");
6284 
6285   verifyFormat(
6286       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
6287   verifyFormat("aaaaaaaaaaaaaaa()\n"
6288                "    .aaaaaaaaaaaaaaa()\n"
6289                "    .aaaaaaaaaaaaaaa()\n"
6290                "    .aaaaaaaaaaaaaaa()\n"
6291                "    .aaaaaaaaaaaaaaa();");
6292   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
6293                "    .aaaaaaaaaaaaaaa()\n"
6294                "    .aaaaaaaaaaaaaaa()\n"
6295                "    .aaaaaaaaaaaaaaa();");
6296   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
6297                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
6298                "    .aaaaaaaaaaaaaaa();");
6299   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
6300                "    ->aaaaaaaaaaaaaae(0)\n"
6301                "    ->aaaaaaaaaaaaaaa();");
6302 
6303   // Don't linewrap after very short segments.
6304   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6305                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6306                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6307   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6308                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6309                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6310   verifyFormat("aaa()\n"
6311                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6312                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6313                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6314 
6315   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
6316                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6317                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
6318   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
6319                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
6320                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
6321 
6322   // Prefer not to break after empty parentheses.
6323   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
6324                "    First->LastNewlineOffset);");
6325 
6326   // Prefer not to create "hanging" indents.
6327   verifyFormat(
6328       "return !soooooooooooooome_map\n"
6329       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6330       "            .second;");
6331   verifyFormat(
6332       "return aaaaaaaaaaaaaaaa\n"
6333       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
6334       "    .aaaa(aaaaaaaaaaaaaa);");
6335   // No hanging indent here.
6336   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
6337                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6338   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
6339                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6340   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
6341                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6342                getLLVMStyleWithColumns(60));
6343   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
6344                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
6345                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6346                getLLVMStyleWithColumns(59));
6347   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6348                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6349                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6350 
6351   // Dont break if only closing statements before member call
6352   verifyFormat("test() {\n"
6353                "  ([]() -> {\n"
6354                "    int b = 32;\n"
6355                "    return 3;\n"
6356                "  }).foo();\n"
6357                "}");
6358   verifyFormat("test() {\n"
6359                "  (\n"
6360                "      []() -> {\n"
6361                "        int b = 32;\n"
6362                "        return 3;\n"
6363                "      },\n"
6364                "      foo, bar)\n"
6365                "      .foo();\n"
6366                "}");
6367   verifyFormat("test() {\n"
6368                "  ([]() -> {\n"
6369                "    int b = 32;\n"
6370                "    return 3;\n"
6371                "  })\n"
6372                "      .foo()\n"
6373                "      .bar();\n"
6374                "}");
6375   verifyFormat("test() {\n"
6376                "  ([]() -> {\n"
6377                "    int b = 32;\n"
6378                "    return 3;\n"
6379                "  })\n"
6380                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
6381                "           \"bbbb\");\n"
6382                "}",
6383                getLLVMStyleWithColumns(30));
6384 }
6385 
6386 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
6387   verifyFormat(
6388       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6389       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
6390   verifyFormat(
6391       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
6392       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
6393 
6394   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
6395                "    ccccccccccccccccccccccccc) {\n}");
6396   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
6397                "    ccccccccccccccccccccccccc) {\n}");
6398 
6399   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
6400                "    ccccccccccccccccccccccccc) {\n}");
6401   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
6402                "    ccccccccccccccccccccccccc) {\n}");
6403 
6404   verifyFormat(
6405       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
6406       "    ccccccccccccccccccccccccc) {\n}");
6407   verifyFormat(
6408       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
6409       "    ccccccccccccccccccccccccc) {\n}");
6410 
6411   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
6412                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
6413                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
6414                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
6415   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
6416                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
6417                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
6418                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
6419 
6420   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
6421                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
6422                "    aaaaaaaaaaaaaaa != aa) {\n}");
6423   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
6424                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
6425                "    aaaaaaaaaaaaaaa != aa) {\n}");
6426 }
6427 
6428 TEST_F(FormatTest, BreaksAfterAssignments) {
6429   verifyFormat(
6430       "unsigned Cost =\n"
6431       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
6432       "                        SI->getPointerAddressSpaceee());\n");
6433   verifyFormat(
6434       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
6435       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
6436 
6437   verifyFormat(
6438       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
6439       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
6440   verifyFormat("unsigned OriginalStartColumn =\n"
6441                "    SourceMgr.getSpellingColumnNumber(\n"
6442                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
6443                "    1;");
6444 }
6445 
6446 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
6447   FormatStyle Style = getLLVMStyle();
6448   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6449                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
6450                Style);
6451 
6452   Style.PenaltyBreakAssignment = 20;
6453   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6454                "                                 cccccccccccccccccccccccccc;",
6455                Style);
6456 }
6457 
6458 TEST_F(FormatTest, AlignsAfterAssignments) {
6459   verifyFormat(
6460       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6461       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
6462   verifyFormat(
6463       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6464       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
6465   verifyFormat(
6466       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6467       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
6468   verifyFormat(
6469       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6470       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
6471   verifyFormat(
6472       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
6473       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
6474       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
6475 }
6476 
6477 TEST_F(FormatTest, AlignsAfterReturn) {
6478   verifyFormat(
6479       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6480       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
6481   verifyFormat(
6482       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6483       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
6484   verifyFormat(
6485       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
6486       "       aaaaaaaaaaaaaaaaaaaaaa();");
6487   verifyFormat(
6488       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
6489       "        aaaaaaaaaaaaaaaaaaaaaa());");
6490   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6491                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6492   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6493                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
6494                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6495   verifyFormat("return\n"
6496                "    // true if code is one of a or b.\n"
6497                "    code == a || code == b;");
6498 }
6499 
6500 TEST_F(FormatTest, AlignsAfterOpenBracket) {
6501   verifyFormat(
6502       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
6503       "                                                aaaaaaaaa aaaaaaa) {}");
6504   verifyFormat(
6505       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
6506       "                                               aaaaaaaaaaa aaaaaaaaa);");
6507   verifyFormat(
6508       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
6509       "                                             aaaaaaaaaaaaaaaaaaaaa));");
6510   FormatStyle Style = getLLVMStyle();
6511   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6512   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6513                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
6514                Style);
6515   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
6516                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
6517                Style);
6518   verifyFormat("SomeLongVariableName->someFunction(\n"
6519                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
6520                Style);
6521   verifyFormat(
6522       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
6523       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6524       Style);
6525   verifyFormat(
6526       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
6527       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6528       Style);
6529   verifyFormat(
6530       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
6531       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
6532       Style);
6533 
6534   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
6535                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
6536                "        b));",
6537                Style);
6538 
6539   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6540   Style.BinPackArguments = false;
6541   Style.BinPackParameters = false;
6542   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6543                "    aaaaaaaaaaa aaaaaaaa,\n"
6544                "    aaaaaaaaa aaaaaaa,\n"
6545                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6546                Style);
6547   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
6548                "    aaaaaaaaaaa aaaaaaaaa,\n"
6549                "    aaaaaaaaaaa aaaaaaaaa,\n"
6550                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6551                Style);
6552   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
6553                "    aaaaaaaaaaaaaaa,\n"
6554                "    aaaaaaaaaaaaaaaaaaaaa,\n"
6555                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
6556                Style);
6557   verifyFormat(
6558       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
6559       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
6560       Style);
6561   verifyFormat(
6562       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
6563       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
6564       Style);
6565   verifyFormat(
6566       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6567       "    aaaaaaaaaaaaaaaaaaaaa(\n"
6568       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
6569       "    aaaaaaaaaaaaaaaa);",
6570       Style);
6571   verifyFormat(
6572       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6573       "    aaaaaaaaaaaaaaaaaaaaa(\n"
6574       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
6575       "    aaaaaaaaaaaaaaaa);",
6576       Style);
6577 }
6578 
6579 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
6580   FormatStyle Style = getLLVMStyleWithColumns(40);
6581   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6582                "          bbbbbbbbbbbbbbbbbbbbbb);",
6583                Style);
6584   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6585   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6586   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6587                "          bbbbbbbbbbbbbbbbbbbbbb);",
6588                Style);
6589   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6590   Style.AlignOperands = FormatStyle::OAS_Align;
6591   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6592                "          bbbbbbbbbbbbbbbbbbbbbb);",
6593                Style);
6594   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6595   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6596   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6597                "    bbbbbbbbbbbbbbbbbbbbbb);",
6598                Style);
6599 }
6600 
6601 TEST_F(FormatTest, BreaksConditionalExpressions) {
6602   verifyFormat(
6603       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6604       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6605       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6606   verifyFormat(
6607       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
6608       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6609       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6610   verifyFormat(
6611       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6612       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6613   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
6614                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6615                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6616   verifyFormat(
6617       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
6618       "                                                    : aaaaaaaaaaaaa);");
6619   verifyFormat(
6620       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6621       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6622       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6623       "                   aaaaaaaaaaaaa);");
6624   verifyFormat(
6625       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6626       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6627       "                   aaaaaaaaaaaaa);");
6628   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6629                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6630                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6631                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6632                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6633   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6634                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6635                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6636                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6637                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6638                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6639                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6640   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6641                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6642                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6643                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6644                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6645   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6646                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6647                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6648   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6649                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6650                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6651                "        : aaaaaaaaaaaaaaaa;");
6652   verifyFormat(
6653       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6654       "    ? aaaaaaaaaaaaaaa\n"
6655       "    : aaaaaaaaaaaaaaa;");
6656   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6657                "          aaaaaaaaa\n"
6658                "      ? b\n"
6659                "      : c);");
6660   verifyFormat("return aaaa == bbbb\n"
6661                "           // comment\n"
6662                "           ? aaaa\n"
6663                "           : bbbb;");
6664   verifyFormat("unsigned Indent =\n"
6665                "    format(TheLine.First,\n"
6666                "           IndentForLevel[TheLine.Level] >= 0\n"
6667                "               ? IndentForLevel[TheLine.Level]\n"
6668                "               : TheLine * 2,\n"
6669                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
6670                getLLVMStyleWithColumns(60));
6671   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
6672                "                  ? aaaaaaaaaaaaaaa\n"
6673                "                  : bbbbbbbbbbbbbbb //\n"
6674                "                        ? ccccccccccccccc\n"
6675                "                        : ddddddddddddddd;");
6676   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
6677                "                  ? aaaaaaaaaaaaaaa\n"
6678                "                  : (bbbbbbbbbbbbbbb //\n"
6679                "                         ? ccccccccccccccc\n"
6680                "                         : ddddddddddddddd);");
6681   verifyFormat(
6682       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6683       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6684       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
6685       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
6686       "                                      : aaaaaaaaaa;");
6687   verifyFormat(
6688       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6689       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
6690       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6691 
6692   FormatStyle NoBinPacking = getLLVMStyle();
6693   NoBinPacking.BinPackArguments = false;
6694   verifyFormat(
6695       "void f() {\n"
6696       "  g(aaa,\n"
6697       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
6698       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6699       "        ? aaaaaaaaaaaaaaa\n"
6700       "        : aaaaaaaaaaaaaaa);\n"
6701       "}",
6702       NoBinPacking);
6703   verifyFormat(
6704       "void f() {\n"
6705       "  g(aaa,\n"
6706       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
6707       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6708       "        ?: aaaaaaaaaaaaaaa);\n"
6709       "}",
6710       NoBinPacking);
6711 
6712   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
6713                "             // comment.\n"
6714                "             ccccccccccccccccccccccccccccccccccccccc\n"
6715                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6716                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
6717 
6718   // Assignments in conditional expressions. Apparently not uncommon :-(.
6719   verifyFormat("return a != b\n"
6720                "           // comment\n"
6721                "           ? a = b\n"
6722                "           : a = b;");
6723   verifyFormat("return a != b\n"
6724                "           // comment\n"
6725                "           ? a = a != b\n"
6726                "                     // comment\n"
6727                "                     ? a = b\n"
6728                "                     : a\n"
6729                "           : a;\n");
6730   verifyFormat("return a != b\n"
6731                "           // comment\n"
6732                "           ? a\n"
6733                "           : a = a != b\n"
6734                "                     // comment\n"
6735                "                     ? a = b\n"
6736                "                     : a;");
6737 
6738   // Chained conditionals
6739   FormatStyle Style = getLLVMStyle();
6740   Style.ColumnLimit = 70;
6741   Style.AlignOperands = FormatStyle::OAS_Align;
6742   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6743                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6744                "                        : 3333333333333333;",
6745                Style);
6746   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6747                "       : bbbbbbbbbb     ? 2222222222222222\n"
6748                "                        : 3333333333333333;",
6749                Style);
6750   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
6751                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6752                "                          : 3333333333333333;",
6753                Style);
6754   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6755                "       : bbbbbbbbbbbbbb ? 222222\n"
6756                "                        : 333333;",
6757                Style);
6758   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6759                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6760                "       : cccccccccccccc ? 3333333333333333\n"
6761                "                        : 4444444444444444;",
6762                Style);
6763   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
6764                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6765                "                        : 3333333333333333;",
6766                Style);
6767   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6768                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6769                "                        : (aaa ? bbb : ccc);",
6770                Style);
6771   verifyFormat(
6772       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6773       "                                             : cccccccccccccccccc)\n"
6774       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6775       "                        : 3333333333333333;",
6776       Style);
6777   verifyFormat(
6778       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6779       "                                             : cccccccccccccccccc)\n"
6780       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6781       "                        : 3333333333333333;",
6782       Style);
6783   verifyFormat(
6784       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6785       "                                             : dddddddddddddddddd)\n"
6786       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6787       "                        : 3333333333333333;",
6788       Style);
6789   verifyFormat(
6790       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6791       "                                             : dddddddddddddddddd)\n"
6792       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6793       "                        : 3333333333333333;",
6794       Style);
6795   verifyFormat(
6796       "return aaaaaaaaa        ? 1111111111111111\n"
6797       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6798       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6799       "                                             : dddddddddddddddddd)\n",
6800       Style);
6801   verifyFormat(
6802       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6803       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6804       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6805       "                                             : cccccccccccccccccc);",
6806       Style);
6807   verifyFormat(
6808       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6809       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6810       "                                             : eeeeeeeeeeeeeeeeee)\n"
6811       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6812       "                        : 3333333333333333;",
6813       Style);
6814   verifyFormat(
6815       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6816       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6817       "                                             : eeeeeeeeeeeeeeeeee)\n"
6818       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6819       "                        : 3333333333333333;",
6820       Style);
6821   verifyFormat(
6822       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6823       "                           : cccccccccccc    ? dddddddddddddddddd\n"
6824       "                                             : eeeeeeeeeeeeeeeeee)\n"
6825       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6826       "                        : 3333333333333333;",
6827       Style);
6828   verifyFormat(
6829       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6830       "                                             : cccccccccccccccccc\n"
6831       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6832       "                        : 3333333333333333;",
6833       Style);
6834   verifyFormat(
6835       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6836       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
6837       "                                             : eeeeeeeeeeeeeeeeee\n"
6838       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6839       "                        : 3333333333333333;",
6840       Style);
6841   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
6842                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
6843                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
6844                "                                   : eeeeeeeeeeeeeeeeee)\n"
6845                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
6846                "                             : 3333333333333333;",
6847                Style);
6848   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
6849                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6850                "             : cccccccccccccccc ? dddddddddddddddddd\n"
6851                "                                : eeeeeeeeeeeeeeeeee\n"
6852                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
6853                "                                 : 3333333333333333;",
6854                Style);
6855 
6856   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6857   Style.BreakBeforeTernaryOperators = false;
6858   // FIXME: Aligning the question marks is weird given DontAlign.
6859   // Consider disabling this alignment in this case. Also check whether this
6860   // will render the adjustment from https://reviews.llvm.org/D82199
6861   // unnecessary.
6862   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
6863                "    bbbb                ? cccccccccccccccccc :\n"
6864                "                          ddddd;\n",
6865                Style);
6866 
6867   EXPECT_EQ(
6868       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
6869       "    /*\n"
6870       "     */\n"
6871       "    function() {\n"
6872       "      try {\n"
6873       "        return JJJJJJJJJJJJJJ(\n"
6874       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
6875       "      }\n"
6876       "    } :\n"
6877       "    function() {};",
6878       format(
6879           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
6880           "     /*\n"
6881           "      */\n"
6882           "     function() {\n"
6883           "      try {\n"
6884           "        return JJJJJJJJJJJJJJ(\n"
6885           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
6886           "      }\n"
6887           "    } :\n"
6888           "    function() {};",
6889           getGoogleStyle(FormatStyle::LK_JavaScript)));
6890 }
6891 
6892 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
6893   FormatStyle Style = getLLVMStyle();
6894   Style.BreakBeforeTernaryOperators = false;
6895   Style.ColumnLimit = 70;
6896   verifyFormat(
6897       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6898       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6899       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6900       Style);
6901   verifyFormat(
6902       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
6903       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6904       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6905       Style);
6906   verifyFormat(
6907       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6908       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6909       Style);
6910   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
6911                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6912                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6913                Style);
6914   verifyFormat(
6915       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
6916       "                                                      aaaaaaaaaaaaa);",
6917       Style);
6918   verifyFormat(
6919       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6920       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6921       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6922       "                   aaaaaaaaaaaaa);",
6923       Style);
6924   verifyFormat(
6925       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6926       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6927       "                   aaaaaaaaaaaaa);",
6928       Style);
6929   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6930                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6931                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6932                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6933                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6934                Style);
6935   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6936                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6937                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6938                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6939                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6940                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6941                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6942                Style);
6943   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6944                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
6945                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6946                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6947                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6948                Style);
6949   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6950                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6951                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6952                Style);
6953   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6954                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6955                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6956                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6957                Style);
6958   verifyFormat(
6959       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6960       "    aaaaaaaaaaaaaaa :\n"
6961       "    aaaaaaaaaaaaaaa;",
6962       Style);
6963   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6964                "          aaaaaaaaa ?\n"
6965                "      b :\n"
6966                "      c);",
6967                Style);
6968   verifyFormat("unsigned Indent =\n"
6969                "    format(TheLine.First,\n"
6970                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
6971                "               IndentForLevel[TheLine.Level] :\n"
6972                "               TheLine * 2,\n"
6973                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
6974                Style);
6975   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6976                "                  aaaaaaaaaaaaaaa :\n"
6977                "                  bbbbbbbbbbbbbbb ? //\n"
6978                "                      ccccccccccccccc :\n"
6979                "                      ddddddddddddddd;",
6980                Style);
6981   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6982                "                  aaaaaaaaaaaaaaa :\n"
6983                "                  (bbbbbbbbbbbbbbb ? //\n"
6984                "                       ccccccccccccccc :\n"
6985                "                       ddddddddddddddd);",
6986                Style);
6987   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6988                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
6989                "            ccccccccccccccccccccccccccc;",
6990                Style);
6991   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6992                "           aaaaa :\n"
6993                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
6994                Style);
6995 
6996   // Chained conditionals
6997   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6998                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6999                "                          3333333333333333;",
7000                Style);
7001   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7002                "       bbbbbbbbbb       ? 2222222222222222 :\n"
7003                "                          3333333333333333;",
7004                Style);
7005   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
7006                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7007                "                          3333333333333333;",
7008                Style);
7009   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7010                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
7011                "                          333333;",
7012                Style);
7013   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7014                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7015                "       cccccccccccccccc ? 3333333333333333 :\n"
7016                "                          4444444444444444;",
7017                Style);
7018   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
7019                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7020                "                          3333333333333333;",
7021                Style);
7022   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7023                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7024                "                          (aaa ? bbb : ccc);",
7025                Style);
7026   verifyFormat(
7027       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7028       "                                               cccccccccccccccccc) :\n"
7029       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7030       "                          3333333333333333;",
7031       Style);
7032   verifyFormat(
7033       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7034       "                                               cccccccccccccccccc) :\n"
7035       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7036       "                          3333333333333333;",
7037       Style);
7038   verifyFormat(
7039       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7040       "                                               dddddddddddddddddd) :\n"
7041       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7042       "                          3333333333333333;",
7043       Style);
7044   verifyFormat(
7045       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7046       "                                               dddddddddddddddddd) :\n"
7047       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7048       "                          3333333333333333;",
7049       Style);
7050   verifyFormat(
7051       "return aaaaaaaaa        ? 1111111111111111 :\n"
7052       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7053       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7054       "                                               dddddddddddddddddd)\n",
7055       Style);
7056   verifyFormat(
7057       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7058       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7059       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7060       "                                               cccccccccccccccccc);",
7061       Style);
7062   verifyFormat(
7063       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7064       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
7065       "                                               eeeeeeeeeeeeeeeeee) :\n"
7066       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7067       "                          3333333333333333;",
7068       Style);
7069   verifyFormat(
7070       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7071       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
7072       "                                               eeeeeeeeeeeeeeeeee) :\n"
7073       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7074       "                          3333333333333333;",
7075       Style);
7076   verifyFormat(
7077       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
7078       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
7079       "                                               eeeeeeeeeeeeeeeeee) :\n"
7080       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7081       "                          3333333333333333;",
7082       Style);
7083   verifyFormat(
7084       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7085       "                                               cccccccccccccccccc :\n"
7086       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7087       "                          3333333333333333;",
7088       Style);
7089   verifyFormat(
7090       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7091       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
7092       "                                               eeeeeeeeeeeeeeeeee :\n"
7093       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7094       "                          3333333333333333;",
7095       Style);
7096   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
7097                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7098                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
7099                "                                 eeeeeeeeeeeeeeeeee) :\n"
7100                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7101                "                               3333333333333333;",
7102                Style);
7103   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
7104                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7105                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
7106                "                                  eeeeeeeeeeeeeeeeee :\n"
7107                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7108                "                               3333333333333333;",
7109                Style);
7110 }
7111 
7112 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
7113   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
7114                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
7115   verifyFormat("bool a = true, b = false;");
7116 
7117   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7118                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
7119                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
7120                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
7121   verifyFormat(
7122       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
7123       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
7124       "     d = e && f;");
7125   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
7126                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
7127   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
7128                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
7129   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
7130                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
7131 
7132   FormatStyle Style = getGoogleStyle();
7133   Style.PointerAlignment = FormatStyle::PAS_Left;
7134   Style.DerivePointerAlignment = false;
7135   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7136                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
7137                "    *b = bbbbbbbbbbbbbbbbbbb;",
7138                Style);
7139   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
7140                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
7141                Style);
7142   verifyFormat("vector<int*> a, b;", Style);
7143   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
7144 }
7145 
7146 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
7147   verifyFormat("arr[foo ? bar : baz];");
7148   verifyFormat("f()[foo ? bar : baz];");
7149   verifyFormat("(a + b)[foo ? bar : baz];");
7150   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
7151 }
7152 
7153 TEST_F(FormatTest, AlignsStringLiterals) {
7154   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
7155                "                                      \"short literal\");");
7156   verifyFormat(
7157       "looooooooooooooooooooooooongFunction(\n"
7158       "    \"short literal\"\n"
7159       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
7160   verifyFormat("someFunction(\"Always break between multi-line\"\n"
7161                "             \" string literals\",\n"
7162                "             and, other, parameters);");
7163   EXPECT_EQ("fun + \"1243\" /* comment */\n"
7164             "      \"5678\";",
7165             format("fun + \"1243\" /* comment */\n"
7166                    "    \"5678\";",
7167                    getLLVMStyleWithColumns(28)));
7168   EXPECT_EQ(
7169       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
7170       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
7171       "         \"aaaaaaaaaaaaaaaa\";",
7172       format("aaaaaa ="
7173              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
7174              "aaaaaaaaaaaaaaaaaaaaa\" "
7175              "\"aaaaaaaaaaaaaaaa\";"));
7176   verifyFormat("a = a + \"a\"\n"
7177                "        \"a\"\n"
7178                "        \"a\";");
7179   verifyFormat("f(\"a\", \"b\"\n"
7180                "       \"c\");");
7181 
7182   verifyFormat(
7183       "#define LL_FORMAT \"ll\"\n"
7184       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
7185       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
7186 
7187   verifyFormat("#define A(X)          \\\n"
7188                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
7189                "  \"ccccc\"",
7190                getLLVMStyleWithColumns(23));
7191   verifyFormat("#define A \"def\"\n"
7192                "f(\"abc\" A \"ghi\"\n"
7193                "  \"jkl\");");
7194 
7195   verifyFormat("f(L\"a\"\n"
7196                "  L\"b\");");
7197   verifyFormat("#define A(X)            \\\n"
7198                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
7199                "  L\"ccccc\"",
7200                getLLVMStyleWithColumns(25));
7201 
7202   verifyFormat("f(@\"a\"\n"
7203                "  @\"b\");");
7204   verifyFormat("NSString s = @\"a\"\n"
7205                "             @\"b\"\n"
7206                "             @\"c\";");
7207   verifyFormat("NSString s = @\"a\"\n"
7208                "              \"b\"\n"
7209                "              \"c\";");
7210 }
7211 
7212 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
7213   FormatStyle Style = getLLVMStyle();
7214   // No declarations or definitions should be moved to own line.
7215   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
7216   verifyFormat("class A {\n"
7217                "  int f() { return 1; }\n"
7218                "  int g();\n"
7219                "};\n"
7220                "int f() { return 1; }\n"
7221                "int g();\n",
7222                Style);
7223 
7224   // All declarations and definitions should have the return type moved to its
7225   // own line.
7226   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
7227   Style.TypenameMacros = {"LIST"};
7228   verifyFormat("SomeType\n"
7229                "funcdecl(LIST(uint64_t));",
7230                Style);
7231   verifyFormat("class E {\n"
7232                "  int\n"
7233                "  f() {\n"
7234                "    return 1;\n"
7235                "  }\n"
7236                "  int\n"
7237                "  g();\n"
7238                "};\n"
7239                "int\n"
7240                "f() {\n"
7241                "  return 1;\n"
7242                "}\n"
7243                "int\n"
7244                "g();\n",
7245                Style);
7246 
7247   // Top-level definitions, and no kinds of declarations should have the
7248   // return type moved to its own line.
7249   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
7250   verifyFormat("class B {\n"
7251                "  int f() { return 1; }\n"
7252                "  int g();\n"
7253                "};\n"
7254                "int\n"
7255                "f() {\n"
7256                "  return 1;\n"
7257                "}\n"
7258                "int g();\n",
7259                Style);
7260 
7261   // Top-level definitions and declarations should have the return type moved
7262   // to its own line.
7263   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
7264   verifyFormat("class C {\n"
7265                "  int f() { return 1; }\n"
7266                "  int g();\n"
7267                "};\n"
7268                "int\n"
7269                "f() {\n"
7270                "  return 1;\n"
7271                "}\n"
7272                "int\n"
7273                "g();\n",
7274                Style);
7275 
7276   // All definitions should have the return type moved to its own line, but no
7277   // kinds of declarations.
7278   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
7279   verifyFormat("class D {\n"
7280                "  int\n"
7281                "  f() {\n"
7282                "    return 1;\n"
7283                "  }\n"
7284                "  int g();\n"
7285                "};\n"
7286                "int\n"
7287                "f() {\n"
7288                "  return 1;\n"
7289                "}\n"
7290                "int g();\n",
7291                Style);
7292   verifyFormat("const char *\n"
7293                "f(void) {\n" // Break here.
7294                "  return \"\";\n"
7295                "}\n"
7296                "const char *bar(void);\n", // No break here.
7297                Style);
7298   verifyFormat("template <class T>\n"
7299                "T *\n"
7300                "f(T &c) {\n" // Break here.
7301                "  return NULL;\n"
7302                "}\n"
7303                "template <class T> T *f(T &c);\n", // No break here.
7304                Style);
7305   verifyFormat("class C {\n"
7306                "  int\n"
7307                "  operator+() {\n"
7308                "    return 1;\n"
7309                "  }\n"
7310                "  int\n"
7311                "  operator()() {\n"
7312                "    return 1;\n"
7313                "  }\n"
7314                "};\n",
7315                Style);
7316   verifyFormat("void\n"
7317                "A::operator()() {}\n"
7318                "void\n"
7319                "A::operator>>() {}\n"
7320                "void\n"
7321                "A::operator+() {}\n"
7322                "void\n"
7323                "A::operator*() {}\n"
7324                "void\n"
7325                "A::operator->() {}\n"
7326                "void\n"
7327                "A::operator void *() {}\n"
7328                "void\n"
7329                "A::operator void &() {}\n"
7330                "void\n"
7331                "A::operator void &&() {}\n"
7332                "void\n"
7333                "A::operator char *() {}\n"
7334                "void\n"
7335                "A::operator[]() {}\n"
7336                "void\n"
7337                "A::operator!() {}\n"
7338                "void\n"
7339                "A::operator**() {}\n"
7340                "void\n"
7341                "A::operator<Foo> *() {}\n"
7342                "void\n"
7343                "A::operator<Foo> **() {}\n"
7344                "void\n"
7345                "A::operator<Foo> &() {}\n"
7346                "void\n"
7347                "A::operator void **() {}\n",
7348                Style);
7349   verifyFormat("constexpr auto\n"
7350                "operator()() const -> reference {}\n"
7351                "constexpr auto\n"
7352                "operator>>() const -> reference {}\n"
7353                "constexpr auto\n"
7354                "operator+() const -> reference {}\n"
7355                "constexpr auto\n"
7356                "operator*() const -> reference {}\n"
7357                "constexpr auto\n"
7358                "operator->() const -> reference {}\n"
7359                "constexpr auto\n"
7360                "operator++() const -> reference {}\n"
7361                "constexpr auto\n"
7362                "operator void *() const -> reference {}\n"
7363                "constexpr auto\n"
7364                "operator void **() const -> reference {}\n"
7365                "constexpr auto\n"
7366                "operator void *() const -> reference {}\n"
7367                "constexpr auto\n"
7368                "operator void &() const -> reference {}\n"
7369                "constexpr auto\n"
7370                "operator void &&() const -> reference {}\n"
7371                "constexpr auto\n"
7372                "operator char *() const -> reference {}\n"
7373                "constexpr auto\n"
7374                "operator!() const -> reference {}\n"
7375                "constexpr auto\n"
7376                "operator[]() const -> reference {}\n",
7377                Style);
7378   verifyFormat("void *operator new(std::size_t s);", // No break here.
7379                Style);
7380   verifyFormat("void *\n"
7381                "operator new(std::size_t s) {}",
7382                Style);
7383   verifyFormat("void *\n"
7384                "operator delete[](void *ptr) {}",
7385                Style);
7386   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
7387   verifyFormat("const char *\n"
7388                "f(void)\n" // Break here.
7389                "{\n"
7390                "  return \"\";\n"
7391                "}\n"
7392                "const char *bar(void);\n", // No break here.
7393                Style);
7394   verifyFormat("template <class T>\n"
7395                "T *\n"     // Problem here: no line break
7396                "f(T &c)\n" // Break here.
7397                "{\n"
7398                "  return NULL;\n"
7399                "}\n"
7400                "template <class T> T *f(T &c);\n", // No break here.
7401                Style);
7402   verifyFormat("int\n"
7403                "foo(A<bool> a)\n"
7404                "{\n"
7405                "  return a;\n"
7406                "}\n",
7407                Style);
7408   verifyFormat("int\n"
7409                "foo(A<8> a)\n"
7410                "{\n"
7411                "  return a;\n"
7412                "}\n",
7413                Style);
7414   verifyFormat("int\n"
7415                "foo(A<B<bool>, 8> a)\n"
7416                "{\n"
7417                "  return a;\n"
7418                "}\n",
7419                Style);
7420   verifyFormat("int\n"
7421                "foo(A<B<8>, bool> a)\n"
7422                "{\n"
7423                "  return a;\n"
7424                "}\n",
7425                Style);
7426   verifyFormat("int\n"
7427                "foo(A<B<bool>, bool> a)\n"
7428                "{\n"
7429                "  return a;\n"
7430                "}\n",
7431                Style);
7432   verifyFormat("int\n"
7433                "foo(A<B<8>, 8> a)\n"
7434                "{\n"
7435                "  return a;\n"
7436                "}\n",
7437                Style);
7438 
7439   Style = getGNUStyle();
7440 
7441   // Test for comments at the end of function declarations.
7442   verifyFormat("void\n"
7443                "foo (int a, /*abc*/ int b) // def\n"
7444                "{\n"
7445                "}\n",
7446                Style);
7447 
7448   verifyFormat("void\n"
7449                "foo (int a, /* abc */ int b) /* def */\n"
7450                "{\n"
7451                "}\n",
7452                Style);
7453 
7454   // Definitions that should not break after return type
7455   verifyFormat("void foo (int a, int b); // def\n", Style);
7456   verifyFormat("void foo (int a, int b); /* def */\n", Style);
7457   verifyFormat("void foo (int a, int b);\n", Style);
7458 }
7459 
7460 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
7461   FormatStyle NoBreak = getLLVMStyle();
7462   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
7463   FormatStyle Break = getLLVMStyle();
7464   Break.AlwaysBreakBeforeMultilineStrings = true;
7465   verifyFormat("aaaa = \"bbbb\"\n"
7466                "       \"cccc\";",
7467                NoBreak);
7468   verifyFormat("aaaa =\n"
7469                "    \"bbbb\"\n"
7470                "    \"cccc\";",
7471                Break);
7472   verifyFormat("aaaa(\"bbbb\"\n"
7473                "     \"cccc\");",
7474                NoBreak);
7475   verifyFormat("aaaa(\n"
7476                "    \"bbbb\"\n"
7477                "    \"cccc\");",
7478                Break);
7479   verifyFormat("aaaa(qqq, \"bbbb\"\n"
7480                "          \"cccc\");",
7481                NoBreak);
7482   verifyFormat("aaaa(qqq,\n"
7483                "     \"bbbb\"\n"
7484                "     \"cccc\");",
7485                Break);
7486   verifyFormat("aaaa(qqq,\n"
7487                "     L\"bbbb\"\n"
7488                "     L\"cccc\");",
7489                Break);
7490   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
7491                "                      \"bbbb\"));",
7492                Break);
7493   verifyFormat("string s = someFunction(\n"
7494                "    \"abc\"\n"
7495                "    \"abc\");",
7496                Break);
7497 
7498   // As we break before unary operators, breaking right after them is bad.
7499   verifyFormat("string foo = abc ? \"x\"\n"
7500                "                   \"blah blah blah blah blah blah\"\n"
7501                "                 : \"y\";",
7502                Break);
7503 
7504   // Don't break if there is no column gain.
7505   verifyFormat("f(\"aaaa\"\n"
7506                "  \"bbbb\");",
7507                Break);
7508 
7509   // Treat literals with escaped newlines like multi-line string literals.
7510   EXPECT_EQ("x = \"a\\\n"
7511             "b\\\n"
7512             "c\";",
7513             format("x = \"a\\\n"
7514                    "b\\\n"
7515                    "c\";",
7516                    NoBreak));
7517   EXPECT_EQ("xxxx =\n"
7518             "    \"a\\\n"
7519             "b\\\n"
7520             "c\";",
7521             format("xxxx = \"a\\\n"
7522                    "b\\\n"
7523                    "c\";",
7524                    Break));
7525 
7526   EXPECT_EQ("NSString *const kString =\n"
7527             "    @\"aaaa\"\n"
7528             "    @\"bbbb\";",
7529             format("NSString *const kString = @\"aaaa\"\n"
7530                    "@\"bbbb\";",
7531                    Break));
7532 
7533   Break.ColumnLimit = 0;
7534   verifyFormat("const char *hello = \"hello llvm\";", Break);
7535 }
7536 
7537 TEST_F(FormatTest, AlignsPipes) {
7538   verifyFormat(
7539       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7540       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7541       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7542   verifyFormat(
7543       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
7544       "                     << aaaaaaaaaaaaaaaaaaaa;");
7545   verifyFormat(
7546       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7547       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7548   verifyFormat(
7549       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7550       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7551   verifyFormat(
7552       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
7553       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
7554       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
7555   verifyFormat(
7556       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7557       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7558       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7559   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7560                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7561                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7562                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7563   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
7564                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
7565   verifyFormat(
7566       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7567       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7568   verifyFormat(
7569       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
7570       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
7571 
7572   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
7573                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
7574   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7575                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7576                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
7577                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
7578   verifyFormat("LOG_IF(aaa == //\n"
7579                "       bbb)\n"
7580                "    << a << b;");
7581 
7582   // But sometimes, breaking before the first "<<" is desirable.
7583   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7584                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
7585   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
7586                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7587                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7588   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
7589                "    << BEF << IsTemplate << Description << E->getType();");
7590   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7591                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7592                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7593   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7594                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7595                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7596                "    << aaa;");
7597 
7598   verifyFormat(
7599       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7600       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7601 
7602   // Incomplete string literal.
7603   EXPECT_EQ("llvm::errs() << \"\n"
7604             "             << a;",
7605             format("llvm::errs() << \"\n<<a;"));
7606 
7607   verifyFormat("void f() {\n"
7608                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
7609                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
7610                "}");
7611 
7612   // Handle 'endl'.
7613   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
7614                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7615   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7616 
7617   // Handle '\n'.
7618   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
7619                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7620   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
7621                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
7622   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
7623                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
7624   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7625 }
7626 
7627 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
7628   verifyFormat("return out << \"somepacket = {\\n\"\n"
7629                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
7630                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
7631                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
7632                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
7633                "           << \"}\";");
7634 
7635   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7636                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7637                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
7638   verifyFormat(
7639       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
7640       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
7641       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
7642       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
7643       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
7644   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
7645                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7646   verifyFormat(
7647       "void f() {\n"
7648       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
7649       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7650       "}");
7651 
7652   // Breaking before the first "<<" is generally not desirable.
7653   verifyFormat(
7654       "llvm::errs()\n"
7655       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7656       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7657       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7658       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7659       getLLVMStyleWithColumns(70));
7660   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7661                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7662                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7663                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7664                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7665                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7666                getLLVMStyleWithColumns(70));
7667 
7668   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7669                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7670                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
7671   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7672                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7673                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
7674   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
7675                "           (aaaa + aaaa);",
7676                getLLVMStyleWithColumns(40));
7677   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
7678                "                  (aaaaaaa + aaaaa));",
7679                getLLVMStyleWithColumns(40));
7680   verifyFormat(
7681       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
7682       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
7683       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
7684 }
7685 
7686 TEST_F(FormatTest, UnderstandsEquals) {
7687   verifyFormat(
7688       "aaaaaaaaaaaaaaaaa =\n"
7689       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7690   verifyFormat(
7691       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7692       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7693   verifyFormat(
7694       "if (a) {\n"
7695       "  f();\n"
7696       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7697       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
7698       "}");
7699 
7700   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7701                "        100000000 + 10000000) {\n}");
7702 }
7703 
7704 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
7705   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7706                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
7707 
7708   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7709                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
7710 
7711   verifyFormat(
7712       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
7713       "                                                          Parameter2);");
7714 
7715   verifyFormat(
7716       "ShortObject->shortFunction(\n"
7717       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
7718       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
7719 
7720   verifyFormat("loooooooooooooongFunction(\n"
7721                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
7722 
7723   verifyFormat(
7724       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
7725       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
7726 
7727   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7728                "    .WillRepeatedly(Return(SomeValue));");
7729   verifyFormat("void f() {\n"
7730                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7731                "      .Times(2)\n"
7732                "      .WillRepeatedly(Return(SomeValue));\n"
7733                "}");
7734   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
7735                "    ccccccccccccccccccccccc);");
7736   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7737                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7738                "          .aaaaa(aaaaa),\n"
7739                "      aaaaaaaaaaaaaaaaaaaaa);");
7740   verifyFormat("void f() {\n"
7741                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7742                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
7743                "}");
7744   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7745                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7746                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7747                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7748                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7749   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7750                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7751                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7752                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
7753                "}");
7754 
7755   // Here, it is not necessary to wrap at "." or "->".
7756   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
7757                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7758   verifyFormat(
7759       "aaaaaaaaaaa->aaaaaaaaa(\n"
7760       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7761       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
7762 
7763   verifyFormat(
7764       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7765       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
7766   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
7767                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
7768   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
7769                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
7770 
7771   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7772                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7773                "    .a();");
7774 
7775   FormatStyle NoBinPacking = getLLVMStyle();
7776   NoBinPacking.BinPackParameters = false;
7777   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7778                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7779                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
7780                "                         aaaaaaaaaaaaaaaaaaa,\n"
7781                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7782                NoBinPacking);
7783 
7784   // If there is a subsequent call, change to hanging indentation.
7785   verifyFormat(
7786       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7787       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
7788       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7789   verifyFormat(
7790       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7791       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
7792   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7793                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7794                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7795   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7796                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7797                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
7798 }
7799 
7800 TEST_F(FormatTest, WrapsTemplateDeclarations) {
7801   verifyFormat("template <typename T>\n"
7802                "virtual void loooooooooooongFunction(int Param1, int Param2);");
7803   verifyFormat("template <typename T>\n"
7804                "// T should be one of {A, B}.\n"
7805                "virtual void loooooooooooongFunction(int Param1, int Param2);");
7806   verifyFormat(
7807       "template <typename T>\n"
7808       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
7809   verifyFormat("template <typename T>\n"
7810                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
7811                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
7812   verifyFormat(
7813       "template <typename T>\n"
7814       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
7815       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
7816   verifyFormat(
7817       "template <typename T>\n"
7818       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
7819       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
7820       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7821   verifyFormat("template <typename T>\n"
7822                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7823                "    int aaaaaaaaaaaaaaaaaaaaaa);");
7824   verifyFormat(
7825       "template <typename T1, typename T2 = char, typename T3 = char,\n"
7826       "          typename T4 = char>\n"
7827       "void f();");
7828   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
7829                "          template <typename> class cccccccccccccccccccccc,\n"
7830                "          typename ddddddddddddd>\n"
7831                "class C {};");
7832   verifyFormat(
7833       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
7834       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7835 
7836   verifyFormat("void f() {\n"
7837                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
7838                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
7839                "}");
7840 
7841   verifyFormat("template <typename T> class C {};");
7842   verifyFormat("template <typename T> void f();");
7843   verifyFormat("template <typename T> void f() {}");
7844   verifyFormat(
7845       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7846       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7847       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
7848       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7849       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7850       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
7851       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
7852       getLLVMStyleWithColumns(72));
7853   EXPECT_EQ("static_cast<A< //\n"
7854             "    B> *>(\n"
7855             "\n"
7856             ");",
7857             format("static_cast<A<//\n"
7858                    "    B>*>(\n"
7859                    "\n"
7860                    "    );"));
7861   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7862                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
7863 
7864   FormatStyle AlwaysBreak = getLLVMStyle();
7865   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7866   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
7867   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
7868   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
7869   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7870                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7871                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
7872   verifyFormat("template <template <typename> class Fooooooo,\n"
7873                "          template <typename> class Baaaaaaar>\n"
7874                "struct C {};",
7875                AlwaysBreak);
7876   verifyFormat("template <typename T> // T can be A, B or C.\n"
7877                "struct C {};",
7878                AlwaysBreak);
7879   verifyFormat("template <enum E> class A {\n"
7880                "public:\n"
7881                "  E *f();\n"
7882                "};");
7883 
7884   FormatStyle NeverBreak = getLLVMStyle();
7885   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
7886   verifyFormat("template <typename T> class C {};", NeverBreak);
7887   verifyFormat("template <typename T> void f();", NeverBreak);
7888   verifyFormat("template <typename T> void f() {}", NeverBreak);
7889   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7890                "bbbbbbbbbbbbbbbbbbbb) {}",
7891                NeverBreak);
7892   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7893                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7894                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
7895                NeverBreak);
7896   verifyFormat("template <template <typename> class Fooooooo,\n"
7897                "          template <typename> class Baaaaaaar>\n"
7898                "struct C {};",
7899                NeverBreak);
7900   verifyFormat("template <typename T> // T can be A, B or C.\n"
7901                "struct C {};",
7902                NeverBreak);
7903   verifyFormat("template <enum E> class A {\n"
7904                "public:\n"
7905                "  E *f();\n"
7906                "};",
7907                NeverBreak);
7908   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
7909   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7910                "bbbbbbbbbbbbbbbbbbbb) {}",
7911                NeverBreak);
7912 }
7913 
7914 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
7915   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
7916   Style.ColumnLimit = 60;
7917   EXPECT_EQ("// Baseline - no comments.\n"
7918             "template <\n"
7919             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7920             "void f() {}",
7921             format("// Baseline - no comments.\n"
7922                    "template <\n"
7923                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7924                    "void f() {}",
7925                    Style));
7926 
7927   EXPECT_EQ("template <\n"
7928             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
7929             "void f() {}",
7930             format("template <\n"
7931                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7932                    "void f() {}",
7933                    Style));
7934 
7935   EXPECT_EQ(
7936       "template <\n"
7937       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
7938       "void f() {}",
7939       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
7940              "void f() {}",
7941              Style));
7942 
7943   EXPECT_EQ(
7944       "template <\n"
7945       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
7946       "                                               // multiline\n"
7947       "void f() {}",
7948       format("template <\n"
7949              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7950              "                                              // multiline\n"
7951              "void f() {}",
7952              Style));
7953 
7954   EXPECT_EQ(
7955       "template <typename aaaaaaaaaa<\n"
7956       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
7957       "void f() {}",
7958       format(
7959           "template <\n"
7960           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
7961           "void f() {}",
7962           Style));
7963 }
7964 
7965 TEST_F(FormatTest, WrapsTemplateParameters) {
7966   FormatStyle Style = getLLVMStyle();
7967   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7968   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7969   verifyFormat(
7970       "template <typename... a> struct q {};\n"
7971       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7972       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7973       "    y;",
7974       Style);
7975   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7976   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7977   verifyFormat(
7978       "template <typename... a> struct r {};\n"
7979       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7980       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7981       "    y;",
7982       Style);
7983   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7984   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7985   verifyFormat("template <typename... a> struct s {};\n"
7986                "extern s<\n"
7987                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7988                "aaaaaaaaaaaaaaaaaaaaaa,\n"
7989                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7990                "aaaaaaaaaaaaaaaaaaaaaa>\n"
7991                "    y;",
7992                Style);
7993   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7994   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7995   verifyFormat("template <typename... a> struct t {};\n"
7996                "extern t<\n"
7997                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7998                "aaaaaaaaaaaaaaaaaaaaaa,\n"
7999                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8000                "aaaaaaaaaaaaaaaaaaaaaa>\n"
8001                "    y;",
8002                Style);
8003 }
8004 
8005 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
8006   verifyFormat(
8007       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8008       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8009   verifyFormat(
8010       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8011       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8012       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
8013 
8014   // FIXME: Should we have the extra indent after the second break?
8015   verifyFormat(
8016       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8017       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8018       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8019 
8020   verifyFormat(
8021       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
8022       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
8023 
8024   // Breaking at nested name specifiers is generally not desirable.
8025   verifyFormat(
8026       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8027       "    aaaaaaaaaaaaaaaaaaaaaaa);");
8028 
8029   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
8030                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8031                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8032                "                   aaaaaaaaaaaaaaaaaaaaa);",
8033                getLLVMStyleWithColumns(74));
8034 
8035   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8036                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8037                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8038 }
8039 
8040 TEST_F(FormatTest, UnderstandsTemplateParameters) {
8041   verifyFormat("A<int> a;");
8042   verifyFormat("A<A<A<int>>> a;");
8043   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
8044   verifyFormat("bool x = a < 1 || 2 > a;");
8045   verifyFormat("bool x = 5 < f<int>();");
8046   verifyFormat("bool x = f<int>() > 5;");
8047   verifyFormat("bool x = 5 < a<int>::x;");
8048   verifyFormat("bool x = a < 4 ? a > 2 : false;");
8049   verifyFormat("bool x = f() ? a < 2 : a > 2;");
8050 
8051   verifyGoogleFormat("A<A<int>> a;");
8052   verifyGoogleFormat("A<A<A<int>>> a;");
8053   verifyGoogleFormat("A<A<A<A<int>>>> a;");
8054   verifyGoogleFormat("A<A<int> > a;");
8055   verifyGoogleFormat("A<A<A<int> > > a;");
8056   verifyGoogleFormat("A<A<A<A<int> > > > a;");
8057   verifyGoogleFormat("A<::A<int>> a;");
8058   verifyGoogleFormat("A<::A> a;");
8059   verifyGoogleFormat("A< ::A> a;");
8060   verifyGoogleFormat("A< ::A<int> > a;");
8061   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
8062   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
8063   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
8064   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
8065   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
8066             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
8067 
8068   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
8069 
8070   // template closer followed by a token that starts with > or =
8071   verifyFormat("bool b = a<1> > 1;");
8072   verifyFormat("bool b = a<1> >= 1;");
8073   verifyFormat("int i = a<1> >> 1;");
8074   FormatStyle Style = getLLVMStyle();
8075   Style.SpaceBeforeAssignmentOperators = false;
8076   verifyFormat("bool b= a<1> == 1;", Style);
8077   verifyFormat("a<int> = 1;", Style);
8078   verifyFormat("a<int> >>= 1;", Style);
8079 
8080   verifyFormat("test < a | b >> c;");
8081   verifyFormat("test<test<a | b>> c;");
8082   verifyFormat("test >> a >> b;");
8083   verifyFormat("test << a >> b;");
8084 
8085   verifyFormat("f<int>();");
8086   verifyFormat("template <typename T> void f() {}");
8087   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
8088   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
8089                "sizeof(char)>::type>;");
8090   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
8091   verifyFormat("f(a.operator()<A>());");
8092   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8093                "      .template operator()<A>());",
8094                getLLVMStyleWithColumns(35));
8095 
8096   // Not template parameters.
8097   verifyFormat("return a < b && c > d;");
8098   verifyFormat("void f() {\n"
8099                "  while (a < b && c > d) {\n"
8100                "  }\n"
8101                "}");
8102   verifyFormat("template <typename... Types>\n"
8103                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
8104 
8105   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8106                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
8107                getLLVMStyleWithColumns(60));
8108   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
8109   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
8110   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
8111   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
8112 }
8113 
8114 TEST_F(FormatTest, UnderstandsShiftOperators) {
8115   verifyFormat("if (i < x >> 1)");
8116   verifyFormat("while (i < x >> 1)");
8117   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
8118   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
8119   verifyFormat(
8120       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
8121   verifyFormat("Foo.call<Bar<Function>>()");
8122   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
8123   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
8124                "++i, v = v >> 1)");
8125   verifyFormat("if (w<u<v<x>>, 1>::t)");
8126 }
8127 
8128 TEST_F(FormatTest, BitshiftOperatorWidth) {
8129   EXPECT_EQ("int a = 1 << 2; /* foo\n"
8130             "                   bar */",
8131             format("int    a=1<<2;  /* foo\n"
8132                    "                   bar */"));
8133 
8134   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
8135             "                     bar */",
8136             format("int  b  =256>>1 ;  /* foo\n"
8137                    "                      bar */"));
8138 }
8139 
8140 TEST_F(FormatTest, UnderstandsBinaryOperators) {
8141   verifyFormat("COMPARE(a, ==, b);");
8142   verifyFormat("auto s = sizeof...(Ts) - 1;");
8143 }
8144 
8145 TEST_F(FormatTest, UnderstandsPointersToMembers) {
8146   verifyFormat("int A::*x;");
8147   verifyFormat("int (S::*func)(void *);");
8148   verifyFormat("void f() { int (S::*func)(void *); }");
8149   verifyFormat("typedef bool *(Class::*Member)() const;");
8150   verifyFormat("void f() {\n"
8151                "  (a->*f)();\n"
8152                "  a->*x;\n"
8153                "  (a.*f)();\n"
8154                "  ((*a).*f)();\n"
8155                "  a.*x;\n"
8156                "}");
8157   verifyFormat("void f() {\n"
8158                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
8159                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
8160                "}");
8161   verifyFormat(
8162       "(aaaaaaaaaa->*bbbbbbb)(\n"
8163       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
8164   FormatStyle Style = getLLVMStyle();
8165   Style.PointerAlignment = FormatStyle::PAS_Left;
8166   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
8167 }
8168 
8169 TEST_F(FormatTest, UnderstandsUnaryOperators) {
8170   verifyFormat("int a = -2;");
8171   verifyFormat("f(-1, -2, -3);");
8172   verifyFormat("a[-1] = 5;");
8173   verifyFormat("int a = 5 + -2;");
8174   verifyFormat("if (i == -1) {\n}");
8175   verifyFormat("if (i != -1) {\n}");
8176   verifyFormat("if (i > -1) {\n}");
8177   verifyFormat("if (i < -1) {\n}");
8178   verifyFormat("++(a->f());");
8179   verifyFormat("--(a->f());");
8180   verifyFormat("(a->f())++;");
8181   verifyFormat("a[42]++;");
8182   verifyFormat("if (!(a->f())) {\n}");
8183   verifyFormat("if (!+i) {\n}");
8184   verifyFormat("~&a;");
8185 
8186   verifyFormat("a-- > b;");
8187   verifyFormat("b ? -a : c;");
8188   verifyFormat("n * sizeof char16;");
8189   verifyFormat("n * alignof char16;", getGoogleStyle());
8190   verifyFormat("sizeof(char);");
8191   verifyFormat("alignof(char);", getGoogleStyle());
8192 
8193   verifyFormat("return -1;");
8194   verifyFormat("throw -1;");
8195   verifyFormat("switch (a) {\n"
8196                "case -1:\n"
8197                "  break;\n"
8198                "}");
8199   verifyFormat("#define X -1");
8200   verifyFormat("#define X -kConstant");
8201 
8202   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
8203   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
8204 
8205   verifyFormat("int a = /* confusing comment */ -1;");
8206   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
8207   verifyFormat("int a = i /* confusing comment */++;");
8208 
8209   verifyFormat("co_yield -1;");
8210   verifyFormat("co_return -1;");
8211 
8212   // Check that * is not treated as a binary operator when we set
8213   // PointerAlignment as PAS_Left after a keyword and not a declaration.
8214   FormatStyle PASLeftStyle = getLLVMStyle();
8215   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
8216   verifyFormat("co_return *a;", PASLeftStyle);
8217   verifyFormat("co_await *a;", PASLeftStyle);
8218   verifyFormat("co_yield *a", PASLeftStyle);
8219   verifyFormat("return *a;", PASLeftStyle);
8220 }
8221 
8222 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
8223   verifyFormat("if (!aaaaaaaaaa( // break\n"
8224                "        aaaaa)) {\n"
8225                "}");
8226   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
8227                "    aaaaa));");
8228   verifyFormat("*aaa = aaaaaaa( // break\n"
8229                "    bbbbbb);");
8230 }
8231 
8232 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
8233   verifyFormat("bool operator<();");
8234   verifyFormat("bool operator>();");
8235   verifyFormat("bool operator=();");
8236   verifyFormat("bool operator==();");
8237   verifyFormat("bool operator!=();");
8238   verifyFormat("int operator+();");
8239   verifyFormat("int operator++();");
8240   verifyFormat("int operator++(int) volatile noexcept;");
8241   verifyFormat("bool operator,();");
8242   verifyFormat("bool operator();");
8243   verifyFormat("bool operator()();");
8244   verifyFormat("bool operator[]();");
8245   verifyFormat("operator bool();");
8246   verifyFormat("operator int();");
8247   verifyFormat("operator void *();");
8248   verifyFormat("operator SomeType<int>();");
8249   verifyFormat("operator SomeType<int, int>();");
8250   verifyFormat("operator SomeType<SomeType<int>>();");
8251   verifyFormat("void *operator new(std::size_t size);");
8252   verifyFormat("void *operator new[](std::size_t size);");
8253   verifyFormat("void operator delete(void *ptr);");
8254   verifyFormat("void operator delete[](void *ptr);");
8255   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
8256                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
8257   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
8258                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
8259 
8260   verifyFormat(
8261       "ostream &operator<<(ostream &OutputStream,\n"
8262       "                    SomeReallyLongType WithSomeReallyLongValue);");
8263   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
8264                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
8265                "  return left.group < right.group;\n"
8266                "}");
8267   verifyFormat("SomeType &operator=(const SomeType &S);");
8268   verifyFormat("f.template operator()<int>();");
8269 
8270   verifyGoogleFormat("operator void*();");
8271   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
8272   verifyGoogleFormat("operator ::A();");
8273 
8274   verifyFormat("using A::operator+;");
8275   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
8276                "int i;");
8277 }
8278 
8279 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
8280   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
8281   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
8282   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
8283   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
8284   verifyFormat("Deleted &operator=(const Deleted &) &;");
8285   verifyFormat("Deleted &operator=(const Deleted &) &&;");
8286   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
8287   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
8288   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
8289   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
8290   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
8291   verifyFormat("void Fn(T const &) const &;");
8292   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
8293   verifyFormat("template <typename T>\n"
8294                "void F(T) && = delete;",
8295                getGoogleStyle());
8296 
8297   FormatStyle AlignLeft = getLLVMStyle();
8298   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
8299   verifyFormat("void A::b() && {}", AlignLeft);
8300   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
8301   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
8302                AlignLeft);
8303   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
8304   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
8305   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
8306   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
8307   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
8308   verifyFormat("auto Function(T) & -> void;", AlignLeft);
8309   verifyFormat("void Fn(T const&) const&;", AlignLeft);
8310   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
8311 
8312   FormatStyle Spaces = getLLVMStyle();
8313   Spaces.SpacesInCStyleCastParentheses = true;
8314   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
8315   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
8316   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
8317   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
8318 
8319   Spaces.SpacesInCStyleCastParentheses = false;
8320   Spaces.SpacesInParentheses = true;
8321   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
8322   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
8323                Spaces);
8324   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
8325   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
8326 
8327   FormatStyle BreakTemplate = getLLVMStyle();
8328   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
8329 
8330   verifyFormat("struct f {\n"
8331                "  template <class T>\n"
8332                "  int &foo(const std::string &str) &noexcept {}\n"
8333                "};",
8334                BreakTemplate);
8335 
8336   verifyFormat("struct f {\n"
8337                "  template <class T>\n"
8338                "  int &foo(const std::string &str) &&noexcept {}\n"
8339                "};",
8340                BreakTemplate);
8341 
8342   verifyFormat("struct f {\n"
8343                "  template <class T>\n"
8344                "  int &foo(const std::string &str) const &noexcept {}\n"
8345                "};",
8346                BreakTemplate);
8347 
8348   verifyFormat("struct f {\n"
8349                "  template <class T>\n"
8350                "  int &foo(const std::string &str) const &noexcept {}\n"
8351                "};",
8352                BreakTemplate);
8353 
8354   verifyFormat("struct f {\n"
8355                "  template <class T>\n"
8356                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
8357                "};",
8358                BreakTemplate);
8359 
8360   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
8361   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
8362       FormatStyle::BTDS_Yes;
8363   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
8364 
8365   verifyFormat("struct f {\n"
8366                "  template <class T>\n"
8367                "  int& foo(const std::string& str) & noexcept {}\n"
8368                "};",
8369                AlignLeftBreakTemplate);
8370 
8371   verifyFormat("struct f {\n"
8372                "  template <class T>\n"
8373                "  int& foo(const std::string& str) && noexcept {}\n"
8374                "};",
8375                AlignLeftBreakTemplate);
8376 
8377   verifyFormat("struct f {\n"
8378                "  template <class T>\n"
8379                "  int& foo(const std::string& str) const& noexcept {}\n"
8380                "};",
8381                AlignLeftBreakTemplate);
8382 
8383   verifyFormat("struct f {\n"
8384                "  template <class T>\n"
8385                "  int& foo(const std::string& str) const&& noexcept {}\n"
8386                "};",
8387                AlignLeftBreakTemplate);
8388 
8389   verifyFormat("struct f {\n"
8390                "  template <class T>\n"
8391                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
8392                "};",
8393                AlignLeftBreakTemplate);
8394 
8395   // The `&` in `Type&` should not be confused with a trailing `&` of
8396   // DEPRECATED(reason) member function.
8397   verifyFormat("struct f {\n"
8398                "  template <class T>\n"
8399                "  DEPRECATED(reason)\n"
8400                "  Type &foo(arguments) {}\n"
8401                "};",
8402                BreakTemplate);
8403 
8404   verifyFormat("struct f {\n"
8405                "  template <class T>\n"
8406                "  DEPRECATED(reason)\n"
8407                "  Type& foo(arguments) {}\n"
8408                "};",
8409                AlignLeftBreakTemplate);
8410 
8411   verifyFormat("void (*foopt)(int) = &func;");
8412 }
8413 
8414 TEST_F(FormatTest, UnderstandsNewAndDelete) {
8415   verifyFormat("void f() {\n"
8416                "  A *a = new A;\n"
8417                "  A *a = new (placement) A;\n"
8418                "  delete a;\n"
8419                "  delete (A *)a;\n"
8420                "}");
8421   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
8422                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
8423   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8424                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
8425                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
8426   verifyFormat("delete[] h->p;");
8427 }
8428 
8429 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
8430   verifyFormat("int *f(int *a) {}");
8431   verifyFormat("int main(int argc, char **argv) {}");
8432   verifyFormat("Test::Test(int b) : a(b * b) {}");
8433   verifyIndependentOfContext("f(a, *a);");
8434   verifyFormat("void g() { f(*a); }");
8435   verifyIndependentOfContext("int a = b * 10;");
8436   verifyIndependentOfContext("int a = 10 * b;");
8437   verifyIndependentOfContext("int a = b * c;");
8438   verifyIndependentOfContext("int a += b * c;");
8439   verifyIndependentOfContext("int a -= b * c;");
8440   verifyIndependentOfContext("int a *= b * c;");
8441   verifyIndependentOfContext("int a /= b * c;");
8442   verifyIndependentOfContext("int a = *b;");
8443   verifyIndependentOfContext("int a = *b * c;");
8444   verifyIndependentOfContext("int a = b * *c;");
8445   verifyIndependentOfContext("int a = b * (10);");
8446   verifyIndependentOfContext("S << b * (10);");
8447   verifyIndependentOfContext("return 10 * b;");
8448   verifyIndependentOfContext("return *b * *c;");
8449   verifyIndependentOfContext("return a & ~b;");
8450   verifyIndependentOfContext("f(b ? *c : *d);");
8451   verifyIndependentOfContext("int a = b ? *c : *d;");
8452   verifyIndependentOfContext("*b = a;");
8453   verifyIndependentOfContext("a * ~b;");
8454   verifyIndependentOfContext("a * !b;");
8455   verifyIndependentOfContext("a * +b;");
8456   verifyIndependentOfContext("a * -b;");
8457   verifyIndependentOfContext("a * ++b;");
8458   verifyIndependentOfContext("a * --b;");
8459   verifyIndependentOfContext("a[4] * b;");
8460   verifyIndependentOfContext("a[a * a] = 1;");
8461   verifyIndependentOfContext("f() * b;");
8462   verifyIndependentOfContext("a * [self dostuff];");
8463   verifyIndependentOfContext("int x = a * (a + b);");
8464   verifyIndependentOfContext("(a *)(a + b);");
8465   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
8466   verifyIndependentOfContext("int *pa = (int *)&a;");
8467   verifyIndependentOfContext("return sizeof(int **);");
8468   verifyIndependentOfContext("return sizeof(int ******);");
8469   verifyIndependentOfContext("return (int **&)a;");
8470   verifyIndependentOfContext("f((*PointerToArray)[10]);");
8471   verifyFormat("void f(Type (*parameter)[10]) {}");
8472   verifyFormat("void f(Type (&parameter)[10]) {}");
8473   verifyGoogleFormat("return sizeof(int**);");
8474   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
8475   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
8476   verifyFormat("auto a = [](int **&, int ***) {};");
8477   verifyFormat("auto PointerBinding = [](const char *S) {};");
8478   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
8479   verifyFormat("[](const decltype(*a) &value) {}");
8480   verifyFormat("[](const typeof(*a) &value) {}");
8481   verifyFormat("[](const _Atomic(a *) &value) {}");
8482   verifyFormat("[](const __underlying_type(a) &value) {}");
8483   verifyFormat("decltype(a * b) F();");
8484   verifyFormat("typeof(a * b) F();");
8485   verifyFormat("#define MACRO() [](A *a) { return 1; }");
8486   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
8487   verifyIndependentOfContext("typedef void (*f)(int *a);");
8488   verifyIndependentOfContext("int i{a * b};");
8489   verifyIndependentOfContext("aaa && aaa->f();");
8490   verifyIndependentOfContext("int x = ~*p;");
8491   verifyFormat("Constructor() : a(a), area(width * height) {}");
8492   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
8493   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
8494   verifyFormat("void f() { f(a, c * d); }");
8495   verifyFormat("void f() { f(new a(), c * d); }");
8496   verifyFormat("void f(const MyOverride &override);");
8497   verifyFormat("void f(const MyFinal &final);");
8498   verifyIndependentOfContext("bool a = f() && override.f();");
8499   verifyIndependentOfContext("bool a = f() && final.f();");
8500 
8501   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
8502 
8503   verifyIndependentOfContext("A<int *> a;");
8504   verifyIndependentOfContext("A<int **> a;");
8505   verifyIndependentOfContext("A<int *, int *> a;");
8506   verifyIndependentOfContext("A<int *[]> a;");
8507   verifyIndependentOfContext(
8508       "const char *const p = reinterpret_cast<const char *const>(q);");
8509   verifyIndependentOfContext("A<int **, int **> a;");
8510   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
8511   verifyFormat("for (char **a = b; *a; ++a) {\n}");
8512   verifyFormat("for (; a && b;) {\n}");
8513   verifyFormat("bool foo = true && [] { return false; }();");
8514 
8515   verifyFormat(
8516       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8517       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8518 
8519   verifyGoogleFormat("int const* a = &b;");
8520   verifyGoogleFormat("**outparam = 1;");
8521   verifyGoogleFormat("*outparam = a * b;");
8522   verifyGoogleFormat("int main(int argc, char** argv) {}");
8523   verifyGoogleFormat("A<int*> a;");
8524   verifyGoogleFormat("A<int**> a;");
8525   verifyGoogleFormat("A<int*, int*> a;");
8526   verifyGoogleFormat("A<int**, int**> a;");
8527   verifyGoogleFormat("f(b ? *c : *d);");
8528   verifyGoogleFormat("int a = b ? *c : *d;");
8529   verifyGoogleFormat("Type* t = **x;");
8530   verifyGoogleFormat("Type* t = *++*x;");
8531   verifyGoogleFormat("*++*x;");
8532   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
8533   verifyGoogleFormat("Type* t = x++ * y;");
8534   verifyGoogleFormat(
8535       "const char* const p = reinterpret_cast<const char* const>(q);");
8536   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
8537   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
8538   verifyGoogleFormat("template <typename T>\n"
8539                      "void f(int i = 0, SomeType** temps = NULL);");
8540 
8541   FormatStyle Left = getLLVMStyle();
8542   Left.PointerAlignment = FormatStyle::PAS_Left;
8543   verifyFormat("x = *a(x) = *a(y);", Left);
8544   verifyFormat("for (;; *a = b) {\n}", Left);
8545   verifyFormat("return *this += 1;", Left);
8546   verifyFormat("throw *x;", Left);
8547   verifyFormat("delete *x;", Left);
8548   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
8549   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
8550   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
8551   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
8552   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
8553   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
8554   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
8555   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
8556   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
8557 
8558   verifyIndependentOfContext("a = *(x + y);");
8559   verifyIndependentOfContext("a = &(x + y);");
8560   verifyIndependentOfContext("*(x + y).call();");
8561   verifyIndependentOfContext("&(x + y)->call();");
8562   verifyFormat("void f() { &(*I).first; }");
8563 
8564   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
8565   verifyFormat(
8566       "int *MyValues = {\n"
8567       "    *A, // Operator detection might be confused by the '{'\n"
8568       "    *BB // Operator detection might be confused by previous comment\n"
8569       "};");
8570 
8571   verifyIndependentOfContext("if (int *a = &b)");
8572   verifyIndependentOfContext("if (int &a = *b)");
8573   verifyIndependentOfContext("if (a & b[i])");
8574   verifyIndependentOfContext("if constexpr (a & b[i])");
8575   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
8576   verifyIndependentOfContext("if (a * (b * c))");
8577   verifyIndependentOfContext("if constexpr (a * (b * c))");
8578   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
8579   verifyIndependentOfContext("if (a::b::c::d & b[i])");
8580   verifyIndependentOfContext("if (*b[i])");
8581   verifyIndependentOfContext("if (int *a = (&b))");
8582   verifyIndependentOfContext("while (int *a = &b)");
8583   verifyIndependentOfContext("while (a * (b * c))");
8584   verifyIndependentOfContext("size = sizeof *a;");
8585   verifyIndependentOfContext("if (a && (b = c))");
8586   verifyFormat("void f() {\n"
8587                "  for (const int &v : Values) {\n"
8588                "  }\n"
8589                "}");
8590   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
8591   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
8592   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
8593 
8594   verifyFormat("#define A (!a * b)");
8595   verifyFormat("#define MACRO     \\\n"
8596                "  int *i = a * b; \\\n"
8597                "  void f(a *b);",
8598                getLLVMStyleWithColumns(19));
8599 
8600   verifyIndependentOfContext("A = new SomeType *[Length];");
8601   verifyIndependentOfContext("A = new SomeType *[Length]();");
8602   verifyIndependentOfContext("T **t = new T *;");
8603   verifyIndependentOfContext("T **t = new T *();");
8604   verifyGoogleFormat("A = new SomeType*[Length]();");
8605   verifyGoogleFormat("A = new SomeType*[Length];");
8606   verifyGoogleFormat("T** t = new T*;");
8607   verifyGoogleFormat("T** t = new T*();");
8608 
8609   verifyFormat("STATIC_ASSERT((a & b) == 0);");
8610   verifyFormat("STATIC_ASSERT(0 == (a & b));");
8611   verifyFormat("template <bool a, bool b> "
8612                "typename t::if<x && y>::type f() {}");
8613   verifyFormat("template <int *y> f() {}");
8614   verifyFormat("vector<int *> v;");
8615   verifyFormat("vector<int *const> v;");
8616   verifyFormat("vector<int *const **const *> v;");
8617   verifyFormat("vector<int *volatile> v;");
8618   verifyFormat("vector<a *_Nonnull> v;");
8619   verifyFormat("vector<a *_Nullable> v;");
8620   verifyFormat("vector<a *_Null_unspecified> v;");
8621   verifyFormat("vector<a *__ptr32> v;");
8622   verifyFormat("vector<a *__ptr64> v;");
8623   verifyFormat("vector<a *__capability> v;");
8624   FormatStyle TypeMacros = getLLVMStyle();
8625   TypeMacros.TypenameMacros = {"LIST"};
8626   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
8627   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
8628   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
8629   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
8630   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
8631 
8632   FormatStyle CustomQualifier = getLLVMStyle();
8633   // Add indentifers that should not be parsed as a qualifier by default.
8634   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8635   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
8636   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
8637   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
8638   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
8639   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
8640   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
8641   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
8642   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
8643   verifyFormat("vector<a * _NotAQualifier> v;");
8644   verifyFormat("vector<a * __not_a_qualifier> v;");
8645   verifyFormat("vector<a * b> v;");
8646   verifyFormat("foo<b && false>();");
8647   verifyFormat("foo<b & 1>();");
8648   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
8649   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
8650   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
8651   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
8652   verifyFormat(
8653       "template <class T, class = typename std::enable_if<\n"
8654       "                       std::is_integral<T>::value &&\n"
8655       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
8656       "void F();",
8657       getLLVMStyleWithColumns(70));
8658   verifyFormat("template <class T,\n"
8659                "          class = typename std::enable_if<\n"
8660                "              std::is_integral<T>::value &&\n"
8661                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
8662                "          class U>\n"
8663                "void F();",
8664                getLLVMStyleWithColumns(70));
8665   verifyFormat(
8666       "template <class T,\n"
8667       "          class = typename ::std::enable_if<\n"
8668       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
8669       "void F();",
8670       getGoogleStyleWithColumns(68));
8671 
8672   verifyIndependentOfContext("MACRO(int *i);");
8673   verifyIndependentOfContext("MACRO(auto *a);");
8674   verifyIndependentOfContext("MACRO(const A *a);");
8675   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
8676   verifyIndependentOfContext("MACRO(decltype(A) *a);");
8677   verifyIndependentOfContext("MACRO(typeof(A) *a);");
8678   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
8679   verifyIndependentOfContext("MACRO(A *const a);");
8680   verifyIndependentOfContext("MACRO(A *restrict a);");
8681   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
8682   verifyIndependentOfContext("MACRO(A *__restrict a);");
8683   verifyIndependentOfContext("MACRO(A *volatile a);");
8684   verifyIndependentOfContext("MACRO(A *__volatile a);");
8685   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
8686   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
8687   verifyIndependentOfContext("MACRO(A *_Nullable a);");
8688   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
8689   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
8690   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
8691   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
8692   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
8693   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
8694   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
8695   verifyIndependentOfContext("MACRO(A *__capability);");
8696   verifyIndependentOfContext("MACRO(A &__capability);");
8697   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
8698   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
8699   // If we add __my_qualifier to AttributeMacros it should always be parsed as
8700   // a type declaration:
8701   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
8702   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
8703   // Also check that TypenameMacros prevents parsing it as multiplication:
8704   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
8705   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
8706 
8707   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
8708   verifyFormat("void f() { f(float{1}, a * a); }");
8709   verifyFormat("void f() { f(float(1), a * a); }");
8710   // FIXME: Is there a way to make this work?
8711   // verifyIndependentOfContext("MACRO(A *a);");
8712   verifyFormat("MACRO(A &B);");
8713   verifyFormat("MACRO(A *B);");
8714   verifyFormat("void f() { MACRO(A * B); }");
8715   verifyFormat("void f() { MACRO(A & B); }");
8716 
8717   // This lambda was mis-formatted after D88956 (treating it as a binop):
8718   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
8719   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
8720   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
8721   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
8722 
8723   verifyFormat("DatumHandle const *operator->() const { return input_; }");
8724   verifyFormat("return options != nullptr && operator==(*options);");
8725 
8726   EXPECT_EQ("#define OP(x)                                    \\\n"
8727             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
8728             "    return s << a.DebugString();                 \\\n"
8729             "  }",
8730             format("#define OP(x) \\\n"
8731                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
8732                    "    return s << a.DebugString(); \\\n"
8733                    "  }",
8734                    getLLVMStyleWithColumns(50)));
8735 
8736   // FIXME: We cannot handle this case yet; we might be able to figure out that
8737   // foo<x> d > v; doesn't make sense.
8738   verifyFormat("foo<a<b && c> d> v;");
8739 
8740   FormatStyle PointerMiddle = getLLVMStyle();
8741   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
8742   verifyFormat("delete *x;", PointerMiddle);
8743   verifyFormat("int * x;", PointerMiddle);
8744   verifyFormat("int *[] x;", PointerMiddle);
8745   verifyFormat("template <int * y> f() {}", PointerMiddle);
8746   verifyFormat("int * f(int * a) {}", PointerMiddle);
8747   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
8748   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
8749   verifyFormat("A<int *> a;", PointerMiddle);
8750   verifyFormat("A<int **> a;", PointerMiddle);
8751   verifyFormat("A<int *, int *> a;", PointerMiddle);
8752   verifyFormat("A<int *[]> a;", PointerMiddle);
8753   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
8754   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
8755   verifyFormat("T ** t = new T *;", PointerMiddle);
8756 
8757   // Member function reference qualifiers aren't binary operators.
8758   verifyFormat("string // break\n"
8759                "operator()() & {}");
8760   verifyFormat("string // break\n"
8761                "operator()() && {}");
8762   verifyGoogleFormat("template <typename T>\n"
8763                      "auto x() & -> int {}");
8764 }
8765 
8766 TEST_F(FormatTest, UnderstandsAttributes) {
8767   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
8768   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
8769                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8770   FormatStyle AfterType = getLLVMStyle();
8771   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8772   verifyFormat("__attribute__((nodebug)) void\n"
8773                "foo() {}\n",
8774                AfterType);
8775   verifyFormat("__unused void\n"
8776                "foo() {}",
8777                AfterType);
8778 
8779   FormatStyle CustomAttrs = getLLVMStyle();
8780   CustomAttrs.AttributeMacros.push_back("__unused");
8781   CustomAttrs.AttributeMacros.push_back("__attr1");
8782   CustomAttrs.AttributeMacros.push_back("__attr2");
8783   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
8784   verifyFormat("vector<SomeType *__attribute((foo))> v;");
8785   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
8786   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
8787   // Check that it is parsed as a multiplication without AttributeMacros and
8788   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
8789   verifyFormat("vector<SomeType * __attr1> v;");
8790   verifyFormat("vector<SomeType __attr1 *> v;");
8791   verifyFormat("vector<SomeType __attr1 *const> v;");
8792   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
8793   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
8794   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
8795   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
8796   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
8797   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
8798   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
8799   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
8800 
8801   // Check that these are not parsed as function declarations:
8802   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8803   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
8804   verifyFormat("SomeType s(InitValue);", CustomAttrs);
8805   verifyFormat("SomeType s{InitValue};", CustomAttrs);
8806   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
8807   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
8808   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
8809   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
8810   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
8811   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
8812 }
8813 
8814 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
8815   // Check that qualifiers on pointers don't break parsing of casts.
8816   verifyFormat("x = (foo *const)*v;");
8817   verifyFormat("x = (foo *volatile)*v;");
8818   verifyFormat("x = (foo *restrict)*v;");
8819   verifyFormat("x = (foo *__attribute__((foo)))*v;");
8820   verifyFormat("x = (foo *_Nonnull)*v;");
8821   verifyFormat("x = (foo *_Nullable)*v;");
8822   verifyFormat("x = (foo *_Null_unspecified)*v;");
8823   verifyFormat("x = (foo *_Nonnull)*v;");
8824   verifyFormat("x = (foo *[[clang::attr]])*v;");
8825   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
8826   verifyFormat("x = (foo *__ptr32)*v;");
8827   verifyFormat("x = (foo *__ptr64)*v;");
8828   verifyFormat("x = (foo *__capability)*v;");
8829 
8830   // Check that we handle multiple trailing qualifiers and skip them all to
8831   // determine that the expression is a cast to a pointer type.
8832   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
8833   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
8834   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
8835   StringRef AllQualifiers =
8836       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
8837       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
8838   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
8839   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
8840 
8841   // Also check that address-of is not parsed as a binary bitwise-and:
8842   verifyFormat("x = (foo *const)&v;");
8843   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
8844   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
8845 
8846   // Check custom qualifiers:
8847   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
8848   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8849   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
8850   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
8851   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
8852                CustomQualifier);
8853   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
8854                CustomQualifier);
8855 
8856   // Check that unknown identifiers result in binary operator parsing:
8857   verifyFormat("x = (foo * __unknown_qualifier) * v;");
8858   verifyFormat("x = (foo * __unknown_qualifier) & v;");
8859 }
8860 
8861 TEST_F(FormatTest, UnderstandsSquareAttributes) {
8862   verifyFormat("SomeType s [[unused]] (InitValue);");
8863   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
8864   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
8865   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
8866   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
8867   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8868                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8869   verifyFormat("[[nodiscard]] bool f() { return false; }");
8870   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
8871   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
8872   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
8873 
8874   // Make sure we do not mistake attributes for array subscripts.
8875   verifyFormat("int a() {}\n"
8876                "[[unused]] int b() {}\n");
8877   verifyFormat("NSArray *arr;\n"
8878                "arr[[Foo() bar]];");
8879 
8880   // On the other hand, we still need to correctly find array subscripts.
8881   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
8882 
8883   // Make sure that we do not mistake Objective-C method inside array literals
8884   // as attributes, even if those method names are also keywords.
8885   verifyFormat("@[ [foo bar] ];");
8886   verifyFormat("@[ [NSArray class] ];");
8887   verifyFormat("@[ [foo enum] ];");
8888 
8889   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
8890 
8891   // Make sure we do not parse attributes as lambda introducers.
8892   FormatStyle MultiLineFunctions = getLLVMStyle();
8893   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8894   verifyFormat("[[unused]] int b() {\n"
8895                "  return 42;\n"
8896                "}\n",
8897                MultiLineFunctions);
8898 }
8899 
8900 TEST_F(FormatTest, AttributeClass) {
8901   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
8902   verifyFormat("class S {\n"
8903                "  S(S&&) = default;\n"
8904                "};",
8905                Style);
8906   verifyFormat("class [[nodiscard]] S {\n"
8907                "  S(S&&) = default;\n"
8908                "};",
8909                Style);
8910   verifyFormat("class __attribute((maybeunused)) S {\n"
8911                "  S(S&&) = default;\n"
8912                "};",
8913                Style);
8914   verifyFormat("struct S {\n"
8915                "  S(S&&) = default;\n"
8916                "};",
8917                Style);
8918   verifyFormat("struct [[nodiscard]] S {\n"
8919                "  S(S&&) = default;\n"
8920                "};",
8921                Style);
8922 }
8923 
8924 TEST_F(FormatTest, AttributesAfterMacro) {
8925   FormatStyle Style = getLLVMStyle();
8926   verifyFormat("MACRO;\n"
8927                "__attribute__((maybe_unused)) int foo() {\n"
8928                "  //...\n"
8929                "}");
8930 
8931   verifyFormat("MACRO;\n"
8932                "[[nodiscard]] int foo() {\n"
8933                "  //...\n"
8934                "}");
8935 
8936   EXPECT_EQ("MACRO\n\n"
8937             "__attribute__((maybe_unused)) int foo() {\n"
8938             "  //...\n"
8939             "}",
8940             format("MACRO\n\n"
8941                    "__attribute__((maybe_unused)) int foo() {\n"
8942                    "  //...\n"
8943                    "}"));
8944 
8945   EXPECT_EQ("MACRO\n\n"
8946             "[[nodiscard]] int foo() {\n"
8947             "  //...\n"
8948             "}",
8949             format("MACRO\n\n"
8950                    "[[nodiscard]] int foo() {\n"
8951                    "  //...\n"
8952                    "}"));
8953 }
8954 
8955 TEST_F(FormatTest, AttributePenaltyBreaking) {
8956   FormatStyle Style = getLLVMStyle();
8957   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
8958                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8959                Style);
8960   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
8961                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8962                Style);
8963   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
8964                "shared_ptr<ALongTypeName> &C d) {\n}",
8965                Style);
8966 }
8967 
8968 TEST_F(FormatTest, UnderstandsEllipsis) {
8969   FormatStyle Style = getLLVMStyle();
8970   verifyFormat("int printf(const char *fmt, ...);");
8971   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
8972   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
8973 
8974   verifyFormat("template <int *...PP> a;", Style);
8975 
8976   Style.PointerAlignment = FormatStyle::PAS_Left;
8977   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
8978 
8979   verifyFormat("template <int*... PP> a;", Style);
8980 
8981   Style.PointerAlignment = FormatStyle::PAS_Middle;
8982   verifyFormat("template <int *... PP> a;", Style);
8983 }
8984 
8985 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
8986   EXPECT_EQ("int *a;\n"
8987             "int *a;\n"
8988             "int *a;",
8989             format("int *a;\n"
8990                    "int* a;\n"
8991                    "int *a;",
8992                    getGoogleStyle()));
8993   EXPECT_EQ("int* a;\n"
8994             "int* a;\n"
8995             "int* a;",
8996             format("int* a;\n"
8997                    "int* a;\n"
8998                    "int *a;",
8999                    getGoogleStyle()));
9000   EXPECT_EQ("int *a;\n"
9001             "int *a;\n"
9002             "int *a;",
9003             format("int *a;\n"
9004                    "int * a;\n"
9005                    "int *  a;",
9006                    getGoogleStyle()));
9007   EXPECT_EQ("auto x = [] {\n"
9008             "  int *a;\n"
9009             "  int *a;\n"
9010             "  int *a;\n"
9011             "};",
9012             format("auto x=[]{int *a;\n"
9013                    "int * a;\n"
9014                    "int *  a;};",
9015                    getGoogleStyle()));
9016 }
9017 
9018 TEST_F(FormatTest, UnderstandsRvalueReferences) {
9019   verifyFormat("int f(int &&a) {}");
9020   verifyFormat("int f(int a, char &&b) {}");
9021   verifyFormat("void f() { int &&a = b; }");
9022   verifyGoogleFormat("int f(int a, char&& b) {}");
9023   verifyGoogleFormat("void f() { int&& a = b; }");
9024 
9025   verifyIndependentOfContext("A<int &&> a;");
9026   verifyIndependentOfContext("A<int &&, int &&> a;");
9027   verifyGoogleFormat("A<int&&> a;");
9028   verifyGoogleFormat("A<int&&, int&&> a;");
9029 
9030   // Not rvalue references:
9031   verifyFormat("template <bool B, bool C> class A {\n"
9032                "  static_assert(B && C, \"Something is wrong\");\n"
9033                "};");
9034   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
9035   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
9036   verifyFormat("#define A(a, b) (a && b)");
9037 }
9038 
9039 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
9040   verifyFormat("void f() {\n"
9041                "  x[aaaaaaaaa -\n"
9042                "    b] = 23;\n"
9043                "}",
9044                getLLVMStyleWithColumns(15));
9045 }
9046 
9047 TEST_F(FormatTest, FormatsCasts) {
9048   verifyFormat("Type *A = static_cast<Type *>(P);");
9049   verifyFormat("Type *A = (Type *)P;");
9050   verifyFormat("Type *A = (vector<Type *, int *>)P;");
9051   verifyFormat("int a = (int)(2.0f);");
9052   verifyFormat("int a = (int)2.0f;");
9053   verifyFormat("x[(int32)y];");
9054   verifyFormat("x = (int32)y;");
9055   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
9056   verifyFormat("int a = (int)*b;");
9057   verifyFormat("int a = (int)2.0f;");
9058   verifyFormat("int a = (int)~0;");
9059   verifyFormat("int a = (int)++a;");
9060   verifyFormat("int a = (int)sizeof(int);");
9061   verifyFormat("int a = (int)+2;");
9062   verifyFormat("my_int a = (my_int)2.0f;");
9063   verifyFormat("my_int a = (my_int)sizeof(int);");
9064   verifyFormat("return (my_int)aaa;");
9065   verifyFormat("#define x ((int)-1)");
9066   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
9067   verifyFormat("#define p(q) ((int *)&q)");
9068   verifyFormat("fn(a)(b) + 1;");
9069 
9070   verifyFormat("void f() { my_int a = (my_int)*b; }");
9071   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
9072   verifyFormat("my_int a = (my_int)~0;");
9073   verifyFormat("my_int a = (my_int)++a;");
9074   verifyFormat("my_int a = (my_int)-2;");
9075   verifyFormat("my_int a = (my_int)1;");
9076   verifyFormat("my_int a = (my_int *)1;");
9077   verifyFormat("my_int a = (const my_int)-1;");
9078   verifyFormat("my_int a = (const my_int *)-1;");
9079   verifyFormat("my_int a = (my_int)(my_int)-1;");
9080   verifyFormat("my_int a = (ns::my_int)-2;");
9081   verifyFormat("case (my_int)ONE:");
9082   verifyFormat("auto x = (X)this;");
9083   // Casts in Obj-C style calls used to not be recognized as such.
9084   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
9085 
9086   // FIXME: single value wrapped with paren will be treated as cast.
9087   verifyFormat("void f(int i = (kValue)*kMask) {}");
9088 
9089   verifyFormat("{ (void)F; }");
9090 
9091   // Don't break after a cast's
9092   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9093                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
9094                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
9095 
9096   // These are not casts.
9097   verifyFormat("void f(int *) {}");
9098   verifyFormat("f(foo)->b;");
9099   verifyFormat("f(foo).b;");
9100   verifyFormat("f(foo)(b);");
9101   verifyFormat("f(foo)[b];");
9102   verifyFormat("[](foo) { return 4; }(bar);");
9103   verifyFormat("(*funptr)(foo)[4];");
9104   verifyFormat("funptrs[4](foo)[4];");
9105   verifyFormat("void f(int *);");
9106   verifyFormat("void f(int *) = 0;");
9107   verifyFormat("void f(SmallVector<int>) {}");
9108   verifyFormat("void f(SmallVector<int>);");
9109   verifyFormat("void f(SmallVector<int>) = 0;");
9110   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
9111   verifyFormat("int a = sizeof(int) * b;");
9112   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
9113   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
9114   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
9115   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
9116 
9117   // These are not casts, but at some point were confused with casts.
9118   verifyFormat("virtual void foo(int *) override;");
9119   verifyFormat("virtual void foo(char &) const;");
9120   verifyFormat("virtual void foo(int *a, char *) const;");
9121   verifyFormat("int a = sizeof(int *) + b;");
9122   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
9123   verifyFormat("bool b = f(g<int>) && c;");
9124   verifyFormat("typedef void (*f)(int i) func;");
9125   verifyFormat("void operator++(int) noexcept;");
9126   verifyFormat("void operator++(int &) noexcept;");
9127   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
9128                "&) noexcept;");
9129   verifyFormat(
9130       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
9131   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
9132   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
9133   verifyFormat("void operator delete(nothrow_t &) noexcept;");
9134   verifyFormat("void operator delete(foo &) noexcept;");
9135   verifyFormat("void operator delete(foo) noexcept;");
9136   verifyFormat("void operator delete(int) noexcept;");
9137   verifyFormat("void operator delete(int &) noexcept;");
9138   verifyFormat("void operator delete(int &) volatile noexcept;");
9139   verifyFormat("void operator delete(int &) const");
9140   verifyFormat("void operator delete(int &) = default");
9141   verifyFormat("void operator delete(int &) = delete");
9142   verifyFormat("void operator delete(int &) [[noreturn]]");
9143   verifyFormat("void operator delete(int &) throw();");
9144   verifyFormat("void operator delete(int &) throw(int);");
9145   verifyFormat("auto operator delete(int &) -> int;");
9146   verifyFormat("auto operator delete(int &) override");
9147   verifyFormat("auto operator delete(int &) final");
9148 
9149   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
9150                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
9151   // FIXME: The indentation here is not ideal.
9152   verifyFormat(
9153       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9154       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
9155       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
9156 }
9157 
9158 TEST_F(FormatTest, FormatsFunctionTypes) {
9159   verifyFormat("A<bool()> a;");
9160   verifyFormat("A<SomeType()> a;");
9161   verifyFormat("A<void (*)(int, std::string)> a;");
9162   verifyFormat("A<void *(int)>;");
9163   verifyFormat("void *(*a)(int *, SomeType *);");
9164   verifyFormat("int (*func)(void *);");
9165   verifyFormat("void f() { int (*func)(void *); }");
9166   verifyFormat("template <class CallbackClass>\n"
9167                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
9168 
9169   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
9170   verifyGoogleFormat("void* (*a)(int);");
9171   verifyGoogleFormat(
9172       "template <class CallbackClass>\n"
9173       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
9174 
9175   // Other constructs can look somewhat like function types:
9176   verifyFormat("A<sizeof(*x)> a;");
9177   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
9178   verifyFormat("some_var = function(*some_pointer_var)[0];");
9179   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
9180   verifyFormat("int x = f(&h)();");
9181   verifyFormat("returnsFunction(&param1, &param2)(param);");
9182   verifyFormat("std::function<\n"
9183                "    LooooooooooongTemplatedType<\n"
9184                "        SomeType>*(\n"
9185                "        LooooooooooooooooongType type)>\n"
9186                "    function;",
9187                getGoogleStyleWithColumns(40));
9188 }
9189 
9190 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
9191   verifyFormat("A (*foo_)[6];");
9192   verifyFormat("vector<int> (*foo_)[6];");
9193 }
9194 
9195 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
9196   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
9197                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
9198   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
9199                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
9200   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
9201                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
9202 
9203   // Different ways of ()-initializiation.
9204   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
9205                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
9206   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
9207                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
9208   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
9209                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
9210   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
9211                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
9212 
9213   // Lambdas should not confuse the variable declaration heuristic.
9214   verifyFormat("LooooooooooooooooongType\n"
9215                "    variable(nullptr, [](A *a) {});",
9216                getLLVMStyleWithColumns(40));
9217 }
9218 
9219 TEST_F(FormatTest, BreaksLongDeclarations) {
9220   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
9221                "    AnotherNameForTheLongType;");
9222   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
9223                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
9224   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
9225                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
9226   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
9227                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
9228   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
9229                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
9230   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
9231                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
9232   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
9233                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
9234   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
9235                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
9236   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
9237                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
9238   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
9239                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
9240   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
9241                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
9242   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
9243                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
9244   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
9245                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
9246   FormatStyle Indented = getLLVMStyle();
9247   Indented.IndentWrappedFunctionNames = true;
9248   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
9249                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
9250                Indented);
9251   verifyFormat(
9252       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
9253       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
9254       Indented);
9255   verifyFormat(
9256       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
9257       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
9258       Indented);
9259   verifyFormat(
9260       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
9261       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
9262       Indented);
9263 
9264   // FIXME: Without the comment, this breaks after "(".
9265   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
9266                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
9267                getGoogleStyle());
9268 
9269   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
9270                "                  int LoooooooooooooooooooongParam2) {}");
9271   verifyFormat(
9272       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
9273       "                                   SourceLocation L, IdentifierIn *II,\n"
9274       "                                   Type *T) {}");
9275   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
9276                "ReallyReaaallyLongFunctionName(\n"
9277                "    const std::string &SomeParameter,\n"
9278                "    const SomeType<string, SomeOtherTemplateParameter>\n"
9279                "        &ReallyReallyLongParameterName,\n"
9280                "    const SomeType<string, SomeOtherTemplateParameter>\n"
9281                "        &AnotherLongParameterName) {}");
9282   verifyFormat("template <typename A>\n"
9283                "SomeLoooooooooooooooooooooongType<\n"
9284                "    typename some_namespace::SomeOtherType<A>::Type>\n"
9285                "Function() {}");
9286 
9287   verifyGoogleFormat(
9288       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
9289       "    aaaaaaaaaaaaaaaaaaaaaaa;");
9290   verifyGoogleFormat(
9291       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
9292       "                                   SourceLocation L) {}");
9293   verifyGoogleFormat(
9294       "some_namespace::LongReturnType\n"
9295       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
9296       "    int first_long_parameter, int second_parameter) {}");
9297 
9298   verifyGoogleFormat("template <typename T>\n"
9299                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
9300                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
9301   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9302                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
9303 
9304   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9305                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9306                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9307   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9308                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
9309                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
9310   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9311                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
9312                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
9313                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9314 
9315   verifyFormat("template <typename T> // Templates on own line.\n"
9316                "static int            // Some comment.\n"
9317                "MyFunction(int a);",
9318                getLLVMStyle());
9319 }
9320 
9321 TEST_F(FormatTest, FormatsAccessModifiers) {
9322   FormatStyle Style = getLLVMStyle();
9323   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
9324             FormatStyle::ELBAMS_LogicalBlock);
9325   verifyFormat("struct foo {\n"
9326                "private:\n"
9327                "  void f() {}\n"
9328                "\n"
9329                "private:\n"
9330                "  int i;\n"
9331                "\n"
9332                "protected:\n"
9333                "  int j;\n"
9334                "};\n",
9335                Style);
9336   verifyFormat("struct foo {\n"
9337                "private:\n"
9338                "  void f() {}\n"
9339                "\n"
9340                "private:\n"
9341                "  int i;\n"
9342                "\n"
9343                "protected:\n"
9344                "  int j;\n"
9345                "};\n",
9346                "struct foo {\n"
9347                "private:\n"
9348                "  void f() {}\n"
9349                "private:\n"
9350                "  int i;\n"
9351                "protected:\n"
9352                "  int j;\n"
9353                "};\n",
9354                Style);
9355   verifyFormat("struct foo { /* comment */\n"
9356                "private:\n"
9357                "  int i;\n"
9358                "  // comment\n"
9359                "private:\n"
9360                "  int j;\n"
9361                "};\n",
9362                Style);
9363   verifyFormat("struct foo {\n"
9364                "#ifdef FOO\n"
9365                "#endif\n"
9366                "private:\n"
9367                "  int i;\n"
9368                "#ifdef FOO\n"
9369                "private:\n"
9370                "#endif\n"
9371                "  int j;\n"
9372                "};\n",
9373                Style);
9374   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9375   verifyFormat("struct foo {\n"
9376                "private:\n"
9377                "  void f() {}\n"
9378                "private:\n"
9379                "  int i;\n"
9380                "protected:\n"
9381                "  int j;\n"
9382                "};\n",
9383                Style);
9384   verifyFormat("struct foo {\n"
9385                "private:\n"
9386                "  void f() {}\n"
9387                "private:\n"
9388                "  int i;\n"
9389                "protected:\n"
9390                "  int j;\n"
9391                "};\n",
9392                "struct foo {\n"
9393                "\n"
9394                "private:\n"
9395                "  void f() {}\n"
9396                "\n"
9397                "private:\n"
9398                "  int i;\n"
9399                "\n"
9400                "protected:\n"
9401                "  int j;\n"
9402                "};\n",
9403                Style);
9404   verifyFormat("struct foo { /* comment */\n"
9405                "private:\n"
9406                "  int i;\n"
9407                "  // comment\n"
9408                "private:\n"
9409                "  int j;\n"
9410                "};\n",
9411                "struct foo { /* comment */\n"
9412                "\n"
9413                "private:\n"
9414                "  int i;\n"
9415                "  // comment\n"
9416                "\n"
9417                "private:\n"
9418                "  int j;\n"
9419                "};\n",
9420                Style);
9421   verifyFormat("struct foo {\n"
9422                "#ifdef FOO\n"
9423                "#endif\n"
9424                "private:\n"
9425                "  int i;\n"
9426                "#ifdef FOO\n"
9427                "private:\n"
9428                "#endif\n"
9429                "  int j;\n"
9430                "};\n",
9431                "struct foo {\n"
9432                "#ifdef FOO\n"
9433                "#endif\n"
9434                "\n"
9435                "private:\n"
9436                "  int i;\n"
9437                "#ifdef FOO\n"
9438                "\n"
9439                "private:\n"
9440                "#endif\n"
9441                "  int j;\n"
9442                "};\n",
9443                Style);
9444   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9445   verifyFormat("struct foo {\n"
9446                "private:\n"
9447                "  void f() {}\n"
9448                "\n"
9449                "private:\n"
9450                "  int i;\n"
9451                "\n"
9452                "protected:\n"
9453                "  int j;\n"
9454                "};\n",
9455                Style);
9456   verifyFormat("struct foo {\n"
9457                "private:\n"
9458                "  void f() {}\n"
9459                "\n"
9460                "private:\n"
9461                "  int i;\n"
9462                "\n"
9463                "protected:\n"
9464                "  int j;\n"
9465                "};\n",
9466                "struct foo {\n"
9467                "private:\n"
9468                "  void f() {}\n"
9469                "private:\n"
9470                "  int i;\n"
9471                "protected:\n"
9472                "  int j;\n"
9473                "};\n",
9474                Style);
9475   verifyFormat("struct foo { /* comment */\n"
9476                "private:\n"
9477                "  int i;\n"
9478                "  // comment\n"
9479                "\n"
9480                "private:\n"
9481                "  int j;\n"
9482                "};\n",
9483                "struct foo { /* comment */\n"
9484                "private:\n"
9485                "  int i;\n"
9486                "  // comment\n"
9487                "\n"
9488                "private:\n"
9489                "  int j;\n"
9490                "};\n",
9491                Style);
9492   verifyFormat("struct foo {\n"
9493                "#ifdef FOO\n"
9494                "#endif\n"
9495                "\n"
9496                "private:\n"
9497                "  int i;\n"
9498                "#ifdef FOO\n"
9499                "\n"
9500                "private:\n"
9501                "#endif\n"
9502                "  int j;\n"
9503                "};\n",
9504                "struct foo {\n"
9505                "#ifdef FOO\n"
9506                "#endif\n"
9507                "private:\n"
9508                "  int i;\n"
9509                "#ifdef FOO\n"
9510                "private:\n"
9511                "#endif\n"
9512                "  int j;\n"
9513                "};\n",
9514                Style);
9515   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9516   EXPECT_EQ("struct foo {\n"
9517             "\n"
9518             "private:\n"
9519             "  void f() {}\n"
9520             "\n"
9521             "private:\n"
9522             "  int i;\n"
9523             "\n"
9524             "protected:\n"
9525             "  int j;\n"
9526             "};\n",
9527             format("struct foo {\n"
9528                    "\n"
9529                    "private:\n"
9530                    "  void f() {}\n"
9531                    "\n"
9532                    "private:\n"
9533                    "  int i;\n"
9534                    "\n"
9535                    "protected:\n"
9536                    "  int j;\n"
9537                    "};\n",
9538                    Style));
9539   verifyFormat("struct foo {\n"
9540                "private:\n"
9541                "  void f() {}\n"
9542                "private:\n"
9543                "  int i;\n"
9544                "protected:\n"
9545                "  int j;\n"
9546                "};\n",
9547                Style);
9548   EXPECT_EQ("struct foo { /* comment */\n"
9549             "\n"
9550             "private:\n"
9551             "  int i;\n"
9552             "  // comment\n"
9553             "\n"
9554             "private:\n"
9555             "  int j;\n"
9556             "};\n",
9557             format("struct foo { /* comment */\n"
9558                    "\n"
9559                    "private:\n"
9560                    "  int i;\n"
9561                    "  // comment\n"
9562                    "\n"
9563                    "private:\n"
9564                    "  int j;\n"
9565                    "};\n",
9566                    Style));
9567   verifyFormat("struct foo { /* comment */\n"
9568                "private:\n"
9569                "  int i;\n"
9570                "  // comment\n"
9571                "private:\n"
9572                "  int j;\n"
9573                "};\n",
9574                Style);
9575   EXPECT_EQ("struct foo {\n"
9576             "#ifdef FOO\n"
9577             "#endif\n"
9578             "\n"
9579             "private:\n"
9580             "  int i;\n"
9581             "#ifdef FOO\n"
9582             "\n"
9583             "private:\n"
9584             "#endif\n"
9585             "  int j;\n"
9586             "};\n",
9587             format("struct foo {\n"
9588                    "#ifdef FOO\n"
9589                    "#endif\n"
9590                    "\n"
9591                    "private:\n"
9592                    "  int i;\n"
9593                    "#ifdef FOO\n"
9594                    "\n"
9595                    "private:\n"
9596                    "#endif\n"
9597                    "  int j;\n"
9598                    "};\n",
9599                    Style));
9600   verifyFormat("struct foo {\n"
9601                "#ifdef FOO\n"
9602                "#endif\n"
9603                "private:\n"
9604                "  int i;\n"
9605                "#ifdef FOO\n"
9606                "private:\n"
9607                "#endif\n"
9608                "  int j;\n"
9609                "};\n",
9610                Style);
9611 
9612   FormatStyle NoEmptyLines = getLLVMStyle();
9613   NoEmptyLines.MaxEmptyLinesToKeep = 0;
9614   verifyFormat("struct foo {\n"
9615                "private:\n"
9616                "  void f() {}\n"
9617                "\n"
9618                "private:\n"
9619                "  int i;\n"
9620                "\n"
9621                "public:\n"
9622                "protected:\n"
9623                "  int j;\n"
9624                "};\n",
9625                NoEmptyLines);
9626 
9627   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9628   verifyFormat("struct foo {\n"
9629                "private:\n"
9630                "  void f() {}\n"
9631                "private:\n"
9632                "  int i;\n"
9633                "public:\n"
9634                "protected:\n"
9635                "  int j;\n"
9636                "};\n",
9637                NoEmptyLines);
9638 
9639   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9640   verifyFormat("struct foo {\n"
9641                "private:\n"
9642                "  void f() {}\n"
9643                "\n"
9644                "private:\n"
9645                "  int i;\n"
9646                "\n"
9647                "public:\n"
9648                "\n"
9649                "protected:\n"
9650                "  int j;\n"
9651                "};\n",
9652                NoEmptyLines);
9653 }
9654 
9655 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
9656 
9657   FormatStyle Style = getLLVMStyle();
9658   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
9659   verifyFormat("struct foo {\n"
9660                "private:\n"
9661                "  void f() {}\n"
9662                "\n"
9663                "private:\n"
9664                "  int i;\n"
9665                "\n"
9666                "protected:\n"
9667                "  int j;\n"
9668                "};\n",
9669                Style);
9670 
9671   // Check if lines are removed.
9672   verifyFormat("struct foo {\n"
9673                "private:\n"
9674                "  void f() {}\n"
9675                "\n"
9676                "private:\n"
9677                "  int i;\n"
9678                "\n"
9679                "protected:\n"
9680                "  int j;\n"
9681                "};\n",
9682                "struct foo {\n"
9683                "private:\n"
9684                "\n"
9685                "  void f() {}\n"
9686                "\n"
9687                "private:\n"
9688                "\n"
9689                "  int i;\n"
9690                "\n"
9691                "protected:\n"
9692                "\n"
9693                "  int j;\n"
9694                "};\n",
9695                Style);
9696 
9697   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9698   verifyFormat("struct foo {\n"
9699                "private:\n"
9700                "\n"
9701                "  void f() {}\n"
9702                "\n"
9703                "private:\n"
9704                "\n"
9705                "  int i;\n"
9706                "\n"
9707                "protected:\n"
9708                "\n"
9709                "  int j;\n"
9710                "};\n",
9711                Style);
9712 
9713   // Check if lines are added.
9714   verifyFormat("struct foo {\n"
9715                "private:\n"
9716                "\n"
9717                "  void f() {}\n"
9718                "\n"
9719                "private:\n"
9720                "\n"
9721                "  int i;\n"
9722                "\n"
9723                "protected:\n"
9724                "\n"
9725                "  int j;\n"
9726                "};\n",
9727                "struct foo {\n"
9728                "private:\n"
9729                "  void f() {}\n"
9730                "\n"
9731                "private:\n"
9732                "  int i;\n"
9733                "\n"
9734                "protected:\n"
9735                "  int j;\n"
9736                "};\n",
9737                Style);
9738 
9739   // Leave tests rely on the code layout, test::messUp can not be used.
9740   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9741   Style.MaxEmptyLinesToKeep = 0u;
9742   verifyFormat("struct foo {\n"
9743                "private:\n"
9744                "  void f() {}\n"
9745                "\n"
9746                "private:\n"
9747                "  int i;\n"
9748                "\n"
9749                "protected:\n"
9750                "  int j;\n"
9751                "};\n",
9752                Style);
9753 
9754   // Check if MaxEmptyLinesToKeep is respected.
9755   EXPECT_EQ("struct foo {\n"
9756             "private:\n"
9757             "  void f() {}\n"
9758             "\n"
9759             "private:\n"
9760             "  int i;\n"
9761             "\n"
9762             "protected:\n"
9763             "  int j;\n"
9764             "};\n",
9765             format("struct foo {\n"
9766                    "private:\n"
9767                    "\n\n\n"
9768                    "  void f() {}\n"
9769                    "\n"
9770                    "private:\n"
9771                    "\n\n\n"
9772                    "  int i;\n"
9773                    "\n"
9774                    "protected:\n"
9775                    "\n\n\n"
9776                    "  int j;\n"
9777                    "};\n",
9778                    Style));
9779 
9780   Style.MaxEmptyLinesToKeep = 1u;
9781   EXPECT_EQ("struct foo {\n"
9782             "private:\n"
9783             "\n"
9784             "  void f() {}\n"
9785             "\n"
9786             "private:\n"
9787             "\n"
9788             "  int i;\n"
9789             "\n"
9790             "protected:\n"
9791             "\n"
9792             "  int j;\n"
9793             "};\n",
9794             format("struct foo {\n"
9795                    "private:\n"
9796                    "\n"
9797                    "  void f() {}\n"
9798                    "\n"
9799                    "private:\n"
9800                    "\n"
9801                    "  int i;\n"
9802                    "\n"
9803                    "protected:\n"
9804                    "\n"
9805                    "  int j;\n"
9806                    "};\n",
9807                    Style));
9808   // Check if no lines are kept.
9809   EXPECT_EQ("struct foo {\n"
9810             "private:\n"
9811             "  void f() {}\n"
9812             "\n"
9813             "private:\n"
9814             "  int i;\n"
9815             "\n"
9816             "protected:\n"
9817             "  int j;\n"
9818             "};\n",
9819             format("struct foo {\n"
9820                    "private:\n"
9821                    "  void f() {}\n"
9822                    "\n"
9823                    "private:\n"
9824                    "  int i;\n"
9825                    "\n"
9826                    "protected:\n"
9827                    "  int j;\n"
9828                    "};\n",
9829                    Style));
9830   // Check if MaxEmptyLinesToKeep is respected.
9831   EXPECT_EQ("struct foo {\n"
9832             "private:\n"
9833             "\n"
9834             "  void f() {}\n"
9835             "\n"
9836             "private:\n"
9837             "\n"
9838             "  int i;\n"
9839             "\n"
9840             "protected:\n"
9841             "\n"
9842             "  int j;\n"
9843             "};\n",
9844             format("struct foo {\n"
9845                    "private:\n"
9846                    "\n\n\n"
9847                    "  void f() {}\n"
9848                    "\n"
9849                    "private:\n"
9850                    "\n\n\n"
9851                    "  int i;\n"
9852                    "\n"
9853                    "protected:\n"
9854                    "\n\n\n"
9855                    "  int j;\n"
9856                    "};\n",
9857                    Style));
9858 
9859   Style.MaxEmptyLinesToKeep = 10u;
9860   EXPECT_EQ("struct foo {\n"
9861             "private:\n"
9862             "\n\n\n"
9863             "  void f() {}\n"
9864             "\n"
9865             "private:\n"
9866             "\n\n\n"
9867             "  int i;\n"
9868             "\n"
9869             "protected:\n"
9870             "\n\n\n"
9871             "  int j;\n"
9872             "};\n",
9873             format("struct foo {\n"
9874                    "private:\n"
9875                    "\n\n\n"
9876                    "  void f() {}\n"
9877                    "\n"
9878                    "private:\n"
9879                    "\n\n\n"
9880                    "  int i;\n"
9881                    "\n"
9882                    "protected:\n"
9883                    "\n\n\n"
9884                    "  int j;\n"
9885                    "};\n",
9886                    Style));
9887 
9888   // Test with comments.
9889   Style = getLLVMStyle();
9890   verifyFormat("struct foo {\n"
9891                "private:\n"
9892                "  // comment\n"
9893                "  void f() {}\n"
9894                "\n"
9895                "private: /* comment */\n"
9896                "  int i;\n"
9897                "};\n",
9898                Style);
9899   verifyFormat("struct foo {\n"
9900                "private:\n"
9901                "  // comment\n"
9902                "  void f() {}\n"
9903                "\n"
9904                "private: /* comment */\n"
9905                "  int i;\n"
9906                "};\n",
9907                "struct foo {\n"
9908                "private:\n"
9909                "\n"
9910                "  // comment\n"
9911                "  void f() {}\n"
9912                "\n"
9913                "private: /* comment */\n"
9914                "\n"
9915                "  int i;\n"
9916                "};\n",
9917                Style);
9918 
9919   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9920   verifyFormat("struct foo {\n"
9921                "private:\n"
9922                "\n"
9923                "  // comment\n"
9924                "  void f() {}\n"
9925                "\n"
9926                "private: /* comment */\n"
9927                "\n"
9928                "  int i;\n"
9929                "};\n",
9930                "struct foo {\n"
9931                "private:\n"
9932                "  // comment\n"
9933                "  void f() {}\n"
9934                "\n"
9935                "private: /* comment */\n"
9936                "  int i;\n"
9937                "};\n",
9938                Style);
9939   verifyFormat("struct foo {\n"
9940                "private:\n"
9941                "\n"
9942                "  // comment\n"
9943                "  void f() {}\n"
9944                "\n"
9945                "private: /* comment */\n"
9946                "\n"
9947                "  int i;\n"
9948                "};\n",
9949                Style);
9950 
9951   // Test with preprocessor defines.
9952   Style = getLLVMStyle();
9953   verifyFormat("struct foo {\n"
9954                "private:\n"
9955                "#ifdef FOO\n"
9956                "#endif\n"
9957                "  void f() {}\n"
9958                "};\n",
9959                Style);
9960   verifyFormat("struct foo {\n"
9961                "private:\n"
9962                "#ifdef FOO\n"
9963                "#endif\n"
9964                "  void f() {}\n"
9965                "};\n",
9966                "struct foo {\n"
9967                "private:\n"
9968                "\n"
9969                "#ifdef FOO\n"
9970                "#endif\n"
9971                "  void f() {}\n"
9972                "};\n",
9973                Style);
9974 
9975   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9976   verifyFormat("struct foo {\n"
9977                "private:\n"
9978                "\n"
9979                "#ifdef FOO\n"
9980                "#endif\n"
9981                "  void f() {}\n"
9982                "};\n",
9983                "struct foo {\n"
9984                "private:\n"
9985                "#ifdef FOO\n"
9986                "#endif\n"
9987                "  void f() {}\n"
9988                "};\n",
9989                Style);
9990   verifyFormat("struct foo {\n"
9991                "private:\n"
9992                "\n"
9993                "#ifdef FOO\n"
9994                "#endif\n"
9995                "  void f() {}\n"
9996                "};\n",
9997                Style);
9998 }
9999 
10000 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
10001   // Combined tests of EmptyLineAfterAccessModifier and
10002   // EmptyLineBeforeAccessModifier.
10003   FormatStyle Style = getLLVMStyle();
10004   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10005   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10006   verifyFormat("struct foo {\n"
10007                "private:\n"
10008                "\n"
10009                "protected:\n"
10010                "};\n",
10011                Style);
10012 
10013   Style.MaxEmptyLinesToKeep = 10u;
10014   // Both remove all new lines.
10015   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10016   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
10017   verifyFormat("struct foo {\n"
10018                "private:\n"
10019                "protected:\n"
10020                "};\n",
10021                "struct foo {\n"
10022                "private:\n"
10023                "\n\n\n"
10024                "protected:\n"
10025                "};\n",
10026                Style);
10027 
10028   // Leave tests rely on the code layout, test::messUp can not be used.
10029   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10030   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10031   Style.MaxEmptyLinesToKeep = 10u;
10032   EXPECT_EQ("struct foo {\n"
10033             "private:\n"
10034             "\n\n\n"
10035             "protected:\n"
10036             "};\n",
10037             format("struct foo {\n"
10038                    "private:\n"
10039                    "\n\n\n"
10040                    "protected:\n"
10041                    "};\n",
10042                    Style));
10043   Style.MaxEmptyLinesToKeep = 3u;
10044   EXPECT_EQ("struct foo {\n"
10045             "private:\n"
10046             "\n\n\n"
10047             "protected:\n"
10048             "};\n",
10049             format("struct foo {\n"
10050                    "private:\n"
10051                    "\n\n\n"
10052                    "protected:\n"
10053                    "};\n",
10054                    Style));
10055   Style.MaxEmptyLinesToKeep = 1u;
10056   EXPECT_EQ("struct foo {\n"
10057             "private:\n"
10058             "\n\n\n"
10059             "protected:\n"
10060             "};\n",
10061             format("struct foo {\n"
10062                    "private:\n"
10063                    "\n\n\n"
10064                    "protected:\n"
10065                    "};\n",
10066                    Style)); // Based on new lines in original document and not
10067                             // on the setting.
10068 
10069   Style.MaxEmptyLinesToKeep = 10u;
10070   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10071   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10072   // Newlines are kept if they are greater than zero,
10073   // test::messUp removes all new lines which changes the logic
10074   EXPECT_EQ("struct foo {\n"
10075             "private:\n"
10076             "\n\n\n"
10077             "protected:\n"
10078             "};\n",
10079             format("struct foo {\n"
10080                    "private:\n"
10081                    "\n\n\n"
10082                    "protected:\n"
10083                    "};\n",
10084                    Style));
10085 
10086   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10087   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10088   // test::messUp removes all new lines which changes the logic
10089   EXPECT_EQ("struct foo {\n"
10090             "private:\n"
10091             "\n\n\n"
10092             "protected:\n"
10093             "};\n",
10094             format("struct foo {\n"
10095                    "private:\n"
10096                    "\n\n\n"
10097                    "protected:\n"
10098                    "};\n",
10099                    Style));
10100 
10101   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10102   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
10103   EXPECT_EQ("struct foo {\n"
10104             "private:\n"
10105             "\n\n\n"
10106             "protected:\n"
10107             "};\n",
10108             format("struct foo {\n"
10109                    "private:\n"
10110                    "\n\n\n"
10111                    "protected:\n"
10112                    "};\n",
10113                    Style)); // test::messUp removes all new lines which changes
10114                             // the logic.
10115 
10116   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10117   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10118   verifyFormat("struct foo {\n"
10119                "private:\n"
10120                "protected:\n"
10121                "};\n",
10122                "struct foo {\n"
10123                "private:\n"
10124                "\n\n\n"
10125                "protected:\n"
10126                "};\n",
10127                Style);
10128 
10129   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10130   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
10131   EXPECT_EQ("struct foo {\n"
10132             "private:\n"
10133             "\n\n\n"
10134             "protected:\n"
10135             "};\n",
10136             format("struct foo {\n"
10137                    "private:\n"
10138                    "\n\n\n"
10139                    "protected:\n"
10140                    "};\n",
10141                    Style)); // test::messUp removes all new lines which changes
10142                             // the logic.
10143 
10144   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10145   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10146   verifyFormat("struct foo {\n"
10147                "private:\n"
10148                "protected:\n"
10149                "};\n",
10150                "struct foo {\n"
10151                "private:\n"
10152                "\n\n\n"
10153                "protected:\n"
10154                "};\n",
10155                Style);
10156 
10157   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
10158   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10159   verifyFormat("struct foo {\n"
10160                "private:\n"
10161                "protected:\n"
10162                "};\n",
10163                "struct foo {\n"
10164                "private:\n"
10165                "\n\n\n"
10166                "protected:\n"
10167                "};\n",
10168                Style);
10169 
10170   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
10171   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10172   verifyFormat("struct foo {\n"
10173                "private:\n"
10174                "protected:\n"
10175                "};\n",
10176                "struct foo {\n"
10177                "private:\n"
10178                "\n\n\n"
10179                "protected:\n"
10180                "};\n",
10181                Style);
10182 
10183   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
10184   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
10185   verifyFormat("struct foo {\n"
10186                "private:\n"
10187                "protected:\n"
10188                "};\n",
10189                "struct foo {\n"
10190                "private:\n"
10191                "\n\n\n"
10192                "protected:\n"
10193                "};\n",
10194                Style);
10195 }
10196 
10197 TEST_F(FormatTest, FormatsArrays) {
10198   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
10199                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
10200   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
10201                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
10202   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
10203                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
10204   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10205                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
10206   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10207                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
10208   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10209                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
10210                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
10211   verifyFormat(
10212       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
10213       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
10214       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
10215   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
10216                "    .aaaaaaaaaaaaaaaaaaaaaa();");
10217 
10218   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
10219                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
10220   verifyFormat(
10221       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
10222       "                                  .aaaaaaa[0]\n"
10223       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
10224   verifyFormat("a[::b::c];");
10225 
10226   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
10227 
10228   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
10229   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
10230 }
10231 
10232 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
10233   verifyFormat("(a)->b();");
10234   verifyFormat("--a;");
10235 }
10236 
10237 TEST_F(FormatTest, HandlesIncludeDirectives) {
10238   verifyFormat("#include <string>\n"
10239                "#include <a/b/c.h>\n"
10240                "#include \"a/b/string\"\n"
10241                "#include \"string.h\"\n"
10242                "#include \"string.h\"\n"
10243                "#include <a-a>\n"
10244                "#include < path with space >\n"
10245                "#include_next <test.h>"
10246                "#include \"abc.h\" // this is included for ABC\n"
10247                "#include \"some long include\" // with a comment\n"
10248                "#include \"some very long include path\"\n"
10249                "#include <some/very/long/include/path>\n",
10250                getLLVMStyleWithColumns(35));
10251   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
10252   EXPECT_EQ("#include <a>", format("#include<a>"));
10253 
10254   verifyFormat("#import <string>");
10255   verifyFormat("#import <a/b/c.h>");
10256   verifyFormat("#import \"a/b/string\"");
10257   verifyFormat("#import \"string.h\"");
10258   verifyFormat("#import \"string.h\"");
10259   verifyFormat("#if __has_include(<strstream>)\n"
10260                "#include <strstream>\n"
10261                "#endif");
10262 
10263   verifyFormat("#define MY_IMPORT <a/b>");
10264 
10265   verifyFormat("#if __has_include(<a/b>)");
10266   verifyFormat("#if __has_include_next(<a/b>)");
10267   verifyFormat("#define F __has_include(<a/b>)");
10268   verifyFormat("#define F __has_include_next(<a/b>)");
10269 
10270   // Protocol buffer definition or missing "#".
10271   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
10272                getLLVMStyleWithColumns(30));
10273 
10274   FormatStyle Style = getLLVMStyle();
10275   Style.AlwaysBreakBeforeMultilineStrings = true;
10276   Style.ColumnLimit = 0;
10277   verifyFormat("#import \"abc.h\"", Style);
10278 
10279   // But 'import' might also be a regular C++ namespace.
10280   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10281                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10282 }
10283 
10284 //===----------------------------------------------------------------------===//
10285 // Error recovery tests.
10286 //===----------------------------------------------------------------------===//
10287 
10288 TEST_F(FormatTest, IncompleteParameterLists) {
10289   FormatStyle NoBinPacking = getLLVMStyle();
10290   NoBinPacking.BinPackParameters = false;
10291   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
10292                "                        double *min_x,\n"
10293                "                        double *max_x,\n"
10294                "                        double *min_y,\n"
10295                "                        double *max_y,\n"
10296                "                        double *min_z,\n"
10297                "                        double *max_z, ) {}",
10298                NoBinPacking);
10299 }
10300 
10301 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
10302   verifyFormat("void f() { return; }\n42");
10303   verifyFormat("void f() {\n"
10304                "  if (0)\n"
10305                "    return;\n"
10306                "}\n"
10307                "42");
10308   verifyFormat("void f() { return }\n42");
10309   verifyFormat("void f() {\n"
10310                "  if (0)\n"
10311                "    return\n"
10312                "}\n"
10313                "42");
10314 }
10315 
10316 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
10317   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
10318   EXPECT_EQ("void f() {\n"
10319             "  if (a)\n"
10320             "    return\n"
10321             "}",
10322             format("void  f  (  )  {  if  ( a )  return  }"));
10323   EXPECT_EQ("namespace N {\n"
10324             "void f()\n"
10325             "}",
10326             format("namespace  N  {  void f()  }"));
10327   EXPECT_EQ("namespace N {\n"
10328             "void f() {}\n"
10329             "void g()\n"
10330             "} // namespace N",
10331             format("namespace N  { void f( ) { } void g( ) }"));
10332 }
10333 
10334 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
10335   verifyFormat("int aaaaaaaa =\n"
10336                "    // Overlylongcomment\n"
10337                "    b;",
10338                getLLVMStyleWithColumns(20));
10339   verifyFormat("function(\n"
10340                "    ShortArgument,\n"
10341                "    LoooooooooooongArgument);\n",
10342                getLLVMStyleWithColumns(20));
10343 }
10344 
10345 TEST_F(FormatTest, IncorrectAccessSpecifier) {
10346   verifyFormat("public:");
10347   verifyFormat("class A {\n"
10348                "public\n"
10349                "  void f() {}\n"
10350                "};");
10351   verifyFormat("public\n"
10352                "int qwerty;");
10353   verifyFormat("public\n"
10354                "B {}");
10355   verifyFormat("public\n"
10356                "{}");
10357   verifyFormat("public\n"
10358                "B { int x; }");
10359 }
10360 
10361 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
10362   verifyFormat("{");
10363   verifyFormat("#})");
10364   verifyNoCrash("(/**/[:!] ?[).");
10365 }
10366 
10367 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
10368   // Found by oss-fuzz:
10369   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
10370   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
10371   Style.ColumnLimit = 60;
10372   verifyNoCrash(
10373       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
10374       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
10375       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
10376       Style);
10377 }
10378 
10379 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
10380   verifyFormat("do {\n}");
10381   verifyFormat("do {\n}\n"
10382                "f();");
10383   verifyFormat("do {\n}\n"
10384                "wheeee(fun);");
10385   verifyFormat("do {\n"
10386                "  f();\n"
10387                "}");
10388 }
10389 
10390 TEST_F(FormatTest, IncorrectCodeMissingParens) {
10391   verifyFormat("if {\n  foo;\n  foo();\n}");
10392   verifyFormat("switch {\n  foo;\n  foo();\n}");
10393   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
10394   verifyFormat("while {\n  foo;\n  foo();\n}");
10395   verifyFormat("do {\n  foo;\n  foo();\n} while;");
10396 }
10397 
10398 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
10399   verifyIncompleteFormat("namespace {\n"
10400                          "class Foo { Foo (\n"
10401                          "};\n"
10402                          "} // namespace");
10403 }
10404 
10405 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
10406   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
10407   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
10408   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
10409   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
10410 
10411   EXPECT_EQ("{\n"
10412             "  {\n"
10413             "    breakme(\n"
10414             "        qwe);\n"
10415             "  }\n",
10416             format("{\n"
10417                    "    {\n"
10418                    " breakme(qwe);\n"
10419                    "}\n",
10420                    getLLVMStyleWithColumns(10)));
10421 }
10422 
10423 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
10424   verifyFormat("int x = {\n"
10425                "    avariable,\n"
10426                "    b(alongervariable)};",
10427                getLLVMStyleWithColumns(25));
10428 }
10429 
10430 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
10431   verifyFormat("return (a)(b){1, 2, 3};");
10432 }
10433 
10434 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
10435   verifyFormat("vector<int> x{1, 2, 3, 4};");
10436   verifyFormat("vector<int> x{\n"
10437                "    1,\n"
10438                "    2,\n"
10439                "    3,\n"
10440                "    4,\n"
10441                "};");
10442   verifyFormat("vector<T> x{{}, {}, {}, {}};");
10443   verifyFormat("f({1, 2});");
10444   verifyFormat("auto v = Foo{-1};");
10445   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
10446   verifyFormat("Class::Class : member{1, 2, 3} {}");
10447   verifyFormat("new vector<int>{1, 2, 3};");
10448   verifyFormat("new int[3]{1, 2, 3};");
10449   verifyFormat("new int{1};");
10450   verifyFormat("return {arg1, arg2};");
10451   verifyFormat("return {arg1, SomeType{parameter}};");
10452   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
10453   verifyFormat("new T{arg1, arg2};");
10454   verifyFormat("f(MyMap[{composite, key}]);");
10455   verifyFormat("class Class {\n"
10456                "  T member = {arg1, arg2};\n"
10457                "};");
10458   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
10459   verifyFormat("const struct A a = {.a = 1, .b = 2};");
10460   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
10461   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
10462   verifyFormat("int a = std::is_integral<int>{} + 0;");
10463 
10464   verifyFormat("int foo(int i) { return fo1{}(i); }");
10465   verifyFormat("int foo(int i) { return fo1{}(i); }");
10466   verifyFormat("auto i = decltype(x){};");
10467   verifyFormat("auto i = typeof(x){};");
10468   verifyFormat("auto i = _Atomic(x){};");
10469   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
10470   verifyFormat("Node n{1, Node{1000}, //\n"
10471                "       2};");
10472   verifyFormat("Aaaa aaaaaaa{\n"
10473                "    {\n"
10474                "        aaaa,\n"
10475                "    },\n"
10476                "};");
10477   verifyFormat("class C : public D {\n"
10478                "  SomeClass SC{2};\n"
10479                "};");
10480   verifyFormat("class C : public A {\n"
10481                "  class D : public B {\n"
10482                "    void f() { int i{2}; }\n"
10483                "  };\n"
10484                "};");
10485   verifyFormat("#define A {a, a},");
10486 
10487   // Avoid breaking between equal sign and opening brace
10488   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
10489   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
10490   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
10491                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
10492                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
10493                "     {\"ccccccccccccccccccccc\", 2}};",
10494                AvoidBreakingFirstArgument);
10495 
10496   // Binpacking only if there is no trailing comma
10497   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
10498                "                      cccccccccc, dddddddddd};",
10499                getLLVMStyleWithColumns(50));
10500   verifyFormat("const Aaaaaa aaaaa = {\n"
10501                "    aaaaaaaaaaa,\n"
10502                "    bbbbbbbbbbb,\n"
10503                "    ccccccccccc,\n"
10504                "    ddddddddddd,\n"
10505                "};",
10506                getLLVMStyleWithColumns(50));
10507 
10508   // Cases where distinguising braced lists and blocks is hard.
10509   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
10510   verifyFormat("void f() {\n"
10511                "  return; // comment\n"
10512                "}\n"
10513                "SomeType t;");
10514   verifyFormat("void f() {\n"
10515                "  if (a) {\n"
10516                "    f();\n"
10517                "  }\n"
10518                "}\n"
10519                "SomeType t;");
10520 
10521   // In combination with BinPackArguments = false.
10522   FormatStyle NoBinPacking = getLLVMStyle();
10523   NoBinPacking.BinPackArguments = false;
10524   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
10525                "                      bbbbb,\n"
10526                "                      ccccc,\n"
10527                "                      ddddd,\n"
10528                "                      eeeee,\n"
10529                "                      ffffff,\n"
10530                "                      ggggg,\n"
10531                "                      hhhhhh,\n"
10532                "                      iiiiii,\n"
10533                "                      jjjjjj,\n"
10534                "                      kkkkkk};",
10535                NoBinPacking);
10536   verifyFormat("const Aaaaaa aaaaa = {\n"
10537                "    aaaaa,\n"
10538                "    bbbbb,\n"
10539                "    ccccc,\n"
10540                "    ddddd,\n"
10541                "    eeeee,\n"
10542                "    ffffff,\n"
10543                "    ggggg,\n"
10544                "    hhhhhh,\n"
10545                "    iiiiii,\n"
10546                "    jjjjjj,\n"
10547                "    kkkkkk,\n"
10548                "};",
10549                NoBinPacking);
10550   verifyFormat(
10551       "const Aaaaaa aaaaa = {\n"
10552       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
10553       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
10554       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
10555       "};",
10556       NoBinPacking);
10557 
10558   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
10559   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
10560             "    CDDDP83848_BMCR_REGISTER,\n"
10561             "    CDDDP83848_BMSR_REGISTER,\n"
10562             "    CDDDP83848_RBR_REGISTER};",
10563             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
10564                    "                                CDDDP83848_BMSR_REGISTER,\n"
10565                    "                                CDDDP83848_RBR_REGISTER};",
10566                    NoBinPacking));
10567 
10568   // FIXME: The alignment of these trailing comments might be bad. Then again,
10569   // this might be utterly useless in real code.
10570   verifyFormat("Constructor::Constructor()\n"
10571                "    : some_value{         //\n"
10572                "                 aaaaaaa, //\n"
10573                "                 bbbbbbb} {}");
10574 
10575   // In braced lists, the first comment is always assumed to belong to the
10576   // first element. Thus, it can be moved to the next or previous line as
10577   // appropriate.
10578   EXPECT_EQ("function({// First element:\n"
10579             "          1,\n"
10580             "          // Second element:\n"
10581             "          2});",
10582             format("function({\n"
10583                    "    // First element:\n"
10584                    "    1,\n"
10585                    "    // Second element:\n"
10586                    "    2});"));
10587   EXPECT_EQ("std::vector<int> MyNumbers{\n"
10588             "    // First element:\n"
10589             "    1,\n"
10590             "    // Second element:\n"
10591             "    2};",
10592             format("std::vector<int> MyNumbers{// First element:\n"
10593                    "                           1,\n"
10594                    "                           // Second element:\n"
10595                    "                           2};",
10596                    getLLVMStyleWithColumns(30)));
10597   // A trailing comma should still lead to an enforced line break and no
10598   // binpacking.
10599   EXPECT_EQ("vector<int> SomeVector = {\n"
10600             "    // aaa\n"
10601             "    1,\n"
10602             "    2,\n"
10603             "};",
10604             format("vector<int> SomeVector = { // aaa\n"
10605                    "    1, 2, };"));
10606 
10607   // C++11 brace initializer list l-braces should not be treated any differently
10608   // when breaking before lambda bodies is enabled
10609   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
10610   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
10611   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
10612   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
10613   verifyFormat(
10614       "std::runtime_error{\n"
10615       "    \"Long string which will force a break onto the next line...\"};",
10616       BreakBeforeLambdaBody);
10617 
10618   FormatStyle ExtraSpaces = getLLVMStyle();
10619   ExtraSpaces.Cpp11BracedListStyle = false;
10620   ExtraSpaces.ColumnLimit = 75;
10621   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
10622   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
10623   verifyFormat("f({ 1, 2 });", ExtraSpaces);
10624   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
10625   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
10626   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
10627   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
10628   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
10629   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
10630   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
10631   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
10632   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
10633   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
10634   verifyFormat("class Class {\n"
10635                "  T member = { arg1, arg2 };\n"
10636                "};",
10637                ExtraSpaces);
10638   verifyFormat(
10639       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10640       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
10641       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
10642       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
10643       ExtraSpaces);
10644   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
10645   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
10646                ExtraSpaces);
10647   verifyFormat(
10648       "someFunction(OtherParam,\n"
10649       "             BracedList{ // comment 1 (Forcing interesting break)\n"
10650       "                         param1, param2,\n"
10651       "                         // comment 2\n"
10652       "                         param3, param4 });",
10653       ExtraSpaces);
10654   verifyFormat(
10655       "std::this_thread::sleep_for(\n"
10656       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
10657       ExtraSpaces);
10658   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
10659                "    aaaaaaa,\n"
10660                "    aaaaaaaaaa,\n"
10661                "    aaaaa,\n"
10662                "    aaaaaaaaaaaaaaa,\n"
10663                "    aaa,\n"
10664                "    aaaaaaaaaa,\n"
10665                "    a,\n"
10666                "    aaaaaaaaaaaaaaaaaaaaa,\n"
10667                "    aaaaaaaaaaaa,\n"
10668                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
10669                "    aaaaaaa,\n"
10670                "    a};");
10671   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
10672   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
10673   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
10674 
10675   // Avoid breaking between initializer/equal sign and opening brace
10676   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
10677   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
10678                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
10679                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
10680                "  { \"ccccccccccccccccccccc\", 2 }\n"
10681                "};",
10682                ExtraSpaces);
10683   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
10684                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
10685                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
10686                "  { \"ccccccccccccccccccccc\", 2 }\n"
10687                "};",
10688                ExtraSpaces);
10689 
10690   FormatStyle SpaceBeforeBrace = getLLVMStyle();
10691   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
10692   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
10693   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
10694 
10695   FormatStyle SpaceBetweenBraces = getLLVMStyle();
10696   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
10697   SpaceBetweenBraces.SpacesInParentheses = true;
10698   SpaceBetweenBraces.SpacesInSquareBrackets = true;
10699   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
10700   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
10701   verifyFormat("vector< int > x{ // comment 1\n"
10702                "                 1, 2, 3, 4 };",
10703                SpaceBetweenBraces);
10704   SpaceBetweenBraces.ColumnLimit = 20;
10705   EXPECT_EQ("vector< int > x{\n"
10706             "    1, 2, 3, 4 };",
10707             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
10708   SpaceBetweenBraces.ColumnLimit = 24;
10709   EXPECT_EQ("vector< int > x{ 1, 2,\n"
10710             "                 3, 4 };",
10711             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
10712   EXPECT_EQ("vector< int > x{\n"
10713             "    1,\n"
10714             "    2,\n"
10715             "    3,\n"
10716             "    4,\n"
10717             "};",
10718             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
10719   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
10720   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
10721   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
10722 }
10723 
10724 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
10725   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10726                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10727                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10728                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10729                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10730                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
10731   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
10732                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10733                "                 1, 22, 333, 4444, 55555, //\n"
10734                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10735                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
10736   verifyFormat(
10737       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
10738       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
10739       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
10740       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10741       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10742       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10743       "                 7777777};");
10744   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10745                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10746                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
10747   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10748                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10749                "    // Separating comment.\n"
10750                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
10751   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10752                "    // Leading comment\n"
10753                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10754                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
10755   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10756                "                 1, 1, 1, 1};",
10757                getLLVMStyleWithColumns(39));
10758   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10759                "                 1, 1, 1, 1};",
10760                getLLVMStyleWithColumns(38));
10761   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
10762                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
10763                getLLVMStyleWithColumns(43));
10764   verifyFormat(
10765       "static unsigned SomeValues[10][3] = {\n"
10766       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
10767       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
10768   verifyFormat("static auto fields = new vector<string>{\n"
10769                "    \"aaaaaaaaaaaaa\",\n"
10770                "    \"aaaaaaaaaaaaa\",\n"
10771                "    \"aaaaaaaaaaaa\",\n"
10772                "    \"aaaaaaaaaaaaaa\",\n"
10773                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
10774                "    \"aaaaaaaaaaaa\",\n"
10775                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
10776                "};");
10777   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
10778   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
10779                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
10780                "                 3, cccccccccccccccccccccc};",
10781                getLLVMStyleWithColumns(60));
10782 
10783   // Trailing commas.
10784   verifyFormat("vector<int> x = {\n"
10785                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
10786                "};",
10787                getLLVMStyleWithColumns(39));
10788   verifyFormat("vector<int> x = {\n"
10789                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
10790                "};",
10791                getLLVMStyleWithColumns(39));
10792   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10793                "                 1, 1, 1, 1,\n"
10794                "                 /**/ /**/};",
10795                getLLVMStyleWithColumns(39));
10796 
10797   // Trailing comment in the first line.
10798   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
10799                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
10800                "    111111111,  222222222,  3333333333,  444444444,  //\n"
10801                "    11111111,   22222222,   333333333,   44444444};");
10802   // Trailing comment in the last line.
10803   verifyFormat("int aaaaa[] = {\n"
10804                "    1, 2, 3, // comment\n"
10805                "    4, 5, 6  // comment\n"
10806                "};");
10807 
10808   // With nested lists, we should either format one item per line or all nested
10809   // lists one on line.
10810   // FIXME: For some nested lists, we can do better.
10811   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
10812                "        {aaaaaaaaaaaaaaaaaaa},\n"
10813                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
10814                "        {aaaaaaaaaaaaaaaaa}};",
10815                getLLVMStyleWithColumns(60));
10816   verifyFormat(
10817       "SomeStruct my_struct_array = {\n"
10818       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
10819       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
10820       "    {aaa, aaa},\n"
10821       "    {aaa, aaa},\n"
10822       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
10823       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
10824       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
10825 
10826   // No column layout should be used here.
10827   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
10828                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
10829 
10830   verifyNoCrash("a<,");
10831 
10832   // No braced initializer here.
10833   verifyFormat("void f() {\n"
10834                "  struct Dummy {};\n"
10835                "  f(v);\n"
10836                "}");
10837 
10838   // Long lists should be formatted in columns even if they are nested.
10839   verifyFormat(
10840       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10841       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10842       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10843       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10844       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10845       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
10846 
10847   // Allow "single-column" layout even if that violates the column limit. There
10848   // isn't going to be a better way.
10849   verifyFormat("std::vector<int> a = {\n"
10850                "    aaaaaaaa,\n"
10851                "    aaaaaaaa,\n"
10852                "    aaaaaaaa,\n"
10853                "    aaaaaaaa,\n"
10854                "    aaaaaaaaaa,\n"
10855                "    aaaaaaaa,\n"
10856                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
10857                getLLVMStyleWithColumns(30));
10858   verifyFormat("vector<int> aaaa = {\n"
10859                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10860                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10861                "    aaaaaa.aaaaaaa,\n"
10862                "    aaaaaa.aaaaaaa,\n"
10863                "    aaaaaa.aaaaaaa,\n"
10864                "    aaaaaa.aaaaaaa,\n"
10865                "};");
10866 
10867   // Don't create hanging lists.
10868   verifyFormat("someFunction(Param, {List1, List2,\n"
10869                "                     List3});",
10870                getLLVMStyleWithColumns(35));
10871   verifyFormat("someFunction(Param, Param,\n"
10872                "             {List1, List2,\n"
10873                "              List3});",
10874                getLLVMStyleWithColumns(35));
10875   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
10876                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
10877 }
10878 
10879 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
10880   FormatStyle DoNotMerge = getLLVMStyle();
10881   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10882 
10883   verifyFormat("void f() { return 42; }");
10884   verifyFormat("void f() {\n"
10885                "  return 42;\n"
10886                "}",
10887                DoNotMerge);
10888   verifyFormat("void f() {\n"
10889                "  // Comment\n"
10890                "}");
10891   verifyFormat("{\n"
10892                "#error {\n"
10893                "  int a;\n"
10894                "}");
10895   verifyFormat("{\n"
10896                "  int a;\n"
10897                "#error {\n"
10898                "}");
10899   verifyFormat("void f() {} // comment");
10900   verifyFormat("void f() { int a; } // comment");
10901   verifyFormat("void f() {\n"
10902                "} // comment",
10903                DoNotMerge);
10904   verifyFormat("void f() {\n"
10905                "  int a;\n"
10906                "} // comment",
10907                DoNotMerge);
10908   verifyFormat("void f() {\n"
10909                "} // comment",
10910                getLLVMStyleWithColumns(15));
10911 
10912   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
10913   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
10914 
10915   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
10916   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
10917   verifyFormat("class C {\n"
10918                "  C()\n"
10919                "      : iiiiiiii(nullptr),\n"
10920                "        kkkkkkk(nullptr),\n"
10921                "        mmmmmmm(nullptr),\n"
10922                "        nnnnnnn(nullptr) {}\n"
10923                "};",
10924                getGoogleStyle());
10925 
10926   FormatStyle NoColumnLimit = getLLVMStyle();
10927   NoColumnLimit.ColumnLimit = 0;
10928   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
10929   EXPECT_EQ("class C {\n"
10930             "  A() : b(0) {}\n"
10931             "};",
10932             format("class C{A():b(0){}};", NoColumnLimit));
10933   EXPECT_EQ("A()\n"
10934             "    : b(0) {\n"
10935             "}",
10936             format("A()\n:b(0)\n{\n}", NoColumnLimit));
10937 
10938   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
10939   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
10940       FormatStyle::SFS_None;
10941   EXPECT_EQ("A()\n"
10942             "    : b(0) {\n"
10943             "}",
10944             format("A():b(0){}", DoNotMergeNoColumnLimit));
10945   EXPECT_EQ("A()\n"
10946             "    : b(0) {\n"
10947             "}",
10948             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
10949 
10950   verifyFormat("#define A          \\\n"
10951                "  void f() {       \\\n"
10952                "    int i;         \\\n"
10953                "  }",
10954                getLLVMStyleWithColumns(20));
10955   verifyFormat("#define A           \\\n"
10956                "  void f() { int i; }",
10957                getLLVMStyleWithColumns(21));
10958   verifyFormat("#define A            \\\n"
10959                "  void f() {         \\\n"
10960                "    int i;           \\\n"
10961                "  }                  \\\n"
10962                "  int j;",
10963                getLLVMStyleWithColumns(22));
10964   verifyFormat("#define A             \\\n"
10965                "  void f() { int i; } \\\n"
10966                "  int j;",
10967                getLLVMStyleWithColumns(23));
10968 }
10969 
10970 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
10971   FormatStyle MergeEmptyOnly = getLLVMStyle();
10972   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
10973   verifyFormat("class C {\n"
10974                "  int f() {}\n"
10975                "};",
10976                MergeEmptyOnly);
10977   verifyFormat("class C {\n"
10978                "  int f() {\n"
10979                "    return 42;\n"
10980                "  }\n"
10981                "};",
10982                MergeEmptyOnly);
10983   verifyFormat("int f() {}", MergeEmptyOnly);
10984   verifyFormat("int f() {\n"
10985                "  return 42;\n"
10986                "}",
10987                MergeEmptyOnly);
10988 
10989   // Also verify behavior when BraceWrapping.AfterFunction = true
10990   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10991   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
10992   verifyFormat("int f() {}", MergeEmptyOnly);
10993   verifyFormat("class C {\n"
10994                "  int f() {}\n"
10995                "};",
10996                MergeEmptyOnly);
10997 }
10998 
10999 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
11000   FormatStyle MergeInlineOnly = getLLVMStyle();
11001   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
11002   verifyFormat("class C {\n"
11003                "  int f() { return 42; }\n"
11004                "};",
11005                MergeInlineOnly);
11006   verifyFormat("int f() {\n"
11007                "  return 42;\n"
11008                "}",
11009                MergeInlineOnly);
11010 
11011   // SFS_Inline implies SFS_Empty
11012   verifyFormat("class C {\n"
11013                "  int f() {}\n"
11014                "};",
11015                MergeInlineOnly);
11016   verifyFormat("int f() {}", MergeInlineOnly);
11017 
11018   // Also verify behavior when BraceWrapping.AfterFunction = true
11019   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
11020   MergeInlineOnly.BraceWrapping.AfterFunction = true;
11021   verifyFormat("class C {\n"
11022                "  int f() { return 42; }\n"
11023                "};",
11024                MergeInlineOnly);
11025   verifyFormat("int f()\n"
11026                "{\n"
11027                "  return 42;\n"
11028                "}",
11029                MergeInlineOnly);
11030 
11031   // SFS_Inline implies SFS_Empty
11032   verifyFormat("int f() {}", MergeInlineOnly);
11033   verifyFormat("class C {\n"
11034                "  int f() {}\n"
11035                "};",
11036                MergeInlineOnly);
11037 }
11038 
11039 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
11040   FormatStyle MergeInlineOnly = getLLVMStyle();
11041   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
11042       FormatStyle::SFS_InlineOnly;
11043   verifyFormat("class C {\n"
11044                "  int f() { return 42; }\n"
11045                "};",
11046                MergeInlineOnly);
11047   verifyFormat("int f() {\n"
11048                "  return 42;\n"
11049                "}",
11050                MergeInlineOnly);
11051 
11052   // SFS_InlineOnly does not imply SFS_Empty
11053   verifyFormat("class C {\n"
11054                "  int f() {}\n"
11055                "};",
11056                MergeInlineOnly);
11057   verifyFormat("int f() {\n"
11058                "}",
11059                MergeInlineOnly);
11060 
11061   // Also verify behavior when BraceWrapping.AfterFunction = true
11062   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
11063   MergeInlineOnly.BraceWrapping.AfterFunction = true;
11064   verifyFormat("class C {\n"
11065                "  int f() { return 42; }\n"
11066                "};",
11067                MergeInlineOnly);
11068   verifyFormat("int f()\n"
11069                "{\n"
11070                "  return 42;\n"
11071                "}",
11072                MergeInlineOnly);
11073 
11074   // SFS_InlineOnly does not imply SFS_Empty
11075   verifyFormat("int f()\n"
11076                "{\n"
11077                "}",
11078                MergeInlineOnly);
11079   verifyFormat("class C {\n"
11080                "  int f() {}\n"
11081                "};",
11082                MergeInlineOnly);
11083 }
11084 
11085 TEST_F(FormatTest, SplitEmptyFunction) {
11086   FormatStyle Style = getLLVMStyle();
11087   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
11088   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
11089   Style.BraceWrapping.AfterFunction = true;
11090   Style.BraceWrapping.SplitEmptyFunction = false;
11091   Style.ColumnLimit = 40;
11092 
11093   verifyFormat("int f()\n"
11094                "{}",
11095                Style);
11096   verifyFormat("int f()\n"
11097                "{\n"
11098                "  return 42;\n"
11099                "}",
11100                Style);
11101   verifyFormat("int f()\n"
11102                "{\n"
11103                "  // some comment\n"
11104                "}",
11105                Style);
11106 
11107   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
11108   verifyFormat("int f() {}", Style);
11109   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
11110                "{}",
11111                Style);
11112   verifyFormat("int f()\n"
11113                "{\n"
11114                "  return 0;\n"
11115                "}",
11116                Style);
11117 
11118   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
11119   verifyFormat("class Foo {\n"
11120                "  int f() {}\n"
11121                "};\n",
11122                Style);
11123   verifyFormat("class Foo {\n"
11124                "  int f() { return 0; }\n"
11125                "};\n",
11126                Style);
11127   verifyFormat("class Foo {\n"
11128                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
11129                "  {}\n"
11130                "};\n",
11131                Style);
11132   verifyFormat("class Foo {\n"
11133                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
11134                "  {\n"
11135                "    return 0;\n"
11136                "  }\n"
11137                "};\n",
11138                Style);
11139 
11140   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
11141   verifyFormat("int f() {}", Style);
11142   verifyFormat("int f() { return 0; }", Style);
11143   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
11144                "{}",
11145                Style);
11146   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
11147                "{\n"
11148                "  return 0;\n"
11149                "}",
11150                Style);
11151 }
11152 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
11153   FormatStyle Style = getLLVMStyle();
11154   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
11155   verifyFormat("#ifdef A\n"
11156                "int f() {}\n"
11157                "#else\n"
11158                "int g() {}\n"
11159                "#endif",
11160                Style);
11161 }
11162 
11163 TEST_F(FormatTest, SplitEmptyClass) {
11164   FormatStyle Style = getLLVMStyle();
11165   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
11166   Style.BraceWrapping.AfterClass = true;
11167   Style.BraceWrapping.SplitEmptyRecord = false;
11168 
11169   verifyFormat("class Foo\n"
11170                "{};",
11171                Style);
11172   verifyFormat("/* something */ class Foo\n"
11173                "{};",
11174                Style);
11175   verifyFormat("template <typename X> class Foo\n"
11176                "{};",
11177                Style);
11178   verifyFormat("class Foo\n"
11179                "{\n"
11180                "  Foo();\n"
11181                "};",
11182                Style);
11183   verifyFormat("typedef class Foo\n"
11184                "{\n"
11185                "} Foo_t;",
11186                Style);
11187 
11188   Style.BraceWrapping.SplitEmptyRecord = true;
11189   Style.BraceWrapping.AfterStruct = true;
11190   verifyFormat("class rep\n"
11191                "{\n"
11192                "};",
11193                Style);
11194   verifyFormat("struct rep\n"
11195                "{\n"
11196                "};",
11197                Style);
11198   verifyFormat("template <typename T> class rep\n"
11199                "{\n"
11200                "};",
11201                Style);
11202   verifyFormat("template <typename T> struct rep\n"
11203                "{\n"
11204                "};",
11205                Style);
11206   verifyFormat("class rep\n"
11207                "{\n"
11208                "  int x;\n"
11209                "};",
11210                Style);
11211   verifyFormat("struct rep\n"
11212                "{\n"
11213                "  int x;\n"
11214                "};",
11215                Style);
11216   verifyFormat("template <typename T> class rep\n"
11217                "{\n"
11218                "  int x;\n"
11219                "};",
11220                Style);
11221   verifyFormat("template <typename T> struct rep\n"
11222                "{\n"
11223                "  int x;\n"
11224                "};",
11225                Style);
11226   verifyFormat("template <typename T> class rep // Foo\n"
11227                "{\n"
11228                "  int x;\n"
11229                "};",
11230                Style);
11231   verifyFormat("template <typename T> struct rep // Bar\n"
11232                "{\n"
11233                "  int x;\n"
11234                "};",
11235                Style);
11236 
11237   verifyFormat("template <typename T> class rep<T>\n"
11238                "{\n"
11239                "  int x;\n"
11240                "};",
11241                Style);
11242 
11243   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
11244                "{\n"
11245                "  int x;\n"
11246                "};",
11247                Style);
11248   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
11249                "{\n"
11250                "};",
11251                Style);
11252 
11253   verifyFormat("#include \"stdint.h\"\n"
11254                "namespace rep {}",
11255                Style);
11256   verifyFormat("#include <stdint.h>\n"
11257                "namespace rep {}",
11258                Style);
11259   verifyFormat("#include <stdint.h>\n"
11260                "namespace rep {}",
11261                "#include <stdint.h>\n"
11262                "namespace rep {\n"
11263                "\n"
11264                "\n"
11265                "}",
11266                Style);
11267 }
11268 
11269 TEST_F(FormatTest, SplitEmptyStruct) {
11270   FormatStyle Style = getLLVMStyle();
11271   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
11272   Style.BraceWrapping.AfterStruct = true;
11273   Style.BraceWrapping.SplitEmptyRecord = false;
11274 
11275   verifyFormat("struct Foo\n"
11276                "{};",
11277                Style);
11278   verifyFormat("/* something */ struct Foo\n"
11279                "{};",
11280                Style);
11281   verifyFormat("template <typename X> struct Foo\n"
11282                "{};",
11283                Style);
11284   verifyFormat("struct Foo\n"
11285                "{\n"
11286                "  Foo();\n"
11287                "};",
11288                Style);
11289   verifyFormat("typedef struct Foo\n"
11290                "{\n"
11291                "} Foo_t;",
11292                Style);
11293   // typedef struct Bar {} Bar_t;
11294 }
11295 
11296 TEST_F(FormatTest, SplitEmptyUnion) {
11297   FormatStyle Style = getLLVMStyle();
11298   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
11299   Style.BraceWrapping.AfterUnion = true;
11300   Style.BraceWrapping.SplitEmptyRecord = false;
11301 
11302   verifyFormat("union Foo\n"
11303                "{};",
11304                Style);
11305   verifyFormat("/* something */ union Foo\n"
11306                "{};",
11307                Style);
11308   verifyFormat("union Foo\n"
11309                "{\n"
11310                "  A,\n"
11311                "};",
11312                Style);
11313   verifyFormat("typedef union Foo\n"
11314                "{\n"
11315                "} Foo_t;",
11316                Style);
11317 }
11318 
11319 TEST_F(FormatTest, SplitEmptyNamespace) {
11320   FormatStyle Style = getLLVMStyle();
11321   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
11322   Style.BraceWrapping.AfterNamespace = true;
11323   Style.BraceWrapping.SplitEmptyNamespace = false;
11324 
11325   verifyFormat("namespace Foo\n"
11326                "{};",
11327                Style);
11328   verifyFormat("/* something */ namespace Foo\n"
11329                "{};",
11330                Style);
11331   verifyFormat("inline namespace Foo\n"
11332                "{};",
11333                Style);
11334   verifyFormat("/* something */ inline namespace Foo\n"
11335                "{};",
11336                Style);
11337   verifyFormat("export namespace Foo\n"
11338                "{};",
11339                Style);
11340   verifyFormat("namespace Foo\n"
11341                "{\n"
11342                "void Bar();\n"
11343                "};",
11344                Style);
11345 }
11346 
11347 TEST_F(FormatTest, NeverMergeShortRecords) {
11348   FormatStyle Style = getLLVMStyle();
11349 
11350   verifyFormat("class Foo {\n"
11351                "  Foo();\n"
11352                "};",
11353                Style);
11354   verifyFormat("typedef class Foo {\n"
11355                "  Foo();\n"
11356                "} Foo_t;",
11357                Style);
11358   verifyFormat("struct Foo {\n"
11359                "  Foo();\n"
11360                "};",
11361                Style);
11362   verifyFormat("typedef struct Foo {\n"
11363                "  Foo();\n"
11364                "} Foo_t;",
11365                Style);
11366   verifyFormat("union Foo {\n"
11367                "  A,\n"
11368                "};",
11369                Style);
11370   verifyFormat("typedef union Foo {\n"
11371                "  A,\n"
11372                "} Foo_t;",
11373                Style);
11374   verifyFormat("namespace Foo {\n"
11375                "void Bar();\n"
11376                "};",
11377                Style);
11378 
11379   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
11380   Style.BraceWrapping.AfterClass = true;
11381   Style.BraceWrapping.AfterStruct = true;
11382   Style.BraceWrapping.AfterUnion = true;
11383   Style.BraceWrapping.AfterNamespace = true;
11384   verifyFormat("class Foo\n"
11385                "{\n"
11386                "  Foo();\n"
11387                "};",
11388                Style);
11389   verifyFormat("typedef class Foo\n"
11390                "{\n"
11391                "  Foo();\n"
11392                "} Foo_t;",
11393                Style);
11394   verifyFormat("struct Foo\n"
11395                "{\n"
11396                "  Foo();\n"
11397                "};",
11398                Style);
11399   verifyFormat("typedef struct Foo\n"
11400                "{\n"
11401                "  Foo();\n"
11402                "} Foo_t;",
11403                Style);
11404   verifyFormat("union Foo\n"
11405                "{\n"
11406                "  A,\n"
11407                "};",
11408                Style);
11409   verifyFormat("typedef union Foo\n"
11410                "{\n"
11411                "  A,\n"
11412                "} Foo_t;",
11413                Style);
11414   verifyFormat("namespace Foo\n"
11415                "{\n"
11416                "void Bar();\n"
11417                "};",
11418                Style);
11419 }
11420 
11421 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
11422   // Elaborate type variable declarations.
11423   verifyFormat("struct foo a = {bar};\nint n;");
11424   verifyFormat("class foo a = {bar};\nint n;");
11425   verifyFormat("union foo a = {bar};\nint n;");
11426 
11427   // Elaborate types inside function definitions.
11428   verifyFormat("struct foo f() {}\nint n;");
11429   verifyFormat("class foo f() {}\nint n;");
11430   verifyFormat("union foo f() {}\nint n;");
11431 
11432   // Templates.
11433   verifyFormat("template <class X> void f() {}\nint n;");
11434   verifyFormat("template <struct X> void f() {}\nint n;");
11435   verifyFormat("template <union X> void f() {}\nint n;");
11436 
11437   // Actual definitions...
11438   verifyFormat("struct {\n} n;");
11439   verifyFormat(
11440       "template <template <class T, class Y>, class Z> class X {\n} n;");
11441   verifyFormat("union Z {\n  int n;\n} x;");
11442   verifyFormat("class MACRO Z {\n} n;");
11443   verifyFormat("class MACRO(X) Z {\n} n;");
11444   verifyFormat("class __attribute__(X) Z {\n} n;");
11445   verifyFormat("class __declspec(X) Z {\n} n;");
11446   verifyFormat("class A##B##C {\n} n;");
11447   verifyFormat("class alignas(16) Z {\n} n;");
11448   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
11449   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
11450 
11451   // Redefinition from nested context:
11452   verifyFormat("class A::B::C {\n} n;");
11453 
11454   // Template definitions.
11455   verifyFormat(
11456       "template <typename F>\n"
11457       "Matcher(const Matcher<F> &Other,\n"
11458       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
11459       "                             !is_same<F, T>::value>::type * = 0)\n"
11460       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
11461 
11462   // FIXME: This is still incorrectly handled at the formatter side.
11463   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
11464   verifyFormat("int i = SomeFunction(a<b, a> b);");
11465 
11466   // FIXME:
11467   // This now gets parsed incorrectly as class definition.
11468   // verifyFormat("class A<int> f() {\n}\nint n;");
11469 
11470   // Elaborate types where incorrectly parsing the structural element would
11471   // break the indent.
11472   verifyFormat("if (true)\n"
11473                "  class X x;\n"
11474                "else\n"
11475                "  f();\n");
11476 
11477   // This is simply incomplete. Formatting is not important, but must not crash.
11478   verifyFormat("class A:");
11479 }
11480 
11481 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
11482   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
11483             format("#error Leave     all         white!!!!! space* alone!\n"));
11484   EXPECT_EQ(
11485       "#warning Leave     all         white!!!!! space* alone!\n",
11486       format("#warning Leave     all         white!!!!! space* alone!\n"));
11487   EXPECT_EQ("#error 1", format("  #  error   1"));
11488   EXPECT_EQ("#warning 1", format("  #  warning 1"));
11489 }
11490 
11491 TEST_F(FormatTest, FormatHashIfExpressions) {
11492   verifyFormat("#if AAAA && BBBB");
11493   verifyFormat("#if (AAAA && BBBB)");
11494   verifyFormat("#elif (AAAA && BBBB)");
11495   // FIXME: Come up with a better indentation for #elif.
11496   verifyFormat(
11497       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
11498       "    defined(BBBBBBBB)\n"
11499       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
11500       "    defined(BBBBBBBB)\n"
11501       "#endif",
11502       getLLVMStyleWithColumns(65));
11503 }
11504 
11505 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
11506   FormatStyle AllowsMergedIf = getGoogleStyle();
11507   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
11508       FormatStyle::SIS_WithoutElse;
11509   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
11510   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
11511   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
11512   EXPECT_EQ("if (true) return 42;",
11513             format("if (true)\nreturn 42;", AllowsMergedIf));
11514   FormatStyle ShortMergedIf = AllowsMergedIf;
11515   ShortMergedIf.ColumnLimit = 25;
11516   verifyFormat("#define A \\\n"
11517                "  if (true) return 42;",
11518                ShortMergedIf);
11519   verifyFormat("#define A \\\n"
11520                "  f();    \\\n"
11521                "  if (true)\n"
11522                "#define B",
11523                ShortMergedIf);
11524   verifyFormat("#define A \\\n"
11525                "  f();    \\\n"
11526                "  if (true)\n"
11527                "g();",
11528                ShortMergedIf);
11529   verifyFormat("{\n"
11530                "#ifdef A\n"
11531                "  // Comment\n"
11532                "  if (true) continue;\n"
11533                "#endif\n"
11534                "  // Comment\n"
11535                "  if (true) continue;\n"
11536                "}",
11537                ShortMergedIf);
11538   ShortMergedIf.ColumnLimit = 33;
11539   verifyFormat("#define A \\\n"
11540                "  if constexpr (true) return 42;",
11541                ShortMergedIf);
11542   verifyFormat("#define A \\\n"
11543                "  if CONSTEXPR (true) return 42;",
11544                ShortMergedIf);
11545   ShortMergedIf.ColumnLimit = 29;
11546   verifyFormat("#define A                   \\\n"
11547                "  if (aaaaaaaaaa) return 1; \\\n"
11548                "  return 2;",
11549                ShortMergedIf);
11550   ShortMergedIf.ColumnLimit = 28;
11551   verifyFormat("#define A         \\\n"
11552                "  if (aaaaaaaaaa) \\\n"
11553                "    return 1;     \\\n"
11554                "  return 2;",
11555                ShortMergedIf);
11556   verifyFormat("#define A                \\\n"
11557                "  if constexpr (aaaaaaa) \\\n"
11558                "    return 1;            \\\n"
11559                "  return 2;",
11560                ShortMergedIf);
11561   verifyFormat("#define A                \\\n"
11562                "  if CONSTEXPR (aaaaaaa) \\\n"
11563                "    return 1;            \\\n"
11564                "  return 2;",
11565                ShortMergedIf);
11566 }
11567 
11568 TEST_F(FormatTest, FormatStarDependingOnContext) {
11569   verifyFormat("void f(int *a);");
11570   verifyFormat("void f() { f(fint * b); }");
11571   verifyFormat("class A {\n  void f(int *a);\n};");
11572   verifyFormat("class A {\n  int *a;\n};");
11573   verifyFormat("namespace a {\n"
11574                "namespace b {\n"
11575                "class A {\n"
11576                "  void f() {}\n"
11577                "  int *a;\n"
11578                "};\n"
11579                "} // namespace b\n"
11580                "} // namespace a");
11581 }
11582 
11583 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
11584   verifyFormat("while");
11585   verifyFormat("operator");
11586 }
11587 
11588 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
11589   // This code would be painfully slow to format if we didn't skip it.
11590   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
11591                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11592                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11593                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11594                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11595                    "A(1, 1)\n"
11596                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
11597                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11598                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11599                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11600                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11601                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11602                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11603                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11604                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11605                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
11606   // Deeply nested part is untouched, rest is formatted.
11607   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
11608             format(std::string("int    i;\n") + Code + "int    j;\n",
11609                    getLLVMStyle(), SC_ExpectIncomplete));
11610 }
11611 
11612 //===----------------------------------------------------------------------===//
11613 // Objective-C tests.
11614 //===----------------------------------------------------------------------===//
11615 
11616 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
11617   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
11618   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
11619             format("-(NSUInteger)indexOfObject:(id)anObject;"));
11620   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
11621   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
11622   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
11623             format("-(NSInteger)Method3:(id)anObject;"));
11624   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
11625             format("-(NSInteger)Method4:(id)anObject;"));
11626   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
11627             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
11628   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
11629             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
11630   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
11631             "forAllCells:(BOOL)flag;",
11632             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
11633                    "forAllCells:(BOOL)flag;"));
11634 
11635   // Very long objectiveC method declaration.
11636   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
11637                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
11638   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
11639                "                    inRange:(NSRange)range\n"
11640                "                   outRange:(NSRange)out_range\n"
11641                "                  outRange1:(NSRange)out_range1\n"
11642                "                  outRange2:(NSRange)out_range2\n"
11643                "                  outRange3:(NSRange)out_range3\n"
11644                "                  outRange4:(NSRange)out_range4\n"
11645                "                  outRange5:(NSRange)out_range5\n"
11646                "                  outRange6:(NSRange)out_range6\n"
11647                "                  outRange7:(NSRange)out_range7\n"
11648                "                  outRange8:(NSRange)out_range8\n"
11649                "                  outRange9:(NSRange)out_range9;");
11650 
11651   // When the function name has to be wrapped.
11652   FormatStyle Style = getLLVMStyle();
11653   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
11654   // and always indents instead.
11655   Style.IndentWrappedFunctionNames = false;
11656   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
11657                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
11658                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
11659                "}",
11660                Style);
11661   Style.IndentWrappedFunctionNames = true;
11662   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
11663                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
11664                "               anotherName:(NSString)dddddddddddddd {\n"
11665                "}",
11666                Style);
11667 
11668   verifyFormat("- (int)sum:(vector<int>)numbers;");
11669   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
11670   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
11671   // protocol lists (but not for template classes):
11672   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
11673 
11674   verifyFormat("- (int (*)())foo:(int (*)())f;");
11675   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
11676 
11677   // If there's no return type (very rare in practice!), LLVM and Google style
11678   // agree.
11679   verifyFormat("- foo;");
11680   verifyFormat("- foo:(int)f;");
11681   verifyGoogleFormat("- foo:(int)foo;");
11682 }
11683 
11684 TEST_F(FormatTest, BreaksStringLiterals) {
11685   EXPECT_EQ("\"some text \"\n"
11686             "\"other\";",
11687             format("\"some text other\";", getLLVMStyleWithColumns(12)));
11688   EXPECT_EQ("\"some text \"\n"
11689             "\"other\";",
11690             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
11691   EXPECT_EQ(
11692       "#define A  \\\n"
11693       "  \"some \"  \\\n"
11694       "  \"text \"  \\\n"
11695       "  \"other\";",
11696       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
11697   EXPECT_EQ(
11698       "#define A  \\\n"
11699       "  \"so \"    \\\n"
11700       "  \"text \"  \\\n"
11701       "  \"other\";",
11702       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
11703 
11704   EXPECT_EQ("\"some text\"",
11705             format("\"some text\"", getLLVMStyleWithColumns(1)));
11706   EXPECT_EQ("\"some text\"",
11707             format("\"some text\"", getLLVMStyleWithColumns(11)));
11708   EXPECT_EQ("\"some \"\n"
11709             "\"text\"",
11710             format("\"some text\"", getLLVMStyleWithColumns(10)));
11711   EXPECT_EQ("\"some \"\n"
11712             "\"text\"",
11713             format("\"some text\"", getLLVMStyleWithColumns(7)));
11714   EXPECT_EQ("\"some\"\n"
11715             "\" tex\"\n"
11716             "\"t\"",
11717             format("\"some text\"", getLLVMStyleWithColumns(6)));
11718   EXPECT_EQ("\"some\"\n"
11719             "\" tex\"\n"
11720             "\" and\"",
11721             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
11722   EXPECT_EQ("\"some\"\n"
11723             "\"/tex\"\n"
11724             "\"/and\"",
11725             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
11726 
11727   EXPECT_EQ("variable =\n"
11728             "    \"long string \"\n"
11729             "    \"literal\";",
11730             format("variable = \"long string literal\";",
11731                    getLLVMStyleWithColumns(20)));
11732 
11733   EXPECT_EQ("variable = f(\n"
11734             "    \"long string \"\n"
11735             "    \"literal\",\n"
11736             "    short,\n"
11737             "    loooooooooooooooooooong);",
11738             format("variable = f(\"long string literal\", short, "
11739                    "loooooooooooooooooooong);",
11740                    getLLVMStyleWithColumns(20)));
11741 
11742   EXPECT_EQ(
11743       "f(g(\"long string \"\n"
11744       "    \"literal\"),\n"
11745       "  b);",
11746       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
11747   EXPECT_EQ("f(g(\"long string \"\n"
11748             "    \"literal\",\n"
11749             "    a),\n"
11750             "  b);",
11751             format("f(g(\"long string literal\", a), b);",
11752                    getLLVMStyleWithColumns(20)));
11753   EXPECT_EQ(
11754       "f(\"one two\".split(\n"
11755       "    variable));",
11756       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
11757   EXPECT_EQ("f(\"one two three four five six \"\n"
11758             "  \"seven\".split(\n"
11759             "      really_looooong_variable));",
11760             format("f(\"one two three four five six seven\"."
11761                    "split(really_looooong_variable));",
11762                    getLLVMStyleWithColumns(33)));
11763 
11764   EXPECT_EQ("f(\"some \"\n"
11765             "  \"text\",\n"
11766             "  other);",
11767             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
11768 
11769   // Only break as a last resort.
11770   verifyFormat(
11771       "aaaaaaaaaaaaaaaaaaaa(\n"
11772       "    aaaaaaaaaaaaaaaaaaaa,\n"
11773       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
11774 
11775   EXPECT_EQ("\"splitmea\"\n"
11776             "\"trandomp\"\n"
11777             "\"oint\"",
11778             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
11779 
11780   EXPECT_EQ("\"split/\"\n"
11781             "\"pathat/\"\n"
11782             "\"slashes\"",
11783             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
11784 
11785   EXPECT_EQ("\"split/\"\n"
11786             "\"pathat/\"\n"
11787             "\"slashes\"",
11788             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
11789   EXPECT_EQ("\"split at \"\n"
11790             "\"spaces/at/\"\n"
11791             "\"slashes.at.any$\"\n"
11792             "\"non-alphanumeric%\"\n"
11793             "\"1111111111characte\"\n"
11794             "\"rs\"",
11795             format("\"split at "
11796                    "spaces/at/"
11797                    "slashes.at."
11798                    "any$non-"
11799                    "alphanumeric%"
11800                    "1111111111characte"
11801                    "rs\"",
11802                    getLLVMStyleWithColumns(20)));
11803 
11804   // Verify that splitting the strings understands
11805   // Style::AlwaysBreakBeforeMultilineStrings.
11806   EXPECT_EQ("aaaaaaaaaaaa(\n"
11807             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
11808             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
11809             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
11810                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
11811                    "aaaaaaaaaaaaaaaaaaaaaa\");",
11812                    getGoogleStyle()));
11813   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11814             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
11815             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
11816                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
11817                    "aaaaaaaaaaaaaaaaaaaaaa\";",
11818                    getGoogleStyle()));
11819   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11820             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
11821             format("llvm::outs() << "
11822                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
11823                    "aaaaaaaaaaaaaaaaaaa\";"));
11824   EXPECT_EQ("ffff(\n"
11825             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11826             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
11827             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
11828                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
11829                    getGoogleStyle()));
11830 
11831   FormatStyle Style = getLLVMStyleWithColumns(12);
11832   Style.BreakStringLiterals = false;
11833   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
11834 
11835   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
11836   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11837   EXPECT_EQ("#define A \\\n"
11838             "  \"some \" \\\n"
11839             "  \"text \" \\\n"
11840             "  \"other\";",
11841             format("#define A \"some text other\";", AlignLeft));
11842 }
11843 
11844 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
11845   EXPECT_EQ("C a = \"some more \"\n"
11846             "      \"text\";",
11847             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
11848 }
11849 
11850 TEST_F(FormatTest, FullyRemoveEmptyLines) {
11851   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
11852   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11853   EXPECT_EQ("int i = a(b());",
11854             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
11855 }
11856 
11857 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
11858   EXPECT_EQ(
11859       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
11860       "(\n"
11861       "    \"x\t\");",
11862       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
11863              "aaaaaaa("
11864              "\"x\t\");"));
11865 }
11866 
11867 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
11868   EXPECT_EQ(
11869       "u8\"utf8 string \"\n"
11870       "u8\"literal\";",
11871       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
11872   EXPECT_EQ(
11873       "u\"utf16 string \"\n"
11874       "u\"literal\";",
11875       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
11876   EXPECT_EQ(
11877       "U\"utf32 string \"\n"
11878       "U\"literal\";",
11879       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
11880   EXPECT_EQ("L\"wide string \"\n"
11881             "L\"literal\";",
11882             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
11883   EXPECT_EQ("@\"NSString \"\n"
11884             "@\"literal\";",
11885             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
11886   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
11887 
11888   // This input makes clang-format try to split the incomplete unicode escape
11889   // sequence, which used to lead to a crasher.
11890   verifyNoCrash(
11891       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
11892       getLLVMStyleWithColumns(60));
11893 }
11894 
11895 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
11896   FormatStyle Style = getGoogleStyleWithColumns(15);
11897   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
11898   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
11899   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
11900   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
11901   EXPECT_EQ("u8R\"x(raw literal)x\";",
11902             format("u8R\"x(raw literal)x\";", Style));
11903 }
11904 
11905 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
11906   FormatStyle Style = getLLVMStyleWithColumns(20);
11907   EXPECT_EQ(
11908       "_T(\"aaaaaaaaaaaaaa\")\n"
11909       "_T(\"aaaaaaaaaaaaaa\")\n"
11910       "_T(\"aaaaaaaaaaaa\")",
11911       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
11912   EXPECT_EQ("f(x,\n"
11913             "  _T(\"aaaaaaaaaaaa\")\n"
11914             "  _T(\"aaa\"),\n"
11915             "  z);",
11916             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
11917 
11918   // FIXME: Handle embedded spaces in one iteration.
11919   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
11920   //            "_T(\"aaaaaaaaaaaaa\")\n"
11921   //            "_T(\"aaaaaaaaaaaaa\")\n"
11922   //            "_T(\"a\")",
11923   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
11924   //                   getLLVMStyleWithColumns(20)));
11925   EXPECT_EQ(
11926       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
11927       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
11928   EXPECT_EQ("f(\n"
11929             "#if !TEST\n"
11930             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
11931             "#endif\n"
11932             ");",
11933             format("f(\n"
11934                    "#if !TEST\n"
11935                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
11936                    "#endif\n"
11937                    ");"));
11938   EXPECT_EQ("f(\n"
11939             "\n"
11940             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
11941             format("f(\n"
11942                    "\n"
11943                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
11944 }
11945 
11946 TEST_F(FormatTest, BreaksStringLiteralOperands) {
11947   // In a function call with two operands, the second can be broken with no line
11948   // break before it.
11949   EXPECT_EQ(
11950       "func(a, \"long long \"\n"
11951       "        \"long long\");",
11952       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
11953   // In a function call with three operands, the second must be broken with a
11954   // line break before it.
11955   EXPECT_EQ("func(a,\n"
11956             "     \"long long long \"\n"
11957             "     \"long\",\n"
11958             "     c);",
11959             format("func(a, \"long long long long\", c);",
11960                    getLLVMStyleWithColumns(24)));
11961   // In a function call with three operands, the third must be broken with a
11962   // line break before it.
11963   EXPECT_EQ("func(a, b,\n"
11964             "     \"long long long \"\n"
11965             "     \"long\");",
11966             format("func(a, b, \"long long long long\");",
11967                    getLLVMStyleWithColumns(24)));
11968   // In a function call with three operands, both the second and the third must
11969   // be broken with a line break before them.
11970   EXPECT_EQ("func(a,\n"
11971             "     \"long long long \"\n"
11972             "     \"long\",\n"
11973             "     \"long long long \"\n"
11974             "     \"long\");",
11975             format("func(a, \"long long long long\", \"long long long long\");",
11976                    getLLVMStyleWithColumns(24)));
11977   // In a chain of << with two operands, the second can be broken with no line
11978   // break before it.
11979   EXPECT_EQ("a << \"line line \"\n"
11980             "     \"line\";",
11981             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
11982   // In a chain of << with three operands, the second can be broken with no line
11983   // break before it.
11984   EXPECT_EQ(
11985       "abcde << \"line \"\n"
11986       "         \"line line\"\n"
11987       "      << c;",
11988       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
11989   // In a chain of << with three operands, the third must be broken with a line
11990   // break before it.
11991   EXPECT_EQ(
11992       "a << b\n"
11993       "  << \"line line \"\n"
11994       "     \"line\";",
11995       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
11996   // In a chain of << with three operands, the second can be broken with no line
11997   // break before it and the third must be broken with a line break before it.
11998   EXPECT_EQ("abcd << \"line line \"\n"
11999             "        \"line\"\n"
12000             "     << \"line line \"\n"
12001             "        \"line\";",
12002             format("abcd << \"line line line\" << \"line line line\";",
12003                    getLLVMStyleWithColumns(20)));
12004   // In a chain of binary operators with two operands, the second can be broken
12005   // with no line break before it.
12006   EXPECT_EQ(
12007       "abcd + \"line line \"\n"
12008       "       \"line line\";",
12009       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
12010   // In a chain of binary operators with three operands, the second must be
12011   // broken with a line break before it.
12012   EXPECT_EQ("abcd +\n"
12013             "    \"line line \"\n"
12014             "    \"line line\" +\n"
12015             "    e;",
12016             format("abcd + \"line line line line\" + e;",
12017                    getLLVMStyleWithColumns(20)));
12018   // In a function call with two operands, with AlignAfterOpenBracket enabled,
12019   // the first must be broken with a line break before it.
12020   FormatStyle Style = getLLVMStyleWithColumns(25);
12021   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12022   EXPECT_EQ("someFunction(\n"
12023             "    \"long long long \"\n"
12024             "    \"long\",\n"
12025             "    a);",
12026             format("someFunction(\"long long long long\", a);", Style));
12027 }
12028 
12029 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
12030   EXPECT_EQ(
12031       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12032       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12033       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
12034       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12035              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12036              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
12037 }
12038 
12039 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
12040   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
12041             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
12042   EXPECT_EQ("fffffffffff(g(R\"x(\n"
12043             "multiline raw string literal xxxxxxxxxxxxxx\n"
12044             ")x\",\n"
12045             "              a),\n"
12046             "            b);",
12047             format("fffffffffff(g(R\"x(\n"
12048                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12049                    ")x\", a), b);",
12050                    getGoogleStyleWithColumns(20)));
12051   EXPECT_EQ("fffffffffff(\n"
12052             "    g(R\"x(qqq\n"
12053             "multiline raw string literal xxxxxxxxxxxxxx\n"
12054             ")x\",\n"
12055             "      a),\n"
12056             "    b);",
12057             format("fffffffffff(g(R\"x(qqq\n"
12058                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12059                    ")x\", a), b);",
12060                    getGoogleStyleWithColumns(20)));
12061 
12062   EXPECT_EQ("fffffffffff(R\"x(\n"
12063             "multiline raw string literal xxxxxxxxxxxxxx\n"
12064             ")x\");",
12065             format("fffffffffff(R\"x(\n"
12066                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12067                    ")x\");",
12068                    getGoogleStyleWithColumns(20)));
12069   EXPECT_EQ("fffffffffff(R\"x(\n"
12070             "multiline raw string literal xxxxxxxxxxxxxx\n"
12071             ")x\" + bbbbbb);",
12072             format("fffffffffff(R\"x(\n"
12073                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12074                    ")x\" +   bbbbbb);",
12075                    getGoogleStyleWithColumns(20)));
12076   EXPECT_EQ("fffffffffff(\n"
12077             "    R\"x(\n"
12078             "multiline raw string literal xxxxxxxxxxxxxx\n"
12079             ")x\" +\n"
12080             "    bbbbbb);",
12081             format("fffffffffff(\n"
12082                    " R\"x(\n"
12083                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12084                    ")x\" + bbbbbb);",
12085                    getGoogleStyleWithColumns(20)));
12086   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
12087             format("fffffffffff(\n"
12088                    " R\"(single line raw string)\" + bbbbbb);"));
12089 }
12090 
12091 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
12092   verifyFormat("string a = \"unterminated;");
12093   EXPECT_EQ("function(\"unterminated,\n"
12094             "         OtherParameter);",
12095             format("function(  \"unterminated,\n"
12096                    "    OtherParameter);"));
12097 }
12098 
12099 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
12100   FormatStyle Style = getLLVMStyle();
12101   Style.Standard = FormatStyle::LS_Cpp03;
12102   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
12103             format("#define x(_a) printf(\"foo\"_a);", Style));
12104 }
12105 
12106 TEST_F(FormatTest, CppLexVersion) {
12107   FormatStyle Style = getLLVMStyle();
12108   // Formatting of x * y differs if x is a type.
12109   verifyFormat("void foo() { MACRO(a * b); }", Style);
12110   verifyFormat("void foo() { MACRO(int *b); }", Style);
12111 
12112   // LLVM style uses latest lexer.
12113   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
12114   Style.Standard = FormatStyle::LS_Cpp17;
12115   // But in c++17, char8_t isn't a keyword.
12116   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
12117 }
12118 
12119 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
12120 
12121 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
12122   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
12123             "             \"ddeeefff\");",
12124             format("someFunction(\"aaabbbcccdddeeefff\");",
12125                    getLLVMStyleWithColumns(25)));
12126   EXPECT_EQ("someFunction1234567890(\n"
12127             "    \"aaabbbcccdddeeefff\");",
12128             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
12129                    getLLVMStyleWithColumns(26)));
12130   EXPECT_EQ("someFunction1234567890(\n"
12131             "    \"aaabbbcccdddeeeff\"\n"
12132             "    \"f\");",
12133             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
12134                    getLLVMStyleWithColumns(25)));
12135   EXPECT_EQ("someFunction1234567890(\n"
12136             "    \"aaabbbcccdddeeeff\"\n"
12137             "    \"f\");",
12138             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
12139                    getLLVMStyleWithColumns(24)));
12140   EXPECT_EQ("someFunction(\n"
12141             "    \"aaabbbcc ddde \"\n"
12142             "    \"efff\");",
12143             format("someFunction(\"aaabbbcc ddde efff\");",
12144                    getLLVMStyleWithColumns(25)));
12145   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
12146             "             \"ddeeefff\");",
12147             format("someFunction(\"aaabbbccc ddeeefff\");",
12148                    getLLVMStyleWithColumns(25)));
12149   EXPECT_EQ("someFunction1234567890(\n"
12150             "    \"aaabb \"\n"
12151             "    \"cccdddeeefff\");",
12152             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
12153                    getLLVMStyleWithColumns(25)));
12154   EXPECT_EQ("#define A          \\\n"
12155             "  string s =       \\\n"
12156             "      \"123456789\"  \\\n"
12157             "      \"0\";         \\\n"
12158             "  int i;",
12159             format("#define A string s = \"1234567890\"; int i;",
12160                    getLLVMStyleWithColumns(20)));
12161   EXPECT_EQ("someFunction(\n"
12162             "    \"aaabbbcc \"\n"
12163             "    \"dddeeefff\");",
12164             format("someFunction(\"aaabbbcc dddeeefff\");",
12165                    getLLVMStyleWithColumns(25)));
12166 }
12167 
12168 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
12169   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
12170   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
12171   EXPECT_EQ("\"test\"\n"
12172             "\"\\n\"",
12173             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
12174   EXPECT_EQ("\"tes\\\\\"\n"
12175             "\"n\"",
12176             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
12177   EXPECT_EQ("\"\\\\\\\\\"\n"
12178             "\"\\n\"",
12179             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
12180   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
12181   EXPECT_EQ("\"\\uff01\"\n"
12182             "\"test\"",
12183             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
12184   EXPECT_EQ("\"\\Uff01ff02\"",
12185             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
12186   EXPECT_EQ("\"\\x000000000001\"\n"
12187             "\"next\"",
12188             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
12189   EXPECT_EQ("\"\\x000000000001next\"",
12190             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
12191   EXPECT_EQ("\"\\x000000000001\"",
12192             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
12193   EXPECT_EQ("\"test\"\n"
12194             "\"\\000000\"\n"
12195             "\"000001\"",
12196             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
12197   EXPECT_EQ("\"test\\000\"\n"
12198             "\"00000000\"\n"
12199             "\"1\"",
12200             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
12201 }
12202 
12203 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
12204   verifyFormat("void f() {\n"
12205                "  return g() {}\n"
12206                "  void h() {}");
12207   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
12208                "g();\n"
12209                "}");
12210 }
12211 
12212 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
12213   verifyFormat(
12214       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
12215 }
12216 
12217 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
12218   verifyFormat("class X {\n"
12219                "  void f() {\n"
12220                "  }\n"
12221                "};",
12222                getLLVMStyleWithColumns(12));
12223 }
12224 
12225 TEST_F(FormatTest, ConfigurableIndentWidth) {
12226   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
12227   EightIndent.IndentWidth = 8;
12228   EightIndent.ContinuationIndentWidth = 8;
12229   verifyFormat("void f() {\n"
12230                "        someFunction();\n"
12231                "        if (true) {\n"
12232                "                f();\n"
12233                "        }\n"
12234                "}",
12235                EightIndent);
12236   verifyFormat("class X {\n"
12237                "        void f() {\n"
12238                "        }\n"
12239                "};",
12240                EightIndent);
12241   verifyFormat("int x[] = {\n"
12242                "        call(),\n"
12243                "        call()};",
12244                EightIndent);
12245 }
12246 
12247 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
12248   verifyFormat("double\n"
12249                "f();",
12250                getLLVMStyleWithColumns(8));
12251 }
12252 
12253 TEST_F(FormatTest, ConfigurableUseOfTab) {
12254   FormatStyle Tab = getLLVMStyleWithColumns(42);
12255   Tab.IndentWidth = 8;
12256   Tab.UseTab = FormatStyle::UT_Always;
12257   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
12258 
12259   EXPECT_EQ("if (aaaaaaaa && // q\n"
12260             "    bb)\t\t// w\n"
12261             "\t;",
12262             format("if (aaaaaaaa &&// q\n"
12263                    "bb)// w\n"
12264                    ";",
12265                    Tab));
12266   EXPECT_EQ("if (aaa && bbb) // w\n"
12267             "\t;",
12268             format("if(aaa&&bbb)// w\n"
12269                    ";",
12270                    Tab));
12271 
12272   verifyFormat("class X {\n"
12273                "\tvoid f() {\n"
12274                "\t\tsomeFunction(parameter1,\n"
12275                "\t\t\t     parameter2);\n"
12276                "\t}\n"
12277                "};",
12278                Tab);
12279   verifyFormat("#define A                        \\\n"
12280                "\tvoid f() {               \\\n"
12281                "\t\tsomeFunction(    \\\n"
12282                "\t\t    parameter1,  \\\n"
12283                "\t\t    parameter2); \\\n"
12284                "\t}",
12285                Tab);
12286   verifyFormat("int a;\t      // x\n"
12287                "int bbbbbbbb; // x\n",
12288                Tab);
12289 
12290   Tab.TabWidth = 4;
12291   Tab.IndentWidth = 8;
12292   verifyFormat("class TabWidth4Indent8 {\n"
12293                "\t\tvoid f() {\n"
12294                "\t\t\t\tsomeFunction(parameter1,\n"
12295                "\t\t\t\t\t\t\t parameter2);\n"
12296                "\t\t}\n"
12297                "};",
12298                Tab);
12299 
12300   Tab.TabWidth = 4;
12301   Tab.IndentWidth = 4;
12302   verifyFormat("class TabWidth4Indent4 {\n"
12303                "\tvoid f() {\n"
12304                "\t\tsomeFunction(parameter1,\n"
12305                "\t\t\t\t\t parameter2);\n"
12306                "\t}\n"
12307                "};",
12308                Tab);
12309 
12310   Tab.TabWidth = 8;
12311   Tab.IndentWidth = 4;
12312   verifyFormat("class TabWidth8Indent4 {\n"
12313                "    void f() {\n"
12314                "\tsomeFunction(parameter1,\n"
12315                "\t\t     parameter2);\n"
12316                "    }\n"
12317                "};",
12318                Tab);
12319 
12320   Tab.TabWidth = 8;
12321   Tab.IndentWidth = 8;
12322   EXPECT_EQ("/*\n"
12323             "\t      a\t\tcomment\n"
12324             "\t      in multiple lines\n"
12325             "       */",
12326             format("   /*\t \t \n"
12327                    " \t \t a\t\tcomment\t \t\n"
12328                    " \t \t in multiple lines\t\n"
12329                    " \t  */",
12330                    Tab));
12331 
12332   Tab.UseTab = FormatStyle::UT_ForIndentation;
12333   verifyFormat("{\n"
12334                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12335                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12336                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12337                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12338                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12339                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12340                "};",
12341                Tab);
12342   verifyFormat("enum AA {\n"
12343                "\ta1, // Force multiple lines\n"
12344                "\ta2,\n"
12345                "\ta3\n"
12346                "};",
12347                Tab);
12348   EXPECT_EQ("if (aaaaaaaa && // q\n"
12349             "    bb)         // w\n"
12350             "\t;",
12351             format("if (aaaaaaaa &&// q\n"
12352                    "bb)// w\n"
12353                    ";",
12354                    Tab));
12355   verifyFormat("class X {\n"
12356                "\tvoid f() {\n"
12357                "\t\tsomeFunction(parameter1,\n"
12358                "\t\t             parameter2);\n"
12359                "\t}\n"
12360                "};",
12361                Tab);
12362   verifyFormat("{\n"
12363                "\tQ(\n"
12364                "\t    {\n"
12365                "\t\t    int a;\n"
12366                "\t\t    someFunction(aaaaaaaa,\n"
12367                "\t\t                 bbbbbbb);\n"
12368                "\t    },\n"
12369                "\t    p);\n"
12370                "}",
12371                Tab);
12372   EXPECT_EQ("{\n"
12373             "\t/* aaaa\n"
12374             "\t   bbbb */\n"
12375             "}",
12376             format("{\n"
12377                    "/* aaaa\n"
12378                    "   bbbb */\n"
12379                    "}",
12380                    Tab));
12381   EXPECT_EQ("{\n"
12382             "\t/*\n"
12383             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12384             "\t  bbbbbbbbbbbbb\n"
12385             "\t*/\n"
12386             "}",
12387             format("{\n"
12388                    "/*\n"
12389                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12390                    "*/\n"
12391                    "}",
12392                    Tab));
12393   EXPECT_EQ("{\n"
12394             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12395             "\t// bbbbbbbbbbbbb\n"
12396             "}",
12397             format("{\n"
12398                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12399                    "}",
12400                    Tab));
12401   EXPECT_EQ("{\n"
12402             "\t/*\n"
12403             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12404             "\t  bbbbbbbbbbbbb\n"
12405             "\t*/\n"
12406             "}",
12407             format("{\n"
12408                    "\t/*\n"
12409                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12410                    "\t*/\n"
12411                    "}",
12412                    Tab));
12413   EXPECT_EQ("{\n"
12414             "\t/*\n"
12415             "\n"
12416             "\t*/\n"
12417             "}",
12418             format("{\n"
12419                    "\t/*\n"
12420                    "\n"
12421                    "\t*/\n"
12422                    "}",
12423                    Tab));
12424   EXPECT_EQ("{\n"
12425             "\t/*\n"
12426             " asdf\n"
12427             "\t*/\n"
12428             "}",
12429             format("{\n"
12430                    "\t/*\n"
12431                    " asdf\n"
12432                    "\t*/\n"
12433                    "}",
12434                    Tab));
12435 
12436   Tab.UseTab = FormatStyle::UT_Never;
12437   EXPECT_EQ("/*\n"
12438             "              a\t\tcomment\n"
12439             "              in multiple lines\n"
12440             "       */",
12441             format("   /*\t \t \n"
12442                    " \t \t a\t\tcomment\t \t\n"
12443                    " \t \t in multiple lines\t\n"
12444                    " \t  */",
12445                    Tab));
12446   EXPECT_EQ("/* some\n"
12447             "   comment */",
12448             format(" \t \t /* some\n"
12449                    " \t \t    comment */",
12450                    Tab));
12451   EXPECT_EQ("int a; /* some\n"
12452             "   comment */",
12453             format(" \t \t int a; /* some\n"
12454                    " \t \t    comment */",
12455                    Tab));
12456 
12457   EXPECT_EQ("int a; /* some\n"
12458             "comment */",
12459             format(" \t \t int\ta; /* some\n"
12460                    " \t \t    comment */",
12461                    Tab));
12462   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12463             "    comment */",
12464             format(" \t \t f(\"\t\t\"); /* some\n"
12465                    " \t \t    comment */",
12466                    Tab));
12467   EXPECT_EQ("{\n"
12468             "        /*\n"
12469             "         * Comment\n"
12470             "         */\n"
12471             "        int i;\n"
12472             "}",
12473             format("{\n"
12474                    "\t/*\n"
12475                    "\t * Comment\n"
12476                    "\t */\n"
12477                    "\t int i;\n"
12478                    "}",
12479                    Tab));
12480 
12481   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
12482   Tab.TabWidth = 8;
12483   Tab.IndentWidth = 8;
12484   EXPECT_EQ("if (aaaaaaaa && // q\n"
12485             "    bb)         // w\n"
12486             "\t;",
12487             format("if (aaaaaaaa &&// q\n"
12488                    "bb)// w\n"
12489                    ";",
12490                    Tab));
12491   EXPECT_EQ("if (aaa && bbb) // w\n"
12492             "\t;",
12493             format("if(aaa&&bbb)// w\n"
12494                    ";",
12495                    Tab));
12496   verifyFormat("class X {\n"
12497                "\tvoid f() {\n"
12498                "\t\tsomeFunction(parameter1,\n"
12499                "\t\t\t     parameter2);\n"
12500                "\t}\n"
12501                "};",
12502                Tab);
12503   verifyFormat("#define A                        \\\n"
12504                "\tvoid f() {               \\\n"
12505                "\t\tsomeFunction(    \\\n"
12506                "\t\t    parameter1,  \\\n"
12507                "\t\t    parameter2); \\\n"
12508                "\t}",
12509                Tab);
12510   Tab.TabWidth = 4;
12511   Tab.IndentWidth = 8;
12512   verifyFormat("class TabWidth4Indent8 {\n"
12513                "\t\tvoid f() {\n"
12514                "\t\t\t\tsomeFunction(parameter1,\n"
12515                "\t\t\t\t\t\t\t parameter2);\n"
12516                "\t\t}\n"
12517                "};",
12518                Tab);
12519   Tab.TabWidth = 4;
12520   Tab.IndentWidth = 4;
12521   verifyFormat("class TabWidth4Indent4 {\n"
12522                "\tvoid f() {\n"
12523                "\t\tsomeFunction(parameter1,\n"
12524                "\t\t\t\t\t parameter2);\n"
12525                "\t}\n"
12526                "};",
12527                Tab);
12528   Tab.TabWidth = 8;
12529   Tab.IndentWidth = 4;
12530   verifyFormat("class TabWidth8Indent4 {\n"
12531                "    void f() {\n"
12532                "\tsomeFunction(parameter1,\n"
12533                "\t\t     parameter2);\n"
12534                "    }\n"
12535                "};",
12536                Tab);
12537   Tab.TabWidth = 8;
12538   Tab.IndentWidth = 8;
12539   EXPECT_EQ("/*\n"
12540             "\t      a\t\tcomment\n"
12541             "\t      in multiple lines\n"
12542             "       */",
12543             format("   /*\t \t \n"
12544                    " \t \t a\t\tcomment\t \t\n"
12545                    " \t \t in multiple lines\t\n"
12546                    " \t  */",
12547                    Tab));
12548   verifyFormat("{\n"
12549                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12550                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12551                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12552                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12553                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12554                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12555                "};",
12556                Tab);
12557   verifyFormat("enum AA {\n"
12558                "\ta1, // Force multiple lines\n"
12559                "\ta2,\n"
12560                "\ta3\n"
12561                "};",
12562                Tab);
12563   EXPECT_EQ("if (aaaaaaaa && // q\n"
12564             "    bb)         // w\n"
12565             "\t;",
12566             format("if (aaaaaaaa &&// q\n"
12567                    "bb)// w\n"
12568                    ";",
12569                    Tab));
12570   verifyFormat("class X {\n"
12571                "\tvoid f() {\n"
12572                "\t\tsomeFunction(parameter1,\n"
12573                "\t\t\t     parameter2);\n"
12574                "\t}\n"
12575                "};",
12576                Tab);
12577   verifyFormat("{\n"
12578                "\tQ(\n"
12579                "\t    {\n"
12580                "\t\t    int a;\n"
12581                "\t\t    someFunction(aaaaaaaa,\n"
12582                "\t\t\t\t bbbbbbb);\n"
12583                "\t    },\n"
12584                "\t    p);\n"
12585                "}",
12586                Tab);
12587   EXPECT_EQ("{\n"
12588             "\t/* aaaa\n"
12589             "\t   bbbb */\n"
12590             "}",
12591             format("{\n"
12592                    "/* aaaa\n"
12593                    "   bbbb */\n"
12594                    "}",
12595                    Tab));
12596   EXPECT_EQ("{\n"
12597             "\t/*\n"
12598             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12599             "\t  bbbbbbbbbbbbb\n"
12600             "\t*/\n"
12601             "}",
12602             format("{\n"
12603                    "/*\n"
12604                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12605                    "*/\n"
12606                    "}",
12607                    Tab));
12608   EXPECT_EQ("{\n"
12609             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12610             "\t// bbbbbbbbbbbbb\n"
12611             "}",
12612             format("{\n"
12613                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12614                    "}",
12615                    Tab));
12616   EXPECT_EQ("{\n"
12617             "\t/*\n"
12618             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12619             "\t  bbbbbbbbbbbbb\n"
12620             "\t*/\n"
12621             "}",
12622             format("{\n"
12623                    "\t/*\n"
12624                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12625                    "\t*/\n"
12626                    "}",
12627                    Tab));
12628   EXPECT_EQ("{\n"
12629             "\t/*\n"
12630             "\n"
12631             "\t*/\n"
12632             "}",
12633             format("{\n"
12634                    "\t/*\n"
12635                    "\n"
12636                    "\t*/\n"
12637                    "}",
12638                    Tab));
12639   EXPECT_EQ("{\n"
12640             "\t/*\n"
12641             " asdf\n"
12642             "\t*/\n"
12643             "}",
12644             format("{\n"
12645                    "\t/*\n"
12646                    " asdf\n"
12647                    "\t*/\n"
12648                    "}",
12649                    Tab));
12650   EXPECT_EQ("/* some\n"
12651             "   comment */",
12652             format(" \t \t /* some\n"
12653                    " \t \t    comment */",
12654                    Tab));
12655   EXPECT_EQ("int a; /* some\n"
12656             "   comment */",
12657             format(" \t \t int a; /* some\n"
12658                    " \t \t    comment */",
12659                    Tab));
12660   EXPECT_EQ("int a; /* some\n"
12661             "comment */",
12662             format(" \t \t int\ta; /* some\n"
12663                    " \t \t    comment */",
12664                    Tab));
12665   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12666             "    comment */",
12667             format(" \t \t f(\"\t\t\"); /* some\n"
12668                    " \t \t    comment */",
12669                    Tab));
12670   EXPECT_EQ("{\n"
12671             "\t/*\n"
12672             "\t * Comment\n"
12673             "\t */\n"
12674             "\tint i;\n"
12675             "}",
12676             format("{\n"
12677                    "\t/*\n"
12678                    "\t * Comment\n"
12679                    "\t */\n"
12680                    "\t int i;\n"
12681                    "}",
12682                    Tab));
12683   Tab.TabWidth = 2;
12684   Tab.IndentWidth = 2;
12685   EXPECT_EQ("{\n"
12686             "\t/* aaaa\n"
12687             "\t\t bbbb */\n"
12688             "}",
12689             format("{\n"
12690                    "/* aaaa\n"
12691                    "\t bbbb */\n"
12692                    "}",
12693                    Tab));
12694   EXPECT_EQ("{\n"
12695             "\t/*\n"
12696             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12697             "\t\tbbbbbbbbbbbbb\n"
12698             "\t*/\n"
12699             "}",
12700             format("{\n"
12701                    "/*\n"
12702                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12703                    "*/\n"
12704                    "}",
12705                    Tab));
12706   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
12707   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
12708   Tab.TabWidth = 4;
12709   Tab.IndentWidth = 4;
12710   verifyFormat("class Assign {\n"
12711                "\tvoid f() {\n"
12712                "\t\tint         x      = 123;\n"
12713                "\t\tint         random = 4;\n"
12714                "\t\tstd::string alphabet =\n"
12715                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
12716                "\t}\n"
12717                "};",
12718                Tab);
12719 
12720   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
12721   Tab.TabWidth = 8;
12722   Tab.IndentWidth = 8;
12723   EXPECT_EQ("if (aaaaaaaa && // q\n"
12724             "    bb)         // w\n"
12725             "\t;",
12726             format("if (aaaaaaaa &&// q\n"
12727                    "bb)// w\n"
12728                    ";",
12729                    Tab));
12730   EXPECT_EQ("if (aaa && bbb) // w\n"
12731             "\t;",
12732             format("if(aaa&&bbb)// w\n"
12733                    ";",
12734                    Tab));
12735   verifyFormat("class X {\n"
12736                "\tvoid f() {\n"
12737                "\t\tsomeFunction(parameter1,\n"
12738                "\t\t             parameter2);\n"
12739                "\t}\n"
12740                "};",
12741                Tab);
12742   verifyFormat("#define A                        \\\n"
12743                "\tvoid f() {               \\\n"
12744                "\t\tsomeFunction(    \\\n"
12745                "\t\t    parameter1,  \\\n"
12746                "\t\t    parameter2); \\\n"
12747                "\t}",
12748                Tab);
12749   Tab.TabWidth = 4;
12750   Tab.IndentWidth = 8;
12751   verifyFormat("class TabWidth4Indent8 {\n"
12752                "\t\tvoid f() {\n"
12753                "\t\t\t\tsomeFunction(parameter1,\n"
12754                "\t\t\t\t             parameter2);\n"
12755                "\t\t}\n"
12756                "};",
12757                Tab);
12758   Tab.TabWidth = 4;
12759   Tab.IndentWidth = 4;
12760   verifyFormat("class TabWidth4Indent4 {\n"
12761                "\tvoid f() {\n"
12762                "\t\tsomeFunction(parameter1,\n"
12763                "\t\t             parameter2);\n"
12764                "\t}\n"
12765                "};",
12766                Tab);
12767   Tab.TabWidth = 8;
12768   Tab.IndentWidth = 4;
12769   verifyFormat("class TabWidth8Indent4 {\n"
12770                "    void f() {\n"
12771                "\tsomeFunction(parameter1,\n"
12772                "\t             parameter2);\n"
12773                "    }\n"
12774                "};",
12775                Tab);
12776   Tab.TabWidth = 8;
12777   Tab.IndentWidth = 8;
12778   EXPECT_EQ("/*\n"
12779             "              a\t\tcomment\n"
12780             "              in multiple lines\n"
12781             "       */",
12782             format("   /*\t \t \n"
12783                    " \t \t a\t\tcomment\t \t\n"
12784                    " \t \t in multiple lines\t\n"
12785                    " \t  */",
12786                    Tab));
12787   verifyFormat("{\n"
12788                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12789                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12790                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12791                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12792                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12793                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12794                "};",
12795                Tab);
12796   verifyFormat("enum AA {\n"
12797                "\ta1, // Force multiple lines\n"
12798                "\ta2,\n"
12799                "\ta3\n"
12800                "};",
12801                Tab);
12802   EXPECT_EQ("if (aaaaaaaa && // q\n"
12803             "    bb)         // w\n"
12804             "\t;",
12805             format("if (aaaaaaaa &&// q\n"
12806                    "bb)// w\n"
12807                    ";",
12808                    Tab));
12809   verifyFormat("class X {\n"
12810                "\tvoid f() {\n"
12811                "\t\tsomeFunction(parameter1,\n"
12812                "\t\t             parameter2);\n"
12813                "\t}\n"
12814                "};",
12815                Tab);
12816   verifyFormat("{\n"
12817                "\tQ(\n"
12818                "\t    {\n"
12819                "\t\t    int a;\n"
12820                "\t\t    someFunction(aaaaaaaa,\n"
12821                "\t\t                 bbbbbbb);\n"
12822                "\t    },\n"
12823                "\t    p);\n"
12824                "}",
12825                Tab);
12826   EXPECT_EQ("{\n"
12827             "\t/* aaaa\n"
12828             "\t   bbbb */\n"
12829             "}",
12830             format("{\n"
12831                    "/* aaaa\n"
12832                    "   bbbb */\n"
12833                    "}",
12834                    Tab));
12835   EXPECT_EQ("{\n"
12836             "\t/*\n"
12837             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12838             "\t  bbbbbbbbbbbbb\n"
12839             "\t*/\n"
12840             "}",
12841             format("{\n"
12842                    "/*\n"
12843                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12844                    "*/\n"
12845                    "}",
12846                    Tab));
12847   EXPECT_EQ("{\n"
12848             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12849             "\t// bbbbbbbbbbbbb\n"
12850             "}",
12851             format("{\n"
12852                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12853                    "}",
12854                    Tab));
12855   EXPECT_EQ("{\n"
12856             "\t/*\n"
12857             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12858             "\t  bbbbbbbbbbbbb\n"
12859             "\t*/\n"
12860             "}",
12861             format("{\n"
12862                    "\t/*\n"
12863                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12864                    "\t*/\n"
12865                    "}",
12866                    Tab));
12867   EXPECT_EQ("{\n"
12868             "\t/*\n"
12869             "\n"
12870             "\t*/\n"
12871             "}",
12872             format("{\n"
12873                    "\t/*\n"
12874                    "\n"
12875                    "\t*/\n"
12876                    "}",
12877                    Tab));
12878   EXPECT_EQ("{\n"
12879             "\t/*\n"
12880             " asdf\n"
12881             "\t*/\n"
12882             "}",
12883             format("{\n"
12884                    "\t/*\n"
12885                    " asdf\n"
12886                    "\t*/\n"
12887                    "}",
12888                    Tab));
12889   EXPECT_EQ("/* some\n"
12890             "   comment */",
12891             format(" \t \t /* some\n"
12892                    " \t \t    comment */",
12893                    Tab));
12894   EXPECT_EQ("int a; /* some\n"
12895             "   comment */",
12896             format(" \t \t int a; /* some\n"
12897                    " \t \t    comment */",
12898                    Tab));
12899   EXPECT_EQ("int a; /* some\n"
12900             "comment */",
12901             format(" \t \t int\ta; /* some\n"
12902                    " \t \t    comment */",
12903                    Tab));
12904   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12905             "    comment */",
12906             format(" \t \t f(\"\t\t\"); /* some\n"
12907                    " \t \t    comment */",
12908                    Tab));
12909   EXPECT_EQ("{\n"
12910             "\t/*\n"
12911             "\t * Comment\n"
12912             "\t */\n"
12913             "\tint i;\n"
12914             "}",
12915             format("{\n"
12916                    "\t/*\n"
12917                    "\t * Comment\n"
12918                    "\t */\n"
12919                    "\t int i;\n"
12920                    "}",
12921                    Tab));
12922   Tab.TabWidth = 2;
12923   Tab.IndentWidth = 2;
12924   EXPECT_EQ("{\n"
12925             "\t/* aaaa\n"
12926             "\t   bbbb */\n"
12927             "}",
12928             format("{\n"
12929                    "/* aaaa\n"
12930                    "   bbbb */\n"
12931                    "}",
12932                    Tab));
12933   EXPECT_EQ("{\n"
12934             "\t/*\n"
12935             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12936             "\t  bbbbbbbbbbbbb\n"
12937             "\t*/\n"
12938             "}",
12939             format("{\n"
12940                    "/*\n"
12941                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12942                    "*/\n"
12943                    "}",
12944                    Tab));
12945   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
12946   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
12947   Tab.TabWidth = 4;
12948   Tab.IndentWidth = 4;
12949   verifyFormat("class Assign {\n"
12950                "\tvoid f() {\n"
12951                "\t\tint         x      = 123;\n"
12952                "\t\tint         random = 4;\n"
12953                "\t\tstd::string alphabet =\n"
12954                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
12955                "\t}\n"
12956                "};",
12957                Tab);
12958   Tab.AlignOperands = FormatStyle::OAS_Align;
12959   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
12960                "                 cccccccccccccccccccc;",
12961                Tab);
12962   // no alignment
12963   verifyFormat("int aaaaaaaaaa =\n"
12964                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
12965                Tab);
12966   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
12967                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
12968                "                        : 333333333333333;",
12969                Tab);
12970   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
12971   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
12972   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
12973                "               + cccccccccccccccccccc;",
12974                Tab);
12975 }
12976 
12977 TEST_F(FormatTest, ZeroTabWidth) {
12978   FormatStyle Tab = getLLVMStyleWithColumns(42);
12979   Tab.IndentWidth = 8;
12980   Tab.UseTab = FormatStyle::UT_Never;
12981   Tab.TabWidth = 0;
12982   EXPECT_EQ("void a(){\n"
12983             "    // line starts with '\t'\n"
12984             "};",
12985             format("void a(){\n"
12986                    "\t// line starts with '\t'\n"
12987                    "};",
12988                    Tab));
12989 
12990   EXPECT_EQ("void a(){\n"
12991             "    // line starts with '\t'\n"
12992             "};",
12993             format("void a(){\n"
12994                    "\t\t// line starts with '\t'\n"
12995                    "};",
12996                    Tab));
12997 
12998   Tab.UseTab = FormatStyle::UT_ForIndentation;
12999   EXPECT_EQ("void a(){\n"
13000             "    // line starts with '\t'\n"
13001             "};",
13002             format("void a(){\n"
13003                    "\t// line starts with '\t'\n"
13004                    "};",
13005                    Tab));
13006 
13007   EXPECT_EQ("void a(){\n"
13008             "    // line starts with '\t'\n"
13009             "};",
13010             format("void a(){\n"
13011                    "\t\t// line starts with '\t'\n"
13012                    "};",
13013                    Tab));
13014 
13015   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13016   EXPECT_EQ("void a(){\n"
13017             "    // line starts with '\t'\n"
13018             "};",
13019             format("void a(){\n"
13020                    "\t// line starts with '\t'\n"
13021                    "};",
13022                    Tab));
13023 
13024   EXPECT_EQ("void a(){\n"
13025             "    // line starts with '\t'\n"
13026             "};",
13027             format("void a(){\n"
13028                    "\t\t// line starts with '\t'\n"
13029                    "};",
13030                    Tab));
13031 
13032   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
13033   EXPECT_EQ("void a(){\n"
13034             "    // line starts with '\t'\n"
13035             "};",
13036             format("void a(){\n"
13037                    "\t// line starts with '\t'\n"
13038                    "};",
13039                    Tab));
13040 
13041   EXPECT_EQ("void a(){\n"
13042             "    // line starts with '\t'\n"
13043             "};",
13044             format("void a(){\n"
13045                    "\t\t// line starts with '\t'\n"
13046                    "};",
13047                    Tab));
13048 
13049   Tab.UseTab = FormatStyle::UT_Always;
13050   EXPECT_EQ("void a(){\n"
13051             "// line starts with '\t'\n"
13052             "};",
13053             format("void a(){\n"
13054                    "\t// line starts with '\t'\n"
13055                    "};",
13056                    Tab));
13057 
13058   EXPECT_EQ("void a(){\n"
13059             "// line starts with '\t'\n"
13060             "};",
13061             format("void a(){\n"
13062                    "\t\t// line starts with '\t'\n"
13063                    "};",
13064                    Tab));
13065 }
13066 
13067 TEST_F(FormatTest, CalculatesOriginalColumn) {
13068   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13069             "q\"; /* some\n"
13070             "       comment */",
13071             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13072                    "q\"; /* some\n"
13073                    "       comment */",
13074                    getLLVMStyle()));
13075   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
13076             "/* some\n"
13077             "   comment */",
13078             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
13079                    " /* some\n"
13080                    "    comment */",
13081                    getLLVMStyle()));
13082   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13083             "qqq\n"
13084             "/* some\n"
13085             "   comment */",
13086             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13087                    "qqq\n"
13088                    " /* some\n"
13089                    "    comment */",
13090                    getLLVMStyle()));
13091   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13092             "wwww; /* some\n"
13093             "         comment */",
13094             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13095                    "wwww; /* some\n"
13096                    "         comment */",
13097                    getLLVMStyle()));
13098 }
13099 
13100 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
13101   FormatStyle NoSpace = getLLVMStyle();
13102   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
13103 
13104   verifyFormat("while(true)\n"
13105                "  continue;",
13106                NoSpace);
13107   verifyFormat("for(;;)\n"
13108                "  continue;",
13109                NoSpace);
13110   verifyFormat("if(true)\n"
13111                "  f();\n"
13112                "else if(true)\n"
13113                "  f();",
13114                NoSpace);
13115   verifyFormat("do {\n"
13116                "  do_something();\n"
13117                "} while(something());",
13118                NoSpace);
13119   verifyFormat("switch(x) {\n"
13120                "default:\n"
13121                "  break;\n"
13122                "}",
13123                NoSpace);
13124   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
13125   verifyFormat("size_t x = sizeof(x);", NoSpace);
13126   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
13127   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
13128   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
13129   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
13130   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
13131   verifyFormat("alignas(128) char a[128];", NoSpace);
13132   verifyFormat("size_t x = alignof(MyType);", NoSpace);
13133   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
13134   verifyFormat("int f() throw(Deprecated);", NoSpace);
13135   verifyFormat("typedef void (*cb)(int);", NoSpace);
13136   verifyFormat("T A::operator()();", NoSpace);
13137   verifyFormat("X A::operator++(T);", NoSpace);
13138   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
13139 
13140   FormatStyle Space = getLLVMStyle();
13141   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
13142 
13143   verifyFormat("int f ();", Space);
13144   verifyFormat("void f (int a, T b) {\n"
13145                "  while (true)\n"
13146                "    continue;\n"
13147                "}",
13148                Space);
13149   verifyFormat("if (true)\n"
13150                "  f ();\n"
13151                "else if (true)\n"
13152                "  f ();",
13153                Space);
13154   verifyFormat("do {\n"
13155                "  do_something ();\n"
13156                "} while (something ());",
13157                Space);
13158   verifyFormat("switch (x) {\n"
13159                "default:\n"
13160                "  break;\n"
13161                "}",
13162                Space);
13163   verifyFormat("A::A () : a (1) {}", Space);
13164   verifyFormat("void f () __attribute__ ((asdf));", Space);
13165   verifyFormat("*(&a + 1);\n"
13166                "&((&a)[1]);\n"
13167                "a[(b + c) * d];\n"
13168                "(((a + 1) * 2) + 3) * 4;",
13169                Space);
13170   verifyFormat("#define A(x) x", Space);
13171   verifyFormat("#define A (x) x", Space);
13172   verifyFormat("#if defined(x)\n"
13173                "#endif",
13174                Space);
13175   verifyFormat("auto i = std::make_unique<int> (5);", Space);
13176   verifyFormat("size_t x = sizeof (x);", Space);
13177   verifyFormat("auto f (int x) -> decltype (x);", Space);
13178   verifyFormat("auto f (int x) -> typeof (x);", Space);
13179   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
13180   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
13181   verifyFormat("int f (T x) noexcept (x.create ());", Space);
13182   verifyFormat("alignas (128) char a[128];", Space);
13183   verifyFormat("size_t x = alignof (MyType);", Space);
13184   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
13185   verifyFormat("int f () throw (Deprecated);", Space);
13186   verifyFormat("typedef void (*cb) (int);", Space);
13187   verifyFormat("T A::operator() ();", Space);
13188   verifyFormat("X A::operator++ (T);", Space);
13189   verifyFormat("auto lambda = [] () { return 0; };", Space);
13190   verifyFormat("int x = int (y);", Space);
13191 
13192   FormatStyle SomeSpace = getLLVMStyle();
13193   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
13194 
13195   verifyFormat("[]() -> float {}", SomeSpace);
13196   verifyFormat("[] (auto foo) {}", SomeSpace);
13197   verifyFormat("[foo]() -> int {}", SomeSpace);
13198   verifyFormat("int f();", SomeSpace);
13199   verifyFormat("void f (int a, T b) {\n"
13200                "  while (true)\n"
13201                "    continue;\n"
13202                "}",
13203                SomeSpace);
13204   verifyFormat("if (true)\n"
13205                "  f();\n"
13206                "else if (true)\n"
13207                "  f();",
13208                SomeSpace);
13209   verifyFormat("do {\n"
13210                "  do_something();\n"
13211                "} while (something());",
13212                SomeSpace);
13213   verifyFormat("switch (x) {\n"
13214                "default:\n"
13215                "  break;\n"
13216                "}",
13217                SomeSpace);
13218   verifyFormat("A::A() : a (1) {}", SomeSpace);
13219   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
13220   verifyFormat("*(&a + 1);\n"
13221                "&((&a)[1]);\n"
13222                "a[(b + c) * d];\n"
13223                "(((a + 1) * 2) + 3) * 4;",
13224                SomeSpace);
13225   verifyFormat("#define A(x) x", SomeSpace);
13226   verifyFormat("#define A (x) x", SomeSpace);
13227   verifyFormat("#if defined(x)\n"
13228                "#endif",
13229                SomeSpace);
13230   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
13231   verifyFormat("size_t x = sizeof (x);", SomeSpace);
13232   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
13233   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
13234   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
13235   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
13236   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
13237   verifyFormat("alignas (128) char a[128];", SomeSpace);
13238   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
13239   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
13240                SomeSpace);
13241   verifyFormat("int f() throw (Deprecated);", SomeSpace);
13242   verifyFormat("typedef void (*cb) (int);", SomeSpace);
13243   verifyFormat("T A::operator()();", SomeSpace);
13244   verifyFormat("X A::operator++ (T);", SomeSpace);
13245   verifyFormat("int x = int (y);", SomeSpace);
13246   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
13247 }
13248 
13249 TEST_F(FormatTest, SpaceAfterLogicalNot) {
13250   FormatStyle Spaces = getLLVMStyle();
13251   Spaces.SpaceAfterLogicalNot = true;
13252 
13253   verifyFormat("bool x = ! y", Spaces);
13254   verifyFormat("if (! isFailure())", Spaces);
13255   verifyFormat("if (! (a && b))", Spaces);
13256   verifyFormat("\"Error!\"", Spaces);
13257   verifyFormat("! ! x", Spaces);
13258 }
13259 
13260 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
13261   FormatStyle Spaces = getLLVMStyle();
13262 
13263   Spaces.SpacesInParentheses = true;
13264   verifyFormat("do_something( ::globalVar );", Spaces);
13265   verifyFormat("call( x, y, z );", Spaces);
13266   verifyFormat("call();", Spaces);
13267   verifyFormat("std::function<void( int, int )> callback;", Spaces);
13268   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
13269                Spaces);
13270   verifyFormat("while ( (bool)1 )\n"
13271                "  continue;",
13272                Spaces);
13273   verifyFormat("for ( ;; )\n"
13274                "  continue;",
13275                Spaces);
13276   verifyFormat("if ( true )\n"
13277                "  f();\n"
13278                "else if ( true )\n"
13279                "  f();",
13280                Spaces);
13281   verifyFormat("do {\n"
13282                "  do_something( (int)i );\n"
13283                "} while ( something() );",
13284                Spaces);
13285   verifyFormat("switch ( x ) {\n"
13286                "default:\n"
13287                "  break;\n"
13288                "}",
13289                Spaces);
13290 
13291   Spaces.SpacesInParentheses = false;
13292   Spaces.SpacesInCStyleCastParentheses = true;
13293   verifyFormat("Type *A = ( Type * )P;", Spaces);
13294   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
13295   verifyFormat("x = ( int32 )y;", Spaces);
13296   verifyFormat("int a = ( int )(2.0f);", Spaces);
13297   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
13298   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
13299   verifyFormat("#define x (( int )-1)", Spaces);
13300 
13301   // Run the first set of tests again with:
13302   Spaces.SpacesInParentheses = false;
13303   Spaces.SpaceInEmptyParentheses = true;
13304   Spaces.SpacesInCStyleCastParentheses = true;
13305   verifyFormat("call(x, y, z);", Spaces);
13306   verifyFormat("call( );", Spaces);
13307   verifyFormat("std::function<void(int, int)> callback;", Spaces);
13308   verifyFormat("while (( bool )1)\n"
13309                "  continue;",
13310                Spaces);
13311   verifyFormat("for (;;)\n"
13312                "  continue;",
13313                Spaces);
13314   verifyFormat("if (true)\n"
13315                "  f( );\n"
13316                "else if (true)\n"
13317                "  f( );",
13318                Spaces);
13319   verifyFormat("do {\n"
13320                "  do_something(( int )i);\n"
13321                "} while (something( ));",
13322                Spaces);
13323   verifyFormat("switch (x) {\n"
13324                "default:\n"
13325                "  break;\n"
13326                "}",
13327                Spaces);
13328 
13329   // Run the first set of tests again with:
13330   Spaces.SpaceAfterCStyleCast = true;
13331   verifyFormat("call(x, y, z);", Spaces);
13332   verifyFormat("call( );", Spaces);
13333   verifyFormat("std::function<void(int, int)> callback;", Spaces);
13334   verifyFormat("while (( bool ) 1)\n"
13335                "  continue;",
13336                Spaces);
13337   verifyFormat("for (;;)\n"
13338                "  continue;",
13339                Spaces);
13340   verifyFormat("if (true)\n"
13341                "  f( );\n"
13342                "else if (true)\n"
13343                "  f( );",
13344                Spaces);
13345   verifyFormat("do {\n"
13346                "  do_something(( int ) i);\n"
13347                "} while (something( ));",
13348                Spaces);
13349   verifyFormat("switch (x) {\n"
13350                "default:\n"
13351                "  break;\n"
13352                "}",
13353                Spaces);
13354 
13355   // Run subset of tests again with:
13356   Spaces.SpacesInCStyleCastParentheses = false;
13357   Spaces.SpaceAfterCStyleCast = true;
13358   verifyFormat("while ((bool) 1)\n"
13359                "  continue;",
13360                Spaces);
13361   verifyFormat("do {\n"
13362                "  do_something((int) i);\n"
13363                "} while (something( ));",
13364                Spaces);
13365 
13366   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
13367   verifyFormat("size_t idx = (size_t) a;", Spaces);
13368   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
13369   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
13370   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
13371   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
13372   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
13373   Spaces.ColumnLimit = 80;
13374   Spaces.IndentWidth = 4;
13375   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13376   verifyFormat("void foo( ) {\n"
13377                "    size_t foo = (*(function))(\n"
13378                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
13379                "BarrrrrrrrrrrrLong,\n"
13380                "        FoooooooooLooooong);\n"
13381                "}",
13382                Spaces);
13383   Spaces.SpaceAfterCStyleCast = false;
13384   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
13385   verifyFormat("size_t idx = (size_t)a;", Spaces);
13386   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
13387   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
13388   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
13389   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
13390   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
13391 
13392   verifyFormat("void foo( ) {\n"
13393                "    size_t foo = (*(function))(\n"
13394                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
13395                "BarrrrrrrrrrrrLong,\n"
13396                "        FoooooooooLooooong);\n"
13397                "}",
13398                Spaces);
13399 }
13400 
13401 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
13402   verifyFormat("int a[5];");
13403   verifyFormat("a[3] += 42;");
13404 
13405   FormatStyle Spaces = getLLVMStyle();
13406   Spaces.SpacesInSquareBrackets = true;
13407   // Not lambdas.
13408   verifyFormat("int a[ 5 ];", Spaces);
13409   verifyFormat("a[ 3 ] += 42;", Spaces);
13410   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
13411   verifyFormat("double &operator[](int i) { return 0; }\n"
13412                "int i;",
13413                Spaces);
13414   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
13415   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
13416   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
13417   // Lambdas.
13418   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
13419   verifyFormat("return [ i, args... ] {};", Spaces);
13420   verifyFormat("int foo = [ &bar ]() {};", Spaces);
13421   verifyFormat("int foo = [ = ]() {};", Spaces);
13422   verifyFormat("int foo = [ & ]() {};", Spaces);
13423   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
13424   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
13425 }
13426 
13427 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
13428   FormatStyle NoSpaceStyle = getLLVMStyle();
13429   verifyFormat("int a[5];", NoSpaceStyle);
13430   verifyFormat("a[3] += 42;", NoSpaceStyle);
13431 
13432   verifyFormat("int a[1];", NoSpaceStyle);
13433   verifyFormat("int 1 [a];", NoSpaceStyle);
13434   verifyFormat("int a[1][2];", NoSpaceStyle);
13435   verifyFormat("a[7] = 5;", NoSpaceStyle);
13436   verifyFormat("int a = (f())[23];", NoSpaceStyle);
13437   verifyFormat("f([] {})", NoSpaceStyle);
13438 
13439   FormatStyle Space = getLLVMStyle();
13440   Space.SpaceBeforeSquareBrackets = true;
13441   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
13442   verifyFormat("return [i, args...] {};", Space);
13443 
13444   verifyFormat("int a [5];", Space);
13445   verifyFormat("a [3] += 42;", Space);
13446   verifyFormat("constexpr char hello []{\"hello\"};", Space);
13447   verifyFormat("double &operator[](int i) { return 0; }\n"
13448                "int i;",
13449                Space);
13450   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
13451   verifyFormat("int i = a [a][a]->f();", Space);
13452   verifyFormat("int i = (*b) [a]->f();", Space);
13453 
13454   verifyFormat("int a [1];", Space);
13455   verifyFormat("int 1 [a];", Space);
13456   verifyFormat("int a [1][2];", Space);
13457   verifyFormat("a [7] = 5;", Space);
13458   verifyFormat("int a = (f()) [23];", Space);
13459   verifyFormat("f([] {})", Space);
13460 }
13461 
13462 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
13463   verifyFormat("int a = 5;");
13464   verifyFormat("a += 42;");
13465   verifyFormat("a or_eq 8;");
13466 
13467   FormatStyle Spaces = getLLVMStyle();
13468   Spaces.SpaceBeforeAssignmentOperators = false;
13469   verifyFormat("int a= 5;", Spaces);
13470   verifyFormat("a+= 42;", Spaces);
13471   verifyFormat("a or_eq 8;", Spaces);
13472 }
13473 
13474 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
13475   verifyFormat("class Foo : public Bar {};");
13476   verifyFormat("Foo::Foo() : foo(1) {}");
13477   verifyFormat("for (auto a : b) {\n}");
13478   verifyFormat("int x = a ? b : c;");
13479   verifyFormat("{\n"
13480                "label0:\n"
13481                "  int x = 0;\n"
13482                "}");
13483   verifyFormat("switch (x) {\n"
13484                "case 1:\n"
13485                "default:\n"
13486                "}");
13487   verifyFormat("switch (allBraces) {\n"
13488                "case 1: {\n"
13489                "  break;\n"
13490                "}\n"
13491                "case 2: {\n"
13492                "  [[fallthrough]];\n"
13493                "}\n"
13494                "default: {\n"
13495                "  break;\n"
13496                "}\n"
13497                "}");
13498 
13499   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
13500   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
13501   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
13502   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
13503   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
13504   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
13505   verifyFormat("{\n"
13506                "label1:\n"
13507                "  int x = 0;\n"
13508                "}",
13509                CtorInitializerStyle);
13510   verifyFormat("switch (x) {\n"
13511                "case 1:\n"
13512                "default:\n"
13513                "}",
13514                CtorInitializerStyle);
13515   verifyFormat("switch (allBraces) {\n"
13516                "case 1: {\n"
13517                "  break;\n"
13518                "}\n"
13519                "case 2: {\n"
13520                "  [[fallthrough]];\n"
13521                "}\n"
13522                "default: {\n"
13523                "  break;\n"
13524                "}\n"
13525                "}",
13526                CtorInitializerStyle);
13527   CtorInitializerStyle.BreakConstructorInitializers =
13528       FormatStyle::BCIS_AfterColon;
13529   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
13530                "    aaaaaaaaaaaaaaaa(1),\n"
13531                "    bbbbbbbbbbbbbbbb(2) {}",
13532                CtorInitializerStyle);
13533   CtorInitializerStyle.BreakConstructorInitializers =
13534       FormatStyle::BCIS_BeforeComma;
13535   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13536                "    : aaaaaaaaaaaaaaaa(1)\n"
13537                "    , bbbbbbbbbbbbbbbb(2) {}",
13538                CtorInitializerStyle);
13539   CtorInitializerStyle.BreakConstructorInitializers =
13540       FormatStyle::BCIS_BeforeColon;
13541   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13542                "    : aaaaaaaaaaaaaaaa(1),\n"
13543                "      bbbbbbbbbbbbbbbb(2) {}",
13544                CtorInitializerStyle);
13545   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
13546   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13547                ": aaaaaaaaaaaaaaaa(1),\n"
13548                "  bbbbbbbbbbbbbbbb(2) {}",
13549                CtorInitializerStyle);
13550 
13551   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
13552   InheritanceStyle.SpaceBeforeInheritanceColon = false;
13553   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
13554   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
13555   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
13556   verifyFormat("int x = a ? b : c;", InheritanceStyle);
13557   verifyFormat("{\n"
13558                "label2:\n"
13559                "  int x = 0;\n"
13560                "}",
13561                InheritanceStyle);
13562   verifyFormat("switch (x) {\n"
13563                "case 1:\n"
13564                "default:\n"
13565                "}",
13566                InheritanceStyle);
13567   verifyFormat("switch (allBraces) {\n"
13568                "case 1: {\n"
13569                "  break;\n"
13570                "}\n"
13571                "case 2: {\n"
13572                "  [[fallthrough]];\n"
13573                "}\n"
13574                "default: {\n"
13575                "  break;\n"
13576                "}\n"
13577                "}",
13578                InheritanceStyle);
13579   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
13580   verifyFormat("class Foooooooooooooooooooooo\n"
13581                "    : public aaaaaaaaaaaaaaaaaa,\n"
13582                "      public bbbbbbbbbbbbbbbbbb {\n"
13583                "}",
13584                InheritanceStyle);
13585   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
13586   verifyFormat("class Foooooooooooooooooooooo:\n"
13587                "    public aaaaaaaaaaaaaaaaaa,\n"
13588                "    public bbbbbbbbbbbbbbbbbb {\n"
13589                "}",
13590                InheritanceStyle);
13591   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
13592   verifyFormat("class Foooooooooooooooooooooo\n"
13593                "    : public aaaaaaaaaaaaaaaaaa\n"
13594                "    , public bbbbbbbbbbbbbbbbbb {\n"
13595                "}",
13596                InheritanceStyle);
13597   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
13598   verifyFormat("class Foooooooooooooooooooooo\n"
13599                "    : public aaaaaaaaaaaaaaaaaa,\n"
13600                "      public bbbbbbbbbbbbbbbbbb {\n"
13601                "}",
13602                InheritanceStyle);
13603   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
13604   verifyFormat("class Foooooooooooooooooooooo\n"
13605                ": public aaaaaaaaaaaaaaaaaa,\n"
13606                "  public bbbbbbbbbbbbbbbbbb {}",
13607                InheritanceStyle);
13608 
13609   FormatStyle ForLoopStyle = getLLVMStyle();
13610   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
13611   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
13612   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
13613   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
13614   verifyFormat("int x = a ? b : c;", ForLoopStyle);
13615   verifyFormat("{\n"
13616                "label2:\n"
13617                "  int x = 0;\n"
13618                "}",
13619                ForLoopStyle);
13620   verifyFormat("switch (x) {\n"
13621                "case 1:\n"
13622                "default:\n"
13623                "}",
13624                ForLoopStyle);
13625   verifyFormat("switch (allBraces) {\n"
13626                "case 1: {\n"
13627                "  break;\n"
13628                "}\n"
13629                "case 2: {\n"
13630                "  [[fallthrough]];\n"
13631                "}\n"
13632                "default: {\n"
13633                "  break;\n"
13634                "}\n"
13635                "}",
13636                ForLoopStyle);
13637 
13638   FormatStyle CaseStyle = getLLVMStyle();
13639   CaseStyle.SpaceBeforeCaseColon = true;
13640   verifyFormat("class Foo : public Bar {};", CaseStyle);
13641   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
13642   verifyFormat("for (auto a : b) {\n}", CaseStyle);
13643   verifyFormat("int x = a ? b : c;", CaseStyle);
13644   verifyFormat("switch (x) {\n"
13645                "case 1 :\n"
13646                "default :\n"
13647                "}",
13648                CaseStyle);
13649   verifyFormat("switch (allBraces) {\n"
13650                "case 1 : {\n"
13651                "  break;\n"
13652                "}\n"
13653                "case 2 : {\n"
13654                "  [[fallthrough]];\n"
13655                "}\n"
13656                "default : {\n"
13657                "  break;\n"
13658                "}\n"
13659                "}",
13660                CaseStyle);
13661 
13662   FormatStyle NoSpaceStyle = getLLVMStyle();
13663   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
13664   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
13665   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
13666   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
13667   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
13668   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
13669   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
13670   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
13671   verifyFormat("{\n"
13672                "label3:\n"
13673                "  int x = 0;\n"
13674                "}",
13675                NoSpaceStyle);
13676   verifyFormat("switch (x) {\n"
13677                "case 1:\n"
13678                "default:\n"
13679                "}",
13680                NoSpaceStyle);
13681   verifyFormat("switch (allBraces) {\n"
13682                "case 1: {\n"
13683                "  break;\n"
13684                "}\n"
13685                "case 2: {\n"
13686                "  [[fallthrough]];\n"
13687                "}\n"
13688                "default: {\n"
13689                "  break;\n"
13690                "}\n"
13691                "}",
13692                NoSpaceStyle);
13693 
13694   FormatStyle InvertedSpaceStyle = getLLVMStyle();
13695   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
13696   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
13697   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
13698   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
13699   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
13700   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
13701   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
13702   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
13703   verifyFormat("{\n"
13704                "label3:\n"
13705                "  int x = 0;\n"
13706                "}",
13707                InvertedSpaceStyle);
13708   verifyFormat("switch (x) {\n"
13709                "case 1 :\n"
13710                "case 2 : {\n"
13711                "  break;\n"
13712                "}\n"
13713                "default :\n"
13714                "  break;\n"
13715                "}",
13716                InvertedSpaceStyle);
13717   verifyFormat("switch (allBraces) {\n"
13718                "case 1 : {\n"
13719                "  break;\n"
13720                "}\n"
13721                "case 2 : {\n"
13722                "  [[fallthrough]];\n"
13723                "}\n"
13724                "default : {\n"
13725                "  break;\n"
13726                "}\n"
13727                "}",
13728                InvertedSpaceStyle);
13729 }
13730 
13731 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
13732   FormatStyle Style = getLLVMStyle();
13733 
13734   Style.PointerAlignment = FormatStyle::PAS_Left;
13735   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
13736   verifyFormat("void* const* x = NULL;", Style);
13737 
13738 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
13739   do {                                                                         \
13740     Style.PointerAlignment = FormatStyle::Pointers;                            \
13741     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
13742     verifyFormat(Code, Style);                                                 \
13743   } while (false)
13744 
13745   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
13746   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
13747   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
13748 
13749   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
13750   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
13751   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
13752 
13753   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
13754   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
13755   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
13756 
13757   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
13758   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
13759   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
13760 
13761   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
13762   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
13763                         SAPQ_Default);
13764   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13765                         SAPQ_Default);
13766 
13767   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
13768   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
13769                         SAPQ_Before);
13770   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13771                         SAPQ_Before);
13772 
13773   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
13774   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
13775   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13776                         SAPQ_After);
13777 
13778   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
13779   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
13780   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
13781 
13782 #undef verifyQualifierSpaces
13783 
13784   FormatStyle Spaces = getLLVMStyle();
13785   Spaces.AttributeMacros.push_back("qualified");
13786   Spaces.PointerAlignment = FormatStyle::PAS_Right;
13787   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
13788   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
13789   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
13790   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
13791   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
13792   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13793   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
13794   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
13795   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
13796   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
13797   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
13798   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13799 
13800   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
13801   Spaces.PointerAlignment = FormatStyle::PAS_Left;
13802   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
13803   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
13804   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
13805   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
13806   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
13807   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13808   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
13809   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
13810   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
13811   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
13812   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
13813   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
13814   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13815 
13816   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
13817   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
13818   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
13819   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
13820   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
13821   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
13822   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
13823   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13824 }
13825 
13826 TEST_F(FormatTest, AlignConsecutiveMacros) {
13827   FormatStyle Style = getLLVMStyle();
13828   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13829   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13830   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
13831 
13832   verifyFormat("#define a 3\n"
13833                "#define bbbb 4\n"
13834                "#define ccc (5)",
13835                Style);
13836 
13837   verifyFormat("#define f(x) (x * x)\n"
13838                "#define fff(x, y, z) (x * y + z)\n"
13839                "#define ffff(x, y) (x - y)",
13840                Style);
13841 
13842   verifyFormat("#define foo(x, y) (x + y)\n"
13843                "#define bar (5, 6)(2 + 2)",
13844                Style);
13845 
13846   verifyFormat("#define a 3\n"
13847                "#define bbbb 4\n"
13848                "#define ccc (5)\n"
13849                "#define f(x) (x * x)\n"
13850                "#define fff(x, y, z) (x * y + z)\n"
13851                "#define ffff(x, y) (x - y)",
13852                Style);
13853 
13854   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13855   verifyFormat("#define a    3\n"
13856                "#define bbbb 4\n"
13857                "#define ccc  (5)",
13858                Style);
13859 
13860   verifyFormat("#define f(x)         (x * x)\n"
13861                "#define fff(x, y, z) (x * y + z)\n"
13862                "#define ffff(x, y)   (x - y)",
13863                Style);
13864 
13865   verifyFormat("#define foo(x, y) (x + y)\n"
13866                "#define bar       (5, 6)(2 + 2)",
13867                Style);
13868 
13869   verifyFormat("#define a            3\n"
13870                "#define bbbb         4\n"
13871                "#define ccc          (5)\n"
13872                "#define f(x)         (x * x)\n"
13873                "#define fff(x, y, z) (x * y + z)\n"
13874                "#define ffff(x, y)   (x - y)",
13875                Style);
13876 
13877   verifyFormat("#define a         5\n"
13878                "#define foo(x, y) (x + y)\n"
13879                "#define CCC       (6)\n"
13880                "auto lambda = []() {\n"
13881                "  auto  ii = 0;\n"
13882                "  float j  = 0;\n"
13883                "  return 0;\n"
13884                "};\n"
13885                "int   i  = 0;\n"
13886                "float i2 = 0;\n"
13887                "auto  v  = type{\n"
13888                "    i = 1,   //\n"
13889                "    (i = 2), //\n"
13890                "    i = 3    //\n"
13891                "};",
13892                Style);
13893 
13894   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
13895   Style.ColumnLimit = 20;
13896 
13897   verifyFormat("#define a          \\\n"
13898                "  \"aabbbbbbbbbbbb\"\n"
13899                "#define D          \\\n"
13900                "  \"aabbbbbbbbbbbb\" \\\n"
13901                "  \"ccddeeeeeeeee\"\n"
13902                "#define B          \\\n"
13903                "  \"QQQQQQQQQQQQQ\"  \\\n"
13904                "  \"FFFFFFFFFFFFF\"  \\\n"
13905                "  \"LLLLLLLL\"\n",
13906                Style);
13907 
13908   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13909   verifyFormat("#define a          \\\n"
13910                "  \"aabbbbbbbbbbbb\"\n"
13911                "#define D          \\\n"
13912                "  \"aabbbbbbbbbbbb\" \\\n"
13913                "  \"ccddeeeeeeeee\"\n"
13914                "#define B          \\\n"
13915                "  \"QQQQQQQQQQQQQ\"  \\\n"
13916                "  \"FFFFFFFFFFFFF\"  \\\n"
13917                "  \"LLLLLLLL\"\n",
13918                Style);
13919 
13920   // Test across comments
13921   Style.MaxEmptyLinesToKeep = 10;
13922   Style.ReflowComments = false;
13923   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
13924   EXPECT_EQ("#define a    3\n"
13925             "// line comment\n"
13926             "#define bbbb 4\n"
13927             "#define ccc  (5)",
13928             format("#define a 3\n"
13929                    "// line comment\n"
13930                    "#define bbbb 4\n"
13931                    "#define ccc (5)",
13932                    Style));
13933 
13934   EXPECT_EQ("#define a    3\n"
13935             "/* block comment */\n"
13936             "#define bbbb 4\n"
13937             "#define ccc  (5)",
13938             format("#define a  3\n"
13939                    "/* block comment */\n"
13940                    "#define bbbb 4\n"
13941                    "#define ccc (5)",
13942                    Style));
13943 
13944   EXPECT_EQ("#define a    3\n"
13945             "/* multi-line *\n"
13946             " * block comment */\n"
13947             "#define bbbb 4\n"
13948             "#define ccc  (5)",
13949             format("#define a 3\n"
13950                    "/* multi-line *\n"
13951                    " * block comment */\n"
13952                    "#define bbbb 4\n"
13953                    "#define ccc (5)",
13954                    Style));
13955 
13956   EXPECT_EQ("#define a    3\n"
13957             "// multi-line line comment\n"
13958             "//\n"
13959             "#define bbbb 4\n"
13960             "#define ccc  (5)",
13961             format("#define a  3\n"
13962                    "// multi-line line comment\n"
13963                    "//\n"
13964                    "#define bbbb 4\n"
13965                    "#define ccc (5)",
13966                    Style));
13967 
13968   EXPECT_EQ("#define a 3\n"
13969             "// empty lines still break.\n"
13970             "\n"
13971             "#define bbbb 4\n"
13972             "#define ccc  (5)",
13973             format("#define a     3\n"
13974                    "// empty lines still break.\n"
13975                    "\n"
13976                    "#define bbbb     4\n"
13977                    "#define ccc  (5)",
13978                    Style));
13979 
13980   // Test across empty lines
13981   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
13982   EXPECT_EQ("#define a    3\n"
13983             "\n"
13984             "#define bbbb 4\n"
13985             "#define ccc  (5)",
13986             format("#define a 3\n"
13987                    "\n"
13988                    "#define bbbb 4\n"
13989                    "#define ccc (5)",
13990                    Style));
13991 
13992   EXPECT_EQ("#define a    3\n"
13993             "\n"
13994             "\n"
13995             "\n"
13996             "#define bbbb 4\n"
13997             "#define ccc  (5)",
13998             format("#define a        3\n"
13999                    "\n"
14000                    "\n"
14001                    "\n"
14002                    "#define bbbb 4\n"
14003                    "#define ccc (5)",
14004                    Style));
14005 
14006   EXPECT_EQ("#define a 3\n"
14007             "// comments should break alignment\n"
14008             "//\n"
14009             "#define bbbb 4\n"
14010             "#define ccc  (5)",
14011             format("#define a        3\n"
14012                    "// comments should break alignment\n"
14013                    "//\n"
14014                    "#define bbbb 4\n"
14015                    "#define ccc (5)",
14016                    Style));
14017 
14018   // Test across empty lines and comments
14019   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
14020   verifyFormat("#define a    3\n"
14021                "\n"
14022                "// line comment\n"
14023                "#define bbbb 4\n"
14024                "#define ccc  (5)",
14025                Style);
14026 
14027   EXPECT_EQ("#define a    3\n"
14028             "\n"
14029             "\n"
14030             "/* multi-line *\n"
14031             " * block comment */\n"
14032             "\n"
14033             "\n"
14034             "#define bbbb 4\n"
14035             "#define ccc  (5)",
14036             format("#define a 3\n"
14037                    "\n"
14038                    "\n"
14039                    "/* multi-line *\n"
14040                    " * block comment */\n"
14041                    "\n"
14042                    "\n"
14043                    "#define bbbb 4\n"
14044                    "#define ccc (5)",
14045                    Style));
14046 
14047   EXPECT_EQ("#define a    3\n"
14048             "\n"
14049             "\n"
14050             "/* multi-line *\n"
14051             " * block comment */\n"
14052             "\n"
14053             "\n"
14054             "#define bbbb 4\n"
14055             "#define ccc  (5)",
14056             format("#define a 3\n"
14057                    "\n"
14058                    "\n"
14059                    "/* multi-line *\n"
14060                    " * block comment */\n"
14061                    "\n"
14062                    "\n"
14063                    "#define bbbb 4\n"
14064                    "#define ccc       (5)",
14065                    Style));
14066 }
14067 
14068 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
14069   FormatStyle Alignment = getLLVMStyle();
14070   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14071   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
14072 
14073   Alignment.MaxEmptyLinesToKeep = 10;
14074   /* Test alignment across empty lines */
14075   EXPECT_EQ("int a           = 5;\n"
14076             "\n"
14077             "int oneTwoThree = 123;",
14078             format("int a       = 5;\n"
14079                    "\n"
14080                    "int oneTwoThree= 123;",
14081                    Alignment));
14082   EXPECT_EQ("int a           = 5;\n"
14083             "int one         = 1;\n"
14084             "\n"
14085             "int oneTwoThree = 123;",
14086             format("int a = 5;\n"
14087                    "int one = 1;\n"
14088                    "\n"
14089                    "int oneTwoThree = 123;",
14090                    Alignment));
14091   EXPECT_EQ("int a           = 5;\n"
14092             "int one         = 1;\n"
14093             "\n"
14094             "int oneTwoThree = 123;\n"
14095             "int oneTwo      = 12;",
14096             format("int a = 5;\n"
14097                    "int one = 1;\n"
14098                    "\n"
14099                    "int oneTwoThree = 123;\n"
14100                    "int oneTwo = 12;",
14101                    Alignment));
14102 
14103   /* Test across comments */
14104   EXPECT_EQ("int a = 5;\n"
14105             "/* block comment */\n"
14106             "int oneTwoThree = 123;",
14107             format("int a = 5;\n"
14108                    "/* block comment */\n"
14109                    "int oneTwoThree=123;",
14110                    Alignment));
14111 
14112   EXPECT_EQ("int a = 5;\n"
14113             "// line comment\n"
14114             "int oneTwoThree = 123;",
14115             format("int a = 5;\n"
14116                    "// line comment\n"
14117                    "int oneTwoThree=123;",
14118                    Alignment));
14119 
14120   /* Test across comments and newlines */
14121   EXPECT_EQ("int a = 5;\n"
14122             "\n"
14123             "/* block comment */\n"
14124             "int oneTwoThree = 123;",
14125             format("int a = 5;\n"
14126                    "\n"
14127                    "/* block comment */\n"
14128                    "int oneTwoThree=123;",
14129                    Alignment));
14130 
14131   EXPECT_EQ("int a = 5;\n"
14132             "\n"
14133             "// line comment\n"
14134             "int oneTwoThree = 123;",
14135             format("int a = 5;\n"
14136                    "\n"
14137                    "// line comment\n"
14138                    "int oneTwoThree=123;",
14139                    Alignment));
14140 }
14141 
14142 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
14143   FormatStyle Alignment = getLLVMStyle();
14144   Alignment.AlignConsecutiveDeclarations =
14145       FormatStyle::ACS_AcrossEmptyLinesAndComments;
14146   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14147 
14148   Alignment.MaxEmptyLinesToKeep = 10;
14149   /* Test alignment across empty lines */
14150   EXPECT_EQ("int         a = 5;\n"
14151             "\n"
14152             "float const oneTwoThree = 123;",
14153             format("int a = 5;\n"
14154                    "\n"
14155                    "float const oneTwoThree = 123;",
14156                    Alignment));
14157   EXPECT_EQ("int         a = 5;\n"
14158             "float const one = 1;\n"
14159             "\n"
14160             "int         oneTwoThree = 123;",
14161             format("int a = 5;\n"
14162                    "float const one = 1;\n"
14163                    "\n"
14164                    "int oneTwoThree = 123;",
14165                    Alignment));
14166 
14167   /* Test across comments */
14168   EXPECT_EQ("float const a = 5;\n"
14169             "/* block comment */\n"
14170             "int         oneTwoThree = 123;",
14171             format("float const a = 5;\n"
14172                    "/* block comment */\n"
14173                    "int oneTwoThree=123;",
14174                    Alignment));
14175 
14176   EXPECT_EQ("float const a = 5;\n"
14177             "// line comment\n"
14178             "int         oneTwoThree = 123;",
14179             format("float const a = 5;\n"
14180                    "// line comment\n"
14181                    "int oneTwoThree=123;",
14182                    Alignment));
14183 
14184   /* Test across comments and newlines */
14185   EXPECT_EQ("float const a = 5;\n"
14186             "\n"
14187             "/* block comment */\n"
14188             "int         oneTwoThree = 123;",
14189             format("float const a = 5;\n"
14190                    "\n"
14191                    "/* block comment */\n"
14192                    "int         oneTwoThree=123;",
14193                    Alignment));
14194 
14195   EXPECT_EQ("float const a = 5;\n"
14196             "\n"
14197             "// line comment\n"
14198             "int         oneTwoThree = 123;",
14199             format("float const a = 5;\n"
14200                    "\n"
14201                    "// line comment\n"
14202                    "int oneTwoThree=123;",
14203                    Alignment));
14204 }
14205 
14206 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
14207   FormatStyle Alignment = getLLVMStyle();
14208   Alignment.AlignConsecutiveBitFields =
14209       FormatStyle::ACS_AcrossEmptyLinesAndComments;
14210 
14211   Alignment.MaxEmptyLinesToKeep = 10;
14212   /* Test alignment across empty lines */
14213   EXPECT_EQ("int a            : 5;\n"
14214             "\n"
14215             "int longbitfield : 6;",
14216             format("int a : 5;\n"
14217                    "\n"
14218                    "int longbitfield : 6;",
14219                    Alignment));
14220   EXPECT_EQ("int a            : 5;\n"
14221             "int one          : 1;\n"
14222             "\n"
14223             "int longbitfield : 6;",
14224             format("int a : 5;\n"
14225                    "int one : 1;\n"
14226                    "\n"
14227                    "int longbitfield : 6;",
14228                    Alignment));
14229 
14230   /* Test across comments */
14231   EXPECT_EQ("int a            : 5;\n"
14232             "/* block comment */\n"
14233             "int longbitfield : 6;",
14234             format("int a : 5;\n"
14235                    "/* block comment */\n"
14236                    "int longbitfield : 6;",
14237                    Alignment));
14238   EXPECT_EQ("int a            : 5;\n"
14239             "int one          : 1;\n"
14240             "// line comment\n"
14241             "int longbitfield : 6;",
14242             format("int a : 5;\n"
14243                    "int one : 1;\n"
14244                    "// line comment\n"
14245                    "int longbitfield : 6;",
14246                    Alignment));
14247 
14248   /* Test across comments and newlines */
14249   EXPECT_EQ("int a            : 5;\n"
14250             "/* block comment */\n"
14251             "\n"
14252             "int longbitfield : 6;",
14253             format("int a : 5;\n"
14254                    "/* block comment */\n"
14255                    "\n"
14256                    "int longbitfield : 6;",
14257                    Alignment));
14258   EXPECT_EQ("int a            : 5;\n"
14259             "int one          : 1;\n"
14260             "\n"
14261             "// line comment\n"
14262             "\n"
14263             "int longbitfield : 6;",
14264             format("int a : 5;\n"
14265                    "int one : 1;\n"
14266                    "\n"
14267                    "// line comment \n"
14268                    "\n"
14269                    "int longbitfield : 6;",
14270                    Alignment));
14271 }
14272 
14273 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
14274   FormatStyle Alignment = getLLVMStyle();
14275   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14276   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
14277 
14278   Alignment.MaxEmptyLinesToKeep = 10;
14279   /* Test alignment across empty lines */
14280   EXPECT_EQ("int a = 5;\n"
14281             "\n"
14282             "int oneTwoThree = 123;",
14283             format("int a       = 5;\n"
14284                    "\n"
14285                    "int oneTwoThree= 123;",
14286                    Alignment));
14287   EXPECT_EQ("int a   = 5;\n"
14288             "int one = 1;\n"
14289             "\n"
14290             "int oneTwoThree = 123;",
14291             format("int a = 5;\n"
14292                    "int one = 1;\n"
14293                    "\n"
14294                    "int oneTwoThree = 123;",
14295                    Alignment));
14296 
14297   /* Test across comments */
14298   EXPECT_EQ("int a           = 5;\n"
14299             "/* block comment */\n"
14300             "int oneTwoThree = 123;",
14301             format("int a = 5;\n"
14302                    "/* block comment */\n"
14303                    "int oneTwoThree=123;",
14304                    Alignment));
14305 
14306   EXPECT_EQ("int a           = 5;\n"
14307             "// line comment\n"
14308             "int oneTwoThree = 123;",
14309             format("int a = 5;\n"
14310                    "// line comment\n"
14311                    "int oneTwoThree=123;",
14312                    Alignment));
14313 
14314   EXPECT_EQ("int a           = 5;\n"
14315             "/*\n"
14316             " * multi-line block comment\n"
14317             " */\n"
14318             "int oneTwoThree = 123;",
14319             format("int a = 5;\n"
14320                    "/*\n"
14321                    " * multi-line block comment\n"
14322                    " */\n"
14323                    "int oneTwoThree=123;",
14324                    Alignment));
14325 
14326   EXPECT_EQ("int a           = 5;\n"
14327             "//\n"
14328             "// multi-line line comment\n"
14329             "//\n"
14330             "int oneTwoThree = 123;",
14331             format("int a = 5;\n"
14332                    "//\n"
14333                    "// multi-line line comment\n"
14334                    "//\n"
14335                    "int oneTwoThree=123;",
14336                    Alignment));
14337 
14338   /* Test across comments and newlines */
14339   EXPECT_EQ("int a = 5;\n"
14340             "\n"
14341             "/* block comment */\n"
14342             "int oneTwoThree = 123;",
14343             format("int a = 5;\n"
14344                    "\n"
14345                    "/* block comment */\n"
14346                    "int oneTwoThree=123;",
14347                    Alignment));
14348 
14349   EXPECT_EQ("int a = 5;\n"
14350             "\n"
14351             "// line comment\n"
14352             "int oneTwoThree = 123;",
14353             format("int a = 5;\n"
14354                    "\n"
14355                    "// line comment\n"
14356                    "int oneTwoThree=123;",
14357                    Alignment));
14358 }
14359 
14360 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
14361   FormatStyle Alignment = getLLVMStyle();
14362   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14363   Alignment.AlignConsecutiveAssignments =
14364       FormatStyle::ACS_AcrossEmptyLinesAndComments;
14365   verifyFormat("int a           = 5;\n"
14366                "int oneTwoThree = 123;",
14367                Alignment);
14368   verifyFormat("int a           = method();\n"
14369                "int oneTwoThree = 133;",
14370                Alignment);
14371   verifyFormat("a &= 5;\n"
14372                "bcd *= 5;\n"
14373                "ghtyf += 5;\n"
14374                "dvfvdb -= 5;\n"
14375                "a /= 5;\n"
14376                "vdsvsv %= 5;\n"
14377                "sfdbddfbdfbb ^= 5;\n"
14378                "dvsdsv |= 5;\n"
14379                "int dsvvdvsdvvv = 123;",
14380                Alignment);
14381   verifyFormat("int i = 1, j = 10;\n"
14382                "something = 2000;",
14383                Alignment);
14384   verifyFormat("something = 2000;\n"
14385                "int i = 1, j = 10;\n",
14386                Alignment);
14387   verifyFormat("something = 2000;\n"
14388                "another   = 911;\n"
14389                "int i = 1, j = 10;\n"
14390                "oneMore = 1;\n"
14391                "i       = 2;",
14392                Alignment);
14393   verifyFormat("int a   = 5;\n"
14394                "int one = 1;\n"
14395                "method();\n"
14396                "int oneTwoThree = 123;\n"
14397                "int oneTwo      = 12;",
14398                Alignment);
14399   verifyFormat("int oneTwoThree = 123;\n"
14400                "int oneTwo      = 12;\n"
14401                "method();\n",
14402                Alignment);
14403   verifyFormat("int oneTwoThree = 123; // comment\n"
14404                "int oneTwo      = 12;  // comment",
14405                Alignment);
14406 
14407   // Bug 25167
14408   /* Uncomment when fixed
14409     verifyFormat("#if A\n"
14410                  "#else\n"
14411                  "int aaaaaaaa = 12;\n"
14412                  "#endif\n"
14413                  "#if B\n"
14414                  "#else\n"
14415                  "int a = 12;\n"
14416                  "#endif\n",
14417                  Alignment);
14418     verifyFormat("enum foo {\n"
14419                  "#if A\n"
14420                  "#else\n"
14421                  "  aaaaaaaa = 12;\n"
14422                  "#endif\n"
14423                  "#if B\n"
14424                  "#else\n"
14425                  "  a = 12;\n"
14426                  "#endif\n"
14427                  "};\n",
14428                  Alignment);
14429   */
14430 
14431   Alignment.MaxEmptyLinesToKeep = 10;
14432   /* Test alignment across empty lines */
14433   EXPECT_EQ("int a           = 5;\n"
14434             "\n"
14435             "int oneTwoThree = 123;",
14436             format("int a       = 5;\n"
14437                    "\n"
14438                    "int oneTwoThree= 123;",
14439                    Alignment));
14440   EXPECT_EQ("int a           = 5;\n"
14441             "int one         = 1;\n"
14442             "\n"
14443             "int oneTwoThree = 123;",
14444             format("int a = 5;\n"
14445                    "int one = 1;\n"
14446                    "\n"
14447                    "int oneTwoThree = 123;",
14448                    Alignment));
14449   EXPECT_EQ("int a           = 5;\n"
14450             "int one         = 1;\n"
14451             "\n"
14452             "int oneTwoThree = 123;\n"
14453             "int oneTwo      = 12;",
14454             format("int a = 5;\n"
14455                    "int one = 1;\n"
14456                    "\n"
14457                    "int oneTwoThree = 123;\n"
14458                    "int oneTwo = 12;",
14459                    Alignment));
14460 
14461   /* Test across comments */
14462   EXPECT_EQ("int a           = 5;\n"
14463             "/* block comment */\n"
14464             "int oneTwoThree = 123;",
14465             format("int a = 5;\n"
14466                    "/* block comment */\n"
14467                    "int oneTwoThree=123;",
14468                    Alignment));
14469 
14470   EXPECT_EQ("int a           = 5;\n"
14471             "// line comment\n"
14472             "int oneTwoThree = 123;",
14473             format("int a = 5;\n"
14474                    "// line comment\n"
14475                    "int oneTwoThree=123;",
14476                    Alignment));
14477 
14478   /* Test across comments and newlines */
14479   EXPECT_EQ("int a           = 5;\n"
14480             "\n"
14481             "/* block comment */\n"
14482             "int oneTwoThree = 123;",
14483             format("int a = 5;\n"
14484                    "\n"
14485                    "/* block comment */\n"
14486                    "int oneTwoThree=123;",
14487                    Alignment));
14488 
14489   EXPECT_EQ("int a           = 5;\n"
14490             "\n"
14491             "// line comment\n"
14492             "int oneTwoThree = 123;",
14493             format("int a = 5;\n"
14494                    "\n"
14495                    "// line comment\n"
14496                    "int oneTwoThree=123;",
14497                    Alignment));
14498 
14499   EXPECT_EQ("int a           = 5;\n"
14500             "//\n"
14501             "// multi-line line comment\n"
14502             "//\n"
14503             "int oneTwoThree = 123;",
14504             format("int a = 5;\n"
14505                    "//\n"
14506                    "// multi-line line comment\n"
14507                    "//\n"
14508                    "int oneTwoThree=123;",
14509                    Alignment));
14510 
14511   EXPECT_EQ("int a           = 5;\n"
14512             "/*\n"
14513             " *  multi-line block comment\n"
14514             " */\n"
14515             "int oneTwoThree = 123;",
14516             format("int a = 5;\n"
14517                    "/*\n"
14518                    " *  multi-line block comment\n"
14519                    " */\n"
14520                    "int oneTwoThree=123;",
14521                    Alignment));
14522 
14523   EXPECT_EQ("int a           = 5;\n"
14524             "\n"
14525             "/* block comment */\n"
14526             "\n"
14527             "\n"
14528             "\n"
14529             "int oneTwoThree = 123;",
14530             format("int a = 5;\n"
14531                    "\n"
14532                    "/* block comment */\n"
14533                    "\n"
14534                    "\n"
14535                    "\n"
14536                    "int oneTwoThree=123;",
14537                    Alignment));
14538 
14539   EXPECT_EQ("int a           = 5;\n"
14540             "\n"
14541             "// line comment\n"
14542             "\n"
14543             "\n"
14544             "\n"
14545             "int oneTwoThree = 123;",
14546             format("int a = 5;\n"
14547                    "\n"
14548                    "// line comment\n"
14549                    "\n"
14550                    "\n"
14551                    "\n"
14552                    "int oneTwoThree=123;",
14553                    Alignment));
14554 
14555   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14556   verifyFormat("#define A \\\n"
14557                "  int aaaa       = 12; \\\n"
14558                "  int b          = 23; \\\n"
14559                "  int ccc        = 234; \\\n"
14560                "  int dddddddddd = 2345;",
14561                Alignment);
14562   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14563   verifyFormat("#define A               \\\n"
14564                "  int aaaa       = 12;  \\\n"
14565                "  int b          = 23;  \\\n"
14566                "  int ccc        = 234; \\\n"
14567                "  int dddddddddd = 2345;",
14568                Alignment);
14569   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14570   verifyFormat("#define A                                                      "
14571                "                \\\n"
14572                "  int aaaa       = 12;                                         "
14573                "                \\\n"
14574                "  int b          = 23;                                         "
14575                "                \\\n"
14576                "  int ccc        = 234;                                        "
14577                "                \\\n"
14578                "  int dddddddddd = 2345;",
14579                Alignment);
14580   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14581                "k = 4, int l = 5,\n"
14582                "                  int m = 6) {\n"
14583                "  int j      = 10;\n"
14584                "  otherThing = 1;\n"
14585                "}",
14586                Alignment);
14587   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14588                "  int i   = 1;\n"
14589                "  int j   = 2;\n"
14590                "  int big = 10000;\n"
14591                "}",
14592                Alignment);
14593   verifyFormat("class C {\n"
14594                "public:\n"
14595                "  int i            = 1;\n"
14596                "  virtual void f() = 0;\n"
14597                "};",
14598                Alignment);
14599   verifyFormat("int i = 1;\n"
14600                "if (SomeType t = getSomething()) {\n"
14601                "}\n"
14602                "int j   = 2;\n"
14603                "int big = 10000;",
14604                Alignment);
14605   verifyFormat("int j = 7;\n"
14606                "for (int k = 0; k < N; ++k) {\n"
14607                "}\n"
14608                "int j   = 2;\n"
14609                "int big = 10000;\n"
14610                "}",
14611                Alignment);
14612   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14613   verifyFormat("int i = 1;\n"
14614                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14615                "    = someLooooooooooooooooongFunction();\n"
14616                "int j = 2;",
14617                Alignment);
14618   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14619   verifyFormat("int i = 1;\n"
14620                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14621                "    someLooooooooooooooooongFunction();\n"
14622                "int j = 2;",
14623                Alignment);
14624 
14625   verifyFormat("auto lambda = []() {\n"
14626                "  auto i = 0;\n"
14627                "  return 0;\n"
14628                "};\n"
14629                "int i  = 0;\n"
14630                "auto v = type{\n"
14631                "    i = 1,   //\n"
14632                "    (i = 2), //\n"
14633                "    i = 3    //\n"
14634                "};",
14635                Alignment);
14636 
14637   verifyFormat(
14638       "int i      = 1;\n"
14639       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14640       "                          loooooooooooooooooooooongParameterB);\n"
14641       "int j      = 2;",
14642       Alignment);
14643 
14644   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
14645                "          typename B   = very_long_type_name_1,\n"
14646                "          typename T_2 = very_long_type_name_2>\n"
14647                "auto foo() {}\n",
14648                Alignment);
14649   verifyFormat("int a, b = 1;\n"
14650                "int c  = 2;\n"
14651                "int dd = 3;\n",
14652                Alignment);
14653   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
14654                "float b[1][] = {{3.f}};\n",
14655                Alignment);
14656   verifyFormat("for (int i = 0; i < 1; i++)\n"
14657                "  int x = 1;\n",
14658                Alignment);
14659   verifyFormat("for (i = 0; i < 1; i++)\n"
14660                "  x = 1;\n"
14661                "y = 1;\n",
14662                Alignment);
14663 
14664   Alignment.ReflowComments = true;
14665   Alignment.ColumnLimit = 50;
14666   EXPECT_EQ("int x   = 0;\n"
14667             "int yy  = 1; /// specificlennospace\n"
14668             "int zzz = 2;\n",
14669             format("int x   = 0;\n"
14670                    "int yy  = 1; ///specificlennospace\n"
14671                    "int zzz = 2;\n",
14672                    Alignment));
14673 }
14674 
14675 TEST_F(FormatTest, AlignConsecutiveAssignments) {
14676   FormatStyle Alignment = getLLVMStyle();
14677   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14678   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14679   verifyFormat("int a = 5;\n"
14680                "int oneTwoThree = 123;",
14681                Alignment);
14682   verifyFormat("int a = 5;\n"
14683                "int oneTwoThree = 123;",
14684                Alignment);
14685 
14686   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14687   verifyFormat("int a           = 5;\n"
14688                "int oneTwoThree = 123;",
14689                Alignment);
14690   verifyFormat("int a           = method();\n"
14691                "int oneTwoThree = 133;",
14692                Alignment);
14693   verifyFormat("a &= 5;\n"
14694                "bcd *= 5;\n"
14695                "ghtyf += 5;\n"
14696                "dvfvdb -= 5;\n"
14697                "a /= 5;\n"
14698                "vdsvsv %= 5;\n"
14699                "sfdbddfbdfbb ^= 5;\n"
14700                "dvsdsv |= 5;\n"
14701                "int dsvvdvsdvvv = 123;",
14702                Alignment);
14703   verifyFormat("int i = 1, j = 10;\n"
14704                "something = 2000;",
14705                Alignment);
14706   verifyFormat("something = 2000;\n"
14707                "int i = 1, j = 10;\n",
14708                Alignment);
14709   verifyFormat("something = 2000;\n"
14710                "another   = 911;\n"
14711                "int i = 1, j = 10;\n"
14712                "oneMore = 1;\n"
14713                "i       = 2;",
14714                Alignment);
14715   verifyFormat("int a   = 5;\n"
14716                "int one = 1;\n"
14717                "method();\n"
14718                "int oneTwoThree = 123;\n"
14719                "int oneTwo      = 12;",
14720                Alignment);
14721   verifyFormat("int oneTwoThree = 123;\n"
14722                "int oneTwo      = 12;\n"
14723                "method();\n",
14724                Alignment);
14725   verifyFormat("int oneTwoThree = 123; // comment\n"
14726                "int oneTwo      = 12;  // comment",
14727                Alignment);
14728 
14729   // Bug 25167
14730   /* Uncomment when fixed
14731     verifyFormat("#if A\n"
14732                  "#else\n"
14733                  "int aaaaaaaa = 12;\n"
14734                  "#endif\n"
14735                  "#if B\n"
14736                  "#else\n"
14737                  "int a = 12;\n"
14738                  "#endif\n",
14739                  Alignment);
14740     verifyFormat("enum foo {\n"
14741                  "#if A\n"
14742                  "#else\n"
14743                  "  aaaaaaaa = 12;\n"
14744                  "#endif\n"
14745                  "#if B\n"
14746                  "#else\n"
14747                  "  a = 12;\n"
14748                  "#endif\n"
14749                  "};\n",
14750                  Alignment);
14751   */
14752 
14753   EXPECT_EQ("int a = 5;\n"
14754             "\n"
14755             "int oneTwoThree = 123;",
14756             format("int a       = 5;\n"
14757                    "\n"
14758                    "int oneTwoThree= 123;",
14759                    Alignment));
14760   EXPECT_EQ("int a   = 5;\n"
14761             "int one = 1;\n"
14762             "\n"
14763             "int oneTwoThree = 123;",
14764             format("int a = 5;\n"
14765                    "int one = 1;\n"
14766                    "\n"
14767                    "int oneTwoThree = 123;",
14768                    Alignment));
14769   EXPECT_EQ("int a   = 5;\n"
14770             "int one = 1;\n"
14771             "\n"
14772             "int oneTwoThree = 123;\n"
14773             "int oneTwo      = 12;",
14774             format("int a = 5;\n"
14775                    "int one = 1;\n"
14776                    "\n"
14777                    "int oneTwoThree = 123;\n"
14778                    "int oneTwo = 12;",
14779                    Alignment));
14780   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14781   verifyFormat("#define A \\\n"
14782                "  int aaaa       = 12; \\\n"
14783                "  int b          = 23; \\\n"
14784                "  int ccc        = 234; \\\n"
14785                "  int dddddddddd = 2345;",
14786                Alignment);
14787   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14788   verifyFormat("#define A               \\\n"
14789                "  int aaaa       = 12;  \\\n"
14790                "  int b          = 23;  \\\n"
14791                "  int ccc        = 234; \\\n"
14792                "  int dddddddddd = 2345;",
14793                Alignment);
14794   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14795   verifyFormat("#define A                                                      "
14796                "                \\\n"
14797                "  int aaaa       = 12;                                         "
14798                "                \\\n"
14799                "  int b          = 23;                                         "
14800                "                \\\n"
14801                "  int ccc        = 234;                                        "
14802                "                \\\n"
14803                "  int dddddddddd = 2345;",
14804                Alignment);
14805   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14806                "k = 4, int l = 5,\n"
14807                "                  int m = 6) {\n"
14808                "  int j      = 10;\n"
14809                "  otherThing = 1;\n"
14810                "}",
14811                Alignment);
14812   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14813                "  int i   = 1;\n"
14814                "  int j   = 2;\n"
14815                "  int big = 10000;\n"
14816                "}",
14817                Alignment);
14818   verifyFormat("class C {\n"
14819                "public:\n"
14820                "  int i            = 1;\n"
14821                "  virtual void f() = 0;\n"
14822                "};",
14823                Alignment);
14824   verifyFormat("int i = 1;\n"
14825                "if (SomeType t = getSomething()) {\n"
14826                "}\n"
14827                "int j   = 2;\n"
14828                "int big = 10000;",
14829                Alignment);
14830   verifyFormat("int j = 7;\n"
14831                "for (int k = 0; k < N; ++k) {\n"
14832                "}\n"
14833                "int j   = 2;\n"
14834                "int big = 10000;\n"
14835                "}",
14836                Alignment);
14837   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14838   verifyFormat("int i = 1;\n"
14839                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14840                "    = someLooooooooooooooooongFunction();\n"
14841                "int j = 2;",
14842                Alignment);
14843   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14844   verifyFormat("int i = 1;\n"
14845                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14846                "    someLooooooooooooooooongFunction();\n"
14847                "int j = 2;",
14848                Alignment);
14849 
14850   verifyFormat("auto lambda = []() {\n"
14851                "  auto i = 0;\n"
14852                "  return 0;\n"
14853                "};\n"
14854                "int i  = 0;\n"
14855                "auto v = type{\n"
14856                "    i = 1,   //\n"
14857                "    (i = 2), //\n"
14858                "    i = 3    //\n"
14859                "};",
14860                Alignment);
14861 
14862   verifyFormat(
14863       "int i      = 1;\n"
14864       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14865       "                          loooooooooooooooooooooongParameterB);\n"
14866       "int j      = 2;",
14867       Alignment);
14868 
14869   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
14870                "          typename B   = very_long_type_name_1,\n"
14871                "          typename T_2 = very_long_type_name_2>\n"
14872                "auto foo() {}\n",
14873                Alignment);
14874   verifyFormat("int a, b = 1;\n"
14875                "int c  = 2;\n"
14876                "int dd = 3;\n",
14877                Alignment);
14878   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
14879                "float b[1][] = {{3.f}};\n",
14880                Alignment);
14881   verifyFormat("for (int i = 0; i < 1; i++)\n"
14882                "  int x = 1;\n",
14883                Alignment);
14884   verifyFormat("for (i = 0; i < 1; i++)\n"
14885                "  x = 1;\n"
14886                "y = 1;\n",
14887                Alignment);
14888 
14889   Alignment.ReflowComments = true;
14890   Alignment.ColumnLimit = 50;
14891   EXPECT_EQ("int x   = 0;\n"
14892             "int yy  = 1; /// specificlennospace\n"
14893             "int zzz = 2;\n",
14894             format("int x   = 0;\n"
14895                    "int yy  = 1; ///specificlennospace\n"
14896                    "int zzz = 2;\n",
14897                    Alignment));
14898 }
14899 
14900 TEST_F(FormatTest, AlignConsecutiveBitFields) {
14901   FormatStyle Alignment = getLLVMStyle();
14902   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
14903   verifyFormat("int const a     : 5;\n"
14904                "int oneTwoThree : 23;",
14905                Alignment);
14906 
14907   // Initializers are allowed starting with c++2a
14908   verifyFormat("int const a     : 5 = 1;\n"
14909                "int oneTwoThree : 23 = 0;",
14910                Alignment);
14911 
14912   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14913   verifyFormat("int const a           : 5;\n"
14914                "int       oneTwoThree : 23;",
14915                Alignment);
14916 
14917   verifyFormat("int const a           : 5;  // comment\n"
14918                "int       oneTwoThree : 23; // comment",
14919                Alignment);
14920 
14921   verifyFormat("int const a           : 5 = 1;\n"
14922                "int       oneTwoThree : 23 = 0;",
14923                Alignment);
14924 
14925   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14926   verifyFormat("int const a           : 5  = 1;\n"
14927                "int       oneTwoThree : 23 = 0;",
14928                Alignment);
14929   verifyFormat("int const a           : 5  = {1};\n"
14930                "int       oneTwoThree : 23 = 0;",
14931                Alignment);
14932 
14933   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
14934   verifyFormat("int const a          :5;\n"
14935                "int       oneTwoThree:23;",
14936                Alignment);
14937 
14938   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
14939   verifyFormat("int const a           :5;\n"
14940                "int       oneTwoThree :23;",
14941                Alignment);
14942 
14943   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
14944   verifyFormat("int const a          : 5;\n"
14945                "int       oneTwoThree: 23;",
14946                Alignment);
14947 
14948   // Known limitations: ':' is only recognized as a bitfield colon when
14949   // followed by a number.
14950   /*
14951   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
14952                "int a           : 5;",
14953                Alignment);
14954   */
14955 }
14956 
14957 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
14958   FormatStyle Alignment = getLLVMStyle();
14959   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14960   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
14961   Alignment.PointerAlignment = FormatStyle::PAS_Right;
14962   verifyFormat("float const a = 5;\n"
14963                "int oneTwoThree = 123;",
14964                Alignment);
14965   verifyFormat("int a = 5;\n"
14966                "float const oneTwoThree = 123;",
14967                Alignment);
14968 
14969   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14970   verifyFormat("float const a = 5;\n"
14971                "int         oneTwoThree = 123;",
14972                Alignment);
14973   verifyFormat("int         a = method();\n"
14974                "float const oneTwoThree = 133;",
14975                Alignment);
14976   verifyFormat("int i = 1, j = 10;\n"
14977                "something = 2000;",
14978                Alignment);
14979   verifyFormat("something = 2000;\n"
14980                "int i = 1, j = 10;\n",
14981                Alignment);
14982   verifyFormat("float      something = 2000;\n"
14983                "double     another = 911;\n"
14984                "int        i = 1, j = 10;\n"
14985                "const int *oneMore = 1;\n"
14986                "unsigned   i = 2;",
14987                Alignment);
14988   verifyFormat("float a = 5;\n"
14989                "int   one = 1;\n"
14990                "method();\n"
14991                "const double       oneTwoThree = 123;\n"
14992                "const unsigned int oneTwo = 12;",
14993                Alignment);
14994   verifyFormat("int      oneTwoThree{0}; // comment\n"
14995                "unsigned oneTwo;         // comment",
14996                Alignment);
14997   verifyFormat("unsigned int       *a;\n"
14998                "int                *b;\n"
14999                "unsigned int Const *c;\n"
15000                "unsigned int const *d;\n"
15001                "unsigned int Const &e;\n"
15002                "unsigned int const &f;",
15003                Alignment);
15004   verifyFormat("Const unsigned int *c;\n"
15005                "const unsigned int *d;\n"
15006                "Const unsigned int &e;\n"
15007                "const unsigned int &f;\n"
15008                "const unsigned      g;\n"
15009                "Const unsigned      h;",
15010                Alignment);
15011   EXPECT_EQ("float const a = 5;\n"
15012             "\n"
15013             "int oneTwoThree = 123;",
15014             format("float const   a = 5;\n"
15015                    "\n"
15016                    "int           oneTwoThree= 123;",
15017                    Alignment));
15018   EXPECT_EQ("float a = 5;\n"
15019             "int   one = 1;\n"
15020             "\n"
15021             "unsigned oneTwoThree = 123;",
15022             format("float    a = 5;\n"
15023                    "int      one = 1;\n"
15024                    "\n"
15025                    "unsigned oneTwoThree = 123;",
15026                    Alignment));
15027   EXPECT_EQ("float a = 5;\n"
15028             "int   one = 1;\n"
15029             "\n"
15030             "unsigned oneTwoThree = 123;\n"
15031             "int      oneTwo = 12;",
15032             format("float    a = 5;\n"
15033                    "int one = 1;\n"
15034                    "\n"
15035                    "unsigned oneTwoThree = 123;\n"
15036                    "int oneTwo = 12;",
15037                    Alignment));
15038   // Function prototype alignment
15039   verifyFormat("int    a();\n"
15040                "double b();",
15041                Alignment);
15042   verifyFormat("int    a(int x);\n"
15043                "double b();",
15044                Alignment);
15045   unsigned OldColumnLimit = Alignment.ColumnLimit;
15046   // We need to set ColumnLimit to zero, in order to stress nested alignments,
15047   // otherwise the function parameters will be re-flowed onto a single line.
15048   Alignment.ColumnLimit = 0;
15049   EXPECT_EQ("int    a(int   x,\n"
15050             "         float y);\n"
15051             "double b(int    x,\n"
15052             "         double y);",
15053             format("int a(int x,\n"
15054                    " float y);\n"
15055                    "double b(int x,\n"
15056                    " double y);",
15057                    Alignment));
15058   // This ensures that function parameters of function declarations are
15059   // correctly indented when their owning functions are indented.
15060   // The failure case here is for 'double y' to not be indented enough.
15061   EXPECT_EQ("double a(int x);\n"
15062             "int    b(int    y,\n"
15063             "         double z);",
15064             format("double a(int x);\n"
15065                    "int b(int y,\n"
15066                    " double z);",
15067                    Alignment));
15068   // Set ColumnLimit low so that we induce wrapping immediately after
15069   // the function name and opening paren.
15070   Alignment.ColumnLimit = 13;
15071   verifyFormat("int function(\n"
15072                "    int  x,\n"
15073                "    bool y);",
15074                Alignment);
15075   Alignment.ColumnLimit = OldColumnLimit;
15076   // Ensure function pointers don't screw up recursive alignment
15077   verifyFormat("int    a(int x, void (*fp)(int y));\n"
15078                "double b();",
15079                Alignment);
15080   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15081   // Ensure recursive alignment is broken by function braces, so that the
15082   // "a = 1" does not align with subsequent assignments inside the function
15083   // body.
15084   verifyFormat("int func(int a = 1) {\n"
15085                "  int b  = 2;\n"
15086                "  int cc = 3;\n"
15087                "}",
15088                Alignment);
15089   verifyFormat("float      something = 2000;\n"
15090                "double     another   = 911;\n"
15091                "int        i = 1, j = 10;\n"
15092                "const int *oneMore = 1;\n"
15093                "unsigned   i       = 2;",
15094                Alignment);
15095   verifyFormat("int      oneTwoThree = {0}; // comment\n"
15096                "unsigned oneTwo      = 0;   // comment",
15097                Alignment);
15098   // Make sure that scope is correctly tracked, in the absence of braces
15099   verifyFormat("for (int i = 0; i < n; i++)\n"
15100                "  j = i;\n"
15101                "double x = 1;\n",
15102                Alignment);
15103   verifyFormat("if (int i = 0)\n"
15104                "  j = i;\n"
15105                "double x = 1;\n",
15106                Alignment);
15107   // Ensure operator[] and operator() are comprehended
15108   verifyFormat("struct test {\n"
15109                "  long long int foo();\n"
15110                "  int           operator[](int a);\n"
15111                "  double        bar();\n"
15112                "};\n",
15113                Alignment);
15114   verifyFormat("struct test {\n"
15115                "  long long int foo();\n"
15116                "  int           operator()(int a);\n"
15117                "  double        bar();\n"
15118                "};\n",
15119                Alignment);
15120 
15121   // PAS_Right
15122   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
15123             "  int const i   = 1;\n"
15124             "  int      *j   = 2;\n"
15125             "  int       big = 10000;\n"
15126             "\n"
15127             "  unsigned oneTwoThree = 123;\n"
15128             "  int      oneTwo      = 12;\n"
15129             "  method();\n"
15130             "  float k  = 2;\n"
15131             "  int   ll = 10000;\n"
15132             "}",
15133             format("void SomeFunction(int parameter= 0) {\n"
15134                    " int const  i= 1;\n"
15135                    "  int *j=2;\n"
15136                    " int big  =  10000;\n"
15137                    "\n"
15138                    "unsigned oneTwoThree  =123;\n"
15139                    "int oneTwo = 12;\n"
15140                    "  method();\n"
15141                    "float k= 2;\n"
15142                    "int ll=10000;\n"
15143                    "}",
15144                    Alignment));
15145   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
15146             "  int const i   = 1;\n"
15147             "  int     **j   = 2, ***k;\n"
15148             "  int      &k   = i;\n"
15149             "  int     &&l   = i + j;\n"
15150             "  int       big = 10000;\n"
15151             "\n"
15152             "  unsigned oneTwoThree = 123;\n"
15153             "  int      oneTwo      = 12;\n"
15154             "  method();\n"
15155             "  float k  = 2;\n"
15156             "  int   ll = 10000;\n"
15157             "}",
15158             format("void SomeFunction(int parameter= 0) {\n"
15159                    " int const  i= 1;\n"
15160                    "  int **j=2,***k;\n"
15161                    "int &k=i;\n"
15162                    "int &&l=i+j;\n"
15163                    " int big  =  10000;\n"
15164                    "\n"
15165                    "unsigned oneTwoThree  =123;\n"
15166                    "int oneTwo = 12;\n"
15167                    "  method();\n"
15168                    "float k= 2;\n"
15169                    "int ll=10000;\n"
15170                    "}",
15171                    Alignment));
15172   // variables are aligned at their name, pointers are at the right most
15173   // position
15174   verifyFormat("int   *a;\n"
15175                "int  **b;\n"
15176                "int ***c;\n"
15177                "int    foobar;\n",
15178                Alignment);
15179 
15180   // PAS_Left
15181   FormatStyle AlignmentLeft = Alignment;
15182   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
15183   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
15184             "  int const i   = 1;\n"
15185             "  int*      j   = 2;\n"
15186             "  int       big = 10000;\n"
15187             "\n"
15188             "  unsigned oneTwoThree = 123;\n"
15189             "  int      oneTwo      = 12;\n"
15190             "  method();\n"
15191             "  float k  = 2;\n"
15192             "  int   ll = 10000;\n"
15193             "}",
15194             format("void SomeFunction(int parameter= 0) {\n"
15195                    " int const  i= 1;\n"
15196                    "  int *j=2;\n"
15197                    " int big  =  10000;\n"
15198                    "\n"
15199                    "unsigned oneTwoThree  =123;\n"
15200                    "int oneTwo = 12;\n"
15201                    "  method();\n"
15202                    "float k= 2;\n"
15203                    "int ll=10000;\n"
15204                    "}",
15205                    AlignmentLeft));
15206   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
15207             "  int const i   = 1;\n"
15208             "  int**     j   = 2;\n"
15209             "  int&      k   = i;\n"
15210             "  int&&     l   = i + j;\n"
15211             "  int       big = 10000;\n"
15212             "\n"
15213             "  unsigned oneTwoThree = 123;\n"
15214             "  int      oneTwo      = 12;\n"
15215             "  method();\n"
15216             "  float k  = 2;\n"
15217             "  int   ll = 10000;\n"
15218             "}",
15219             format("void SomeFunction(int parameter= 0) {\n"
15220                    " int const  i= 1;\n"
15221                    "  int **j=2;\n"
15222                    "int &k=i;\n"
15223                    "int &&l=i+j;\n"
15224                    " int big  =  10000;\n"
15225                    "\n"
15226                    "unsigned oneTwoThree  =123;\n"
15227                    "int oneTwo = 12;\n"
15228                    "  method();\n"
15229                    "float k= 2;\n"
15230                    "int ll=10000;\n"
15231                    "}",
15232                    AlignmentLeft));
15233   // variables are aligned at their name, pointers are at the left most position
15234   verifyFormat("int*   a;\n"
15235                "int**  b;\n"
15236                "int*** c;\n"
15237                "int    foobar;\n",
15238                AlignmentLeft);
15239 
15240   // PAS_Middle
15241   FormatStyle AlignmentMiddle = Alignment;
15242   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
15243   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
15244             "  int const i   = 1;\n"
15245             "  int *     j   = 2;\n"
15246             "  int       big = 10000;\n"
15247             "\n"
15248             "  unsigned oneTwoThree = 123;\n"
15249             "  int      oneTwo      = 12;\n"
15250             "  method();\n"
15251             "  float k  = 2;\n"
15252             "  int   ll = 10000;\n"
15253             "}",
15254             format("void SomeFunction(int parameter= 0) {\n"
15255                    " int const  i= 1;\n"
15256                    "  int *j=2;\n"
15257                    " int big  =  10000;\n"
15258                    "\n"
15259                    "unsigned oneTwoThree  =123;\n"
15260                    "int oneTwo = 12;\n"
15261                    "  method();\n"
15262                    "float k= 2;\n"
15263                    "int ll=10000;\n"
15264                    "}",
15265                    AlignmentMiddle));
15266   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
15267             "  int const i   = 1;\n"
15268             "  int **    j   = 2, ***k;\n"
15269             "  int &     k   = i;\n"
15270             "  int &&    l   = i + j;\n"
15271             "  int       big = 10000;\n"
15272             "\n"
15273             "  unsigned oneTwoThree = 123;\n"
15274             "  int      oneTwo      = 12;\n"
15275             "  method();\n"
15276             "  float k  = 2;\n"
15277             "  int   ll = 10000;\n"
15278             "}",
15279             format("void SomeFunction(int parameter= 0) {\n"
15280                    " int const  i= 1;\n"
15281                    "  int **j=2,***k;\n"
15282                    "int &k=i;\n"
15283                    "int &&l=i+j;\n"
15284                    " int big  =  10000;\n"
15285                    "\n"
15286                    "unsigned oneTwoThree  =123;\n"
15287                    "int oneTwo = 12;\n"
15288                    "  method();\n"
15289                    "float k= 2;\n"
15290                    "int ll=10000;\n"
15291                    "}",
15292                    AlignmentMiddle));
15293   // variables are aligned at their name, pointers are in the middle
15294   verifyFormat("int *   a;\n"
15295                "int *   b;\n"
15296                "int *** c;\n"
15297                "int     foobar;\n",
15298                AlignmentMiddle);
15299 
15300   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15301   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
15302   verifyFormat("#define A \\\n"
15303                "  int       aaaa = 12; \\\n"
15304                "  float     b = 23; \\\n"
15305                "  const int ccc = 234; \\\n"
15306                "  unsigned  dddddddddd = 2345;",
15307                Alignment);
15308   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
15309   verifyFormat("#define A              \\\n"
15310                "  int       aaaa = 12; \\\n"
15311                "  float     b = 23;    \\\n"
15312                "  const int ccc = 234; \\\n"
15313                "  unsigned  dddddddddd = 2345;",
15314                Alignment);
15315   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
15316   Alignment.ColumnLimit = 30;
15317   verifyFormat("#define A                    \\\n"
15318                "  int       aaaa = 12;       \\\n"
15319                "  float     b = 23;          \\\n"
15320                "  const int ccc = 234;       \\\n"
15321                "  int       dddddddddd = 2345;",
15322                Alignment);
15323   Alignment.ColumnLimit = 80;
15324   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
15325                "k = 4, int l = 5,\n"
15326                "                  int m = 6) {\n"
15327                "  const int j = 10;\n"
15328                "  otherThing = 1;\n"
15329                "}",
15330                Alignment);
15331   verifyFormat("void SomeFunction(int parameter = 0) {\n"
15332                "  int const i = 1;\n"
15333                "  int      *j = 2;\n"
15334                "  int       big = 10000;\n"
15335                "}",
15336                Alignment);
15337   verifyFormat("class C {\n"
15338                "public:\n"
15339                "  int          i = 1;\n"
15340                "  virtual void f() = 0;\n"
15341                "};",
15342                Alignment);
15343   verifyFormat("float i = 1;\n"
15344                "if (SomeType t = getSomething()) {\n"
15345                "}\n"
15346                "const unsigned j = 2;\n"
15347                "int            big = 10000;",
15348                Alignment);
15349   verifyFormat("float j = 7;\n"
15350                "for (int k = 0; k < N; ++k) {\n"
15351                "}\n"
15352                "unsigned j = 2;\n"
15353                "int      big = 10000;\n"
15354                "}",
15355                Alignment);
15356   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15357   verifyFormat("float              i = 1;\n"
15358                "LooooooooooongType loooooooooooooooooooooongVariable\n"
15359                "    = someLooooooooooooooooongFunction();\n"
15360                "int j = 2;",
15361                Alignment);
15362   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
15363   verifyFormat("int                i = 1;\n"
15364                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
15365                "    someLooooooooooooooooongFunction();\n"
15366                "int j = 2;",
15367                Alignment);
15368 
15369   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15370   verifyFormat("auto lambda = []() {\n"
15371                "  auto  ii = 0;\n"
15372                "  float j  = 0;\n"
15373                "  return 0;\n"
15374                "};\n"
15375                "int   i  = 0;\n"
15376                "float i2 = 0;\n"
15377                "auto  v  = type{\n"
15378                "    i = 1,   //\n"
15379                "    (i = 2), //\n"
15380                "    i = 3    //\n"
15381                "};",
15382                Alignment);
15383   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15384 
15385   verifyFormat(
15386       "int      i = 1;\n"
15387       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
15388       "                          loooooooooooooooooooooongParameterB);\n"
15389       "int      j = 2;",
15390       Alignment);
15391 
15392   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
15393   // We expect declarations and assignments to align, as long as it doesn't
15394   // exceed the column limit, starting a new alignment sequence whenever it
15395   // happens.
15396   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15397   Alignment.ColumnLimit = 30;
15398   verifyFormat("float    ii              = 1;\n"
15399                "unsigned j               = 2;\n"
15400                "int someVerylongVariable = 1;\n"
15401                "AnotherLongType  ll = 123456;\n"
15402                "VeryVeryLongType k  = 2;\n"
15403                "int              myvar = 1;",
15404                Alignment);
15405   Alignment.ColumnLimit = 80;
15406   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15407 
15408   verifyFormat(
15409       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
15410       "          typename LongType, typename B>\n"
15411       "auto foo() {}\n",
15412       Alignment);
15413   verifyFormat("float a, b = 1;\n"
15414                "int   c = 2;\n"
15415                "int   dd = 3;\n",
15416                Alignment);
15417   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
15418                "float b[1][] = {{3.f}};\n",
15419                Alignment);
15420   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15421   verifyFormat("float a, b = 1;\n"
15422                "int   c  = 2;\n"
15423                "int   dd = 3;\n",
15424                Alignment);
15425   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
15426                "float b[1][] = {{3.f}};\n",
15427                Alignment);
15428   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15429 
15430   Alignment.ColumnLimit = 30;
15431   Alignment.BinPackParameters = false;
15432   verifyFormat("void foo(float     a,\n"
15433                "         float     b,\n"
15434                "         int       c,\n"
15435                "         uint32_t *d) {\n"
15436                "  int   *e = 0;\n"
15437                "  float  f = 0;\n"
15438                "  double g = 0;\n"
15439                "}\n"
15440                "void bar(ino_t     a,\n"
15441                "         int       b,\n"
15442                "         uint32_t *c,\n"
15443                "         bool      d) {}\n",
15444                Alignment);
15445   Alignment.BinPackParameters = true;
15446   Alignment.ColumnLimit = 80;
15447 
15448   // Bug 33507
15449   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
15450   verifyFormat(
15451       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
15452       "  static const Version verVs2017;\n"
15453       "  return true;\n"
15454       "});\n",
15455       Alignment);
15456   Alignment.PointerAlignment = FormatStyle::PAS_Right;
15457 
15458   // See llvm.org/PR35641
15459   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15460   verifyFormat("int func() { //\n"
15461                "  int      b;\n"
15462                "  unsigned c;\n"
15463                "}",
15464                Alignment);
15465 
15466   // See PR37175
15467   FormatStyle Style = getMozillaStyle();
15468   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15469   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
15470             "foo(int a);",
15471             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
15472 
15473   Alignment.PointerAlignment = FormatStyle::PAS_Left;
15474   verifyFormat("unsigned int*       a;\n"
15475                "int*                b;\n"
15476                "unsigned int Const* c;\n"
15477                "unsigned int const* d;\n"
15478                "unsigned int Const& e;\n"
15479                "unsigned int const& f;",
15480                Alignment);
15481   verifyFormat("Const unsigned int* c;\n"
15482                "const unsigned int* d;\n"
15483                "Const unsigned int& e;\n"
15484                "const unsigned int& f;\n"
15485                "const unsigned      g;\n"
15486                "Const unsigned      h;",
15487                Alignment);
15488 
15489   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
15490   verifyFormat("unsigned int *       a;\n"
15491                "int *                b;\n"
15492                "unsigned int Const * c;\n"
15493                "unsigned int const * d;\n"
15494                "unsigned int Const & e;\n"
15495                "unsigned int const & f;",
15496                Alignment);
15497   verifyFormat("Const unsigned int * c;\n"
15498                "const unsigned int * d;\n"
15499                "Const unsigned int & e;\n"
15500                "const unsigned int & f;\n"
15501                "const unsigned       g;\n"
15502                "Const unsigned       h;",
15503                Alignment);
15504 }
15505 
15506 TEST_F(FormatTest, AlignWithLineBreaks) {
15507   auto Style = getLLVMStyleWithColumns(120);
15508 
15509   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
15510   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
15511   verifyFormat("void foo() {\n"
15512                "  int myVar = 5;\n"
15513                "  double x = 3.14;\n"
15514                "  auto str = \"Hello \"\n"
15515                "             \"World\";\n"
15516                "  auto s = \"Hello \"\n"
15517                "           \"Again\";\n"
15518                "}",
15519                Style);
15520 
15521   // clang-format off
15522   verifyFormat("void foo() {\n"
15523                "  const int capacityBefore = Entries.capacity();\n"
15524                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
15525                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
15526                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
15527                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
15528                "}",
15529                Style);
15530   // clang-format on
15531 
15532   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15533   verifyFormat("void foo() {\n"
15534                "  int myVar = 5;\n"
15535                "  double x  = 3.14;\n"
15536                "  auto str  = \"Hello \"\n"
15537                "              \"World\";\n"
15538                "  auto s    = \"Hello \"\n"
15539                "              \"Again\";\n"
15540                "}",
15541                Style);
15542 
15543   // clang-format off
15544   verifyFormat("void foo() {\n"
15545                "  const int capacityBefore = Entries.capacity();\n"
15546                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
15547                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
15548                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
15549                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
15550                "}",
15551                Style);
15552   // clang-format on
15553 
15554   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15555   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15556   verifyFormat("void foo() {\n"
15557                "  int    myVar = 5;\n"
15558                "  double x = 3.14;\n"
15559                "  auto   str = \"Hello \"\n"
15560                "               \"World\";\n"
15561                "  auto   s = \"Hello \"\n"
15562                "             \"Again\";\n"
15563                "}",
15564                Style);
15565 
15566   // clang-format off
15567   verifyFormat("void foo() {\n"
15568                "  const int  capacityBefore = Entries.capacity();\n"
15569                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
15570                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
15571                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
15572                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
15573                "}",
15574                Style);
15575   // clang-format on
15576 
15577   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15578   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15579 
15580   verifyFormat("void foo() {\n"
15581                "  int    myVar = 5;\n"
15582                "  double x     = 3.14;\n"
15583                "  auto   str   = \"Hello \"\n"
15584                "                 \"World\";\n"
15585                "  auto   s     = \"Hello \"\n"
15586                "                 \"Again\";\n"
15587                "}",
15588                Style);
15589 
15590   // clang-format off
15591   verifyFormat("void foo() {\n"
15592                "  const int  capacityBefore = Entries.capacity();\n"
15593                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
15594                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
15595                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
15596                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
15597                "}",
15598                Style);
15599   // clang-format on
15600 }
15601 
15602 TEST_F(FormatTest, LinuxBraceBreaking) {
15603   FormatStyle LinuxBraceStyle = getLLVMStyle();
15604   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
15605   verifyFormat("namespace a\n"
15606                "{\n"
15607                "class A\n"
15608                "{\n"
15609                "  void f()\n"
15610                "  {\n"
15611                "    if (true) {\n"
15612                "      a();\n"
15613                "      b();\n"
15614                "    } else {\n"
15615                "      a();\n"
15616                "    }\n"
15617                "  }\n"
15618                "  void g() { return; }\n"
15619                "};\n"
15620                "struct B {\n"
15621                "  int x;\n"
15622                "};\n"
15623                "} // namespace a\n",
15624                LinuxBraceStyle);
15625   verifyFormat("enum X {\n"
15626                "  Y = 0,\n"
15627                "}\n",
15628                LinuxBraceStyle);
15629   verifyFormat("struct S {\n"
15630                "  int Type;\n"
15631                "  union {\n"
15632                "    int x;\n"
15633                "    double y;\n"
15634                "  } Value;\n"
15635                "  class C\n"
15636                "  {\n"
15637                "    MyFavoriteType Value;\n"
15638                "  } Class;\n"
15639                "}\n",
15640                LinuxBraceStyle);
15641 }
15642 
15643 TEST_F(FormatTest, MozillaBraceBreaking) {
15644   FormatStyle MozillaBraceStyle = getLLVMStyle();
15645   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
15646   MozillaBraceStyle.FixNamespaceComments = false;
15647   verifyFormat("namespace a {\n"
15648                "class A\n"
15649                "{\n"
15650                "  void f()\n"
15651                "  {\n"
15652                "    if (true) {\n"
15653                "      a();\n"
15654                "      b();\n"
15655                "    }\n"
15656                "  }\n"
15657                "  void g() { return; }\n"
15658                "};\n"
15659                "enum E\n"
15660                "{\n"
15661                "  A,\n"
15662                "  // foo\n"
15663                "  B,\n"
15664                "  C\n"
15665                "};\n"
15666                "struct B\n"
15667                "{\n"
15668                "  int x;\n"
15669                "};\n"
15670                "}\n",
15671                MozillaBraceStyle);
15672   verifyFormat("struct S\n"
15673                "{\n"
15674                "  int Type;\n"
15675                "  union\n"
15676                "  {\n"
15677                "    int x;\n"
15678                "    double y;\n"
15679                "  } Value;\n"
15680                "  class C\n"
15681                "  {\n"
15682                "    MyFavoriteType Value;\n"
15683                "  } Class;\n"
15684                "}\n",
15685                MozillaBraceStyle);
15686 }
15687 
15688 TEST_F(FormatTest, StroustrupBraceBreaking) {
15689   FormatStyle StroustrupBraceStyle = getLLVMStyle();
15690   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
15691   verifyFormat("namespace a {\n"
15692                "class A {\n"
15693                "  void f()\n"
15694                "  {\n"
15695                "    if (true) {\n"
15696                "      a();\n"
15697                "      b();\n"
15698                "    }\n"
15699                "  }\n"
15700                "  void g() { return; }\n"
15701                "};\n"
15702                "struct B {\n"
15703                "  int x;\n"
15704                "};\n"
15705                "} // namespace a\n",
15706                StroustrupBraceStyle);
15707 
15708   verifyFormat("void foo()\n"
15709                "{\n"
15710                "  if (a) {\n"
15711                "    a();\n"
15712                "  }\n"
15713                "  else {\n"
15714                "    b();\n"
15715                "  }\n"
15716                "}\n",
15717                StroustrupBraceStyle);
15718 
15719   verifyFormat("#ifdef _DEBUG\n"
15720                "int foo(int i = 0)\n"
15721                "#else\n"
15722                "int foo(int i = 5)\n"
15723                "#endif\n"
15724                "{\n"
15725                "  return i;\n"
15726                "}",
15727                StroustrupBraceStyle);
15728 
15729   verifyFormat("void foo() {}\n"
15730                "void bar()\n"
15731                "#ifdef _DEBUG\n"
15732                "{\n"
15733                "  foo();\n"
15734                "}\n"
15735                "#else\n"
15736                "{\n"
15737                "}\n"
15738                "#endif",
15739                StroustrupBraceStyle);
15740 
15741   verifyFormat("void foobar() { int i = 5; }\n"
15742                "#ifdef _DEBUG\n"
15743                "void bar() {}\n"
15744                "#else\n"
15745                "void bar() { foobar(); }\n"
15746                "#endif",
15747                StroustrupBraceStyle);
15748 }
15749 
15750 TEST_F(FormatTest, AllmanBraceBreaking) {
15751   FormatStyle AllmanBraceStyle = getLLVMStyle();
15752   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
15753 
15754   EXPECT_EQ("namespace a\n"
15755             "{\n"
15756             "void f();\n"
15757             "void g();\n"
15758             "} // namespace a\n",
15759             format("namespace a\n"
15760                    "{\n"
15761                    "void f();\n"
15762                    "void g();\n"
15763                    "}\n",
15764                    AllmanBraceStyle));
15765 
15766   verifyFormat("namespace a\n"
15767                "{\n"
15768                "class A\n"
15769                "{\n"
15770                "  void f()\n"
15771                "  {\n"
15772                "    if (true)\n"
15773                "    {\n"
15774                "      a();\n"
15775                "      b();\n"
15776                "    }\n"
15777                "  }\n"
15778                "  void g() { return; }\n"
15779                "};\n"
15780                "struct B\n"
15781                "{\n"
15782                "  int x;\n"
15783                "};\n"
15784                "union C\n"
15785                "{\n"
15786                "};\n"
15787                "} // namespace a",
15788                AllmanBraceStyle);
15789 
15790   verifyFormat("void f()\n"
15791                "{\n"
15792                "  if (true)\n"
15793                "  {\n"
15794                "    a();\n"
15795                "  }\n"
15796                "  else if (false)\n"
15797                "  {\n"
15798                "    b();\n"
15799                "  }\n"
15800                "  else\n"
15801                "  {\n"
15802                "    c();\n"
15803                "  }\n"
15804                "}\n",
15805                AllmanBraceStyle);
15806 
15807   verifyFormat("void f()\n"
15808                "{\n"
15809                "  for (int i = 0; i < 10; ++i)\n"
15810                "  {\n"
15811                "    a();\n"
15812                "  }\n"
15813                "  while (false)\n"
15814                "  {\n"
15815                "    b();\n"
15816                "  }\n"
15817                "  do\n"
15818                "  {\n"
15819                "    c();\n"
15820                "  } while (false)\n"
15821                "}\n",
15822                AllmanBraceStyle);
15823 
15824   verifyFormat("void f(int a)\n"
15825                "{\n"
15826                "  switch (a)\n"
15827                "  {\n"
15828                "  case 0:\n"
15829                "    break;\n"
15830                "  case 1:\n"
15831                "  {\n"
15832                "    break;\n"
15833                "  }\n"
15834                "  case 2:\n"
15835                "  {\n"
15836                "  }\n"
15837                "  break;\n"
15838                "  default:\n"
15839                "    break;\n"
15840                "  }\n"
15841                "}\n",
15842                AllmanBraceStyle);
15843 
15844   verifyFormat("enum X\n"
15845                "{\n"
15846                "  Y = 0,\n"
15847                "}\n",
15848                AllmanBraceStyle);
15849   verifyFormat("enum X\n"
15850                "{\n"
15851                "  Y = 0\n"
15852                "}\n",
15853                AllmanBraceStyle);
15854 
15855   verifyFormat("@interface BSApplicationController ()\n"
15856                "{\n"
15857                "@private\n"
15858                "  id _extraIvar;\n"
15859                "}\n"
15860                "@end\n",
15861                AllmanBraceStyle);
15862 
15863   verifyFormat("#ifdef _DEBUG\n"
15864                "int foo(int i = 0)\n"
15865                "#else\n"
15866                "int foo(int i = 5)\n"
15867                "#endif\n"
15868                "{\n"
15869                "  return i;\n"
15870                "}",
15871                AllmanBraceStyle);
15872 
15873   verifyFormat("void foo() {}\n"
15874                "void bar()\n"
15875                "#ifdef _DEBUG\n"
15876                "{\n"
15877                "  foo();\n"
15878                "}\n"
15879                "#else\n"
15880                "{\n"
15881                "}\n"
15882                "#endif",
15883                AllmanBraceStyle);
15884 
15885   verifyFormat("void foobar() { int i = 5; }\n"
15886                "#ifdef _DEBUG\n"
15887                "void bar() {}\n"
15888                "#else\n"
15889                "void bar() { foobar(); }\n"
15890                "#endif",
15891                AllmanBraceStyle);
15892 
15893   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
15894             FormatStyle::SLS_All);
15895 
15896   verifyFormat("[](int i) { return i + 2; };\n"
15897                "[](int i, int j)\n"
15898                "{\n"
15899                "  auto x = i + j;\n"
15900                "  auto y = i * j;\n"
15901                "  return x ^ y;\n"
15902                "};\n"
15903                "void foo()\n"
15904                "{\n"
15905                "  auto shortLambda = [](int i) { return i + 2; };\n"
15906                "  auto longLambda = [](int i, int j)\n"
15907                "  {\n"
15908                "    auto x = i + j;\n"
15909                "    auto y = i * j;\n"
15910                "    return x ^ y;\n"
15911                "  };\n"
15912                "}",
15913                AllmanBraceStyle);
15914 
15915   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
15916 
15917   verifyFormat("[](int i)\n"
15918                "{\n"
15919                "  return i + 2;\n"
15920                "};\n"
15921                "[](int i, int j)\n"
15922                "{\n"
15923                "  auto x = i + j;\n"
15924                "  auto y = i * j;\n"
15925                "  return x ^ y;\n"
15926                "};\n"
15927                "void foo()\n"
15928                "{\n"
15929                "  auto shortLambda = [](int i)\n"
15930                "  {\n"
15931                "    return i + 2;\n"
15932                "  };\n"
15933                "  auto longLambda = [](int i, int j)\n"
15934                "  {\n"
15935                "    auto x = i + j;\n"
15936                "    auto y = i * j;\n"
15937                "    return x ^ y;\n"
15938                "  };\n"
15939                "}",
15940                AllmanBraceStyle);
15941 
15942   // Reset
15943   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
15944 
15945   // This shouldn't affect ObjC blocks..
15946   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
15947                "  // ...\n"
15948                "  int i;\n"
15949                "}];",
15950                AllmanBraceStyle);
15951   verifyFormat("void (^block)(void) = ^{\n"
15952                "  // ...\n"
15953                "  int i;\n"
15954                "};",
15955                AllmanBraceStyle);
15956   // .. or dict literals.
15957   verifyFormat("void f()\n"
15958                "{\n"
15959                "  // ...\n"
15960                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
15961                "}",
15962                AllmanBraceStyle);
15963   verifyFormat("void f()\n"
15964                "{\n"
15965                "  // ...\n"
15966                "  [object someMethod:@{a : @\"b\"}];\n"
15967                "}",
15968                AllmanBraceStyle);
15969   verifyFormat("int f()\n"
15970                "{ // comment\n"
15971                "  return 42;\n"
15972                "}",
15973                AllmanBraceStyle);
15974 
15975   AllmanBraceStyle.ColumnLimit = 19;
15976   verifyFormat("void f() { int i; }", AllmanBraceStyle);
15977   AllmanBraceStyle.ColumnLimit = 18;
15978   verifyFormat("void f()\n"
15979                "{\n"
15980                "  int i;\n"
15981                "}",
15982                AllmanBraceStyle);
15983   AllmanBraceStyle.ColumnLimit = 80;
15984 
15985   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
15986   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
15987       FormatStyle::SIS_WithoutElse;
15988   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
15989   verifyFormat("void f(bool b)\n"
15990                "{\n"
15991                "  if (b)\n"
15992                "  {\n"
15993                "    return;\n"
15994                "  }\n"
15995                "}\n",
15996                BreakBeforeBraceShortIfs);
15997   verifyFormat("void f(bool b)\n"
15998                "{\n"
15999                "  if constexpr (b)\n"
16000                "  {\n"
16001                "    return;\n"
16002                "  }\n"
16003                "}\n",
16004                BreakBeforeBraceShortIfs);
16005   verifyFormat("void f(bool b)\n"
16006                "{\n"
16007                "  if CONSTEXPR (b)\n"
16008                "  {\n"
16009                "    return;\n"
16010                "  }\n"
16011                "}\n",
16012                BreakBeforeBraceShortIfs);
16013   verifyFormat("void f(bool b)\n"
16014                "{\n"
16015                "  if (b) return;\n"
16016                "}\n",
16017                BreakBeforeBraceShortIfs);
16018   verifyFormat("void f(bool b)\n"
16019                "{\n"
16020                "  if constexpr (b) return;\n"
16021                "}\n",
16022                BreakBeforeBraceShortIfs);
16023   verifyFormat("void f(bool b)\n"
16024                "{\n"
16025                "  if CONSTEXPR (b) return;\n"
16026                "}\n",
16027                BreakBeforeBraceShortIfs);
16028   verifyFormat("void f(bool b)\n"
16029                "{\n"
16030                "  while (b)\n"
16031                "  {\n"
16032                "    return;\n"
16033                "  }\n"
16034                "}\n",
16035                BreakBeforeBraceShortIfs);
16036 }
16037 
16038 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
16039   FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
16040   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
16041 
16042   // Make a few changes to the style for testing purposes
16043   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
16044       FormatStyle::SFS_Empty;
16045   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
16046   WhitesmithsBraceStyle.ColumnLimit = 0;
16047 
16048   // FIXME: this test case can't decide whether there should be a blank line
16049   // after the ~D() line or not. It adds one if one doesn't exist in the test
16050   // and it removes the line if one exists.
16051   /*
16052   verifyFormat("class A;\n"
16053                "namespace B\n"
16054                "  {\n"
16055                "class C;\n"
16056                "// Comment\n"
16057                "class D\n"
16058                "  {\n"
16059                "public:\n"
16060                "  D();\n"
16061                "  ~D() {}\n"
16062                "private:\n"
16063                "  enum E\n"
16064                "    {\n"
16065                "    F\n"
16066                "    }\n"
16067                "  };\n"
16068                "  } // namespace B\n",
16069                WhitesmithsBraceStyle);
16070   */
16071 
16072   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
16073   verifyFormat("namespace a\n"
16074                "  {\n"
16075                "class A\n"
16076                "  {\n"
16077                "  void f()\n"
16078                "    {\n"
16079                "    if (true)\n"
16080                "      {\n"
16081                "      a();\n"
16082                "      b();\n"
16083                "      }\n"
16084                "    }\n"
16085                "  void g()\n"
16086                "    {\n"
16087                "    return;\n"
16088                "    }\n"
16089                "  };\n"
16090                "struct B\n"
16091                "  {\n"
16092                "  int x;\n"
16093                "  };\n"
16094                "  } // namespace a",
16095                WhitesmithsBraceStyle);
16096 
16097   verifyFormat("namespace a\n"
16098                "  {\n"
16099                "namespace b\n"
16100                "  {\n"
16101                "class A\n"
16102                "  {\n"
16103                "  void f()\n"
16104                "    {\n"
16105                "    if (true)\n"
16106                "      {\n"
16107                "      a();\n"
16108                "      b();\n"
16109                "      }\n"
16110                "    }\n"
16111                "  void g()\n"
16112                "    {\n"
16113                "    return;\n"
16114                "    }\n"
16115                "  };\n"
16116                "struct B\n"
16117                "  {\n"
16118                "  int x;\n"
16119                "  };\n"
16120                "  } // namespace b\n"
16121                "  } // namespace a",
16122                WhitesmithsBraceStyle);
16123 
16124   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
16125   verifyFormat("namespace a\n"
16126                "  {\n"
16127                "namespace b\n"
16128                "  {\n"
16129                "  class A\n"
16130                "    {\n"
16131                "    void f()\n"
16132                "      {\n"
16133                "      if (true)\n"
16134                "        {\n"
16135                "        a();\n"
16136                "        b();\n"
16137                "        }\n"
16138                "      }\n"
16139                "    void g()\n"
16140                "      {\n"
16141                "      return;\n"
16142                "      }\n"
16143                "    };\n"
16144                "  struct B\n"
16145                "    {\n"
16146                "    int x;\n"
16147                "    };\n"
16148                "  } // namespace b\n"
16149                "  } // namespace a",
16150                WhitesmithsBraceStyle);
16151 
16152   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
16153   verifyFormat("namespace a\n"
16154                "  {\n"
16155                "  namespace b\n"
16156                "    {\n"
16157                "    class A\n"
16158                "      {\n"
16159                "      void f()\n"
16160                "        {\n"
16161                "        if (true)\n"
16162                "          {\n"
16163                "          a();\n"
16164                "          b();\n"
16165                "          }\n"
16166                "        }\n"
16167                "      void g()\n"
16168                "        {\n"
16169                "        return;\n"
16170                "        }\n"
16171                "      };\n"
16172                "    struct B\n"
16173                "      {\n"
16174                "      int x;\n"
16175                "      };\n"
16176                "    } // namespace b\n"
16177                "  }   // namespace a",
16178                WhitesmithsBraceStyle);
16179 
16180   verifyFormat("void f()\n"
16181                "  {\n"
16182                "  if (true)\n"
16183                "    {\n"
16184                "    a();\n"
16185                "    }\n"
16186                "  else if (false)\n"
16187                "    {\n"
16188                "    b();\n"
16189                "    }\n"
16190                "  else\n"
16191                "    {\n"
16192                "    c();\n"
16193                "    }\n"
16194                "  }\n",
16195                WhitesmithsBraceStyle);
16196 
16197   verifyFormat("void f()\n"
16198                "  {\n"
16199                "  for (int i = 0; i < 10; ++i)\n"
16200                "    {\n"
16201                "    a();\n"
16202                "    }\n"
16203                "  while (false)\n"
16204                "    {\n"
16205                "    b();\n"
16206                "    }\n"
16207                "  do\n"
16208                "    {\n"
16209                "    c();\n"
16210                "    } while (false)\n"
16211                "  }\n",
16212                WhitesmithsBraceStyle);
16213 
16214   WhitesmithsBraceStyle.IndentCaseLabels = true;
16215   verifyFormat("void switchTest1(int a)\n"
16216                "  {\n"
16217                "  switch (a)\n"
16218                "    {\n"
16219                "    case 2:\n"
16220                "      {\n"
16221                "      }\n"
16222                "      break;\n"
16223                "    }\n"
16224                "  }\n",
16225                WhitesmithsBraceStyle);
16226 
16227   verifyFormat("void switchTest2(int a)\n"
16228                "  {\n"
16229                "  switch (a)\n"
16230                "    {\n"
16231                "    case 0:\n"
16232                "      break;\n"
16233                "    case 1:\n"
16234                "      {\n"
16235                "      break;\n"
16236                "      }\n"
16237                "    case 2:\n"
16238                "      {\n"
16239                "      }\n"
16240                "      break;\n"
16241                "    default:\n"
16242                "      break;\n"
16243                "    }\n"
16244                "  }\n",
16245                WhitesmithsBraceStyle);
16246 
16247   verifyFormat("void switchTest3(int a)\n"
16248                "  {\n"
16249                "  switch (a)\n"
16250                "    {\n"
16251                "    case 0:\n"
16252                "      {\n"
16253                "      foo(x);\n"
16254                "      }\n"
16255                "      break;\n"
16256                "    default:\n"
16257                "      {\n"
16258                "      foo(1);\n"
16259                "      }\n"
16260                "      break;\n"
16261                "    }\n"
16262                "  }\n",
16263                WhitesmithsBraceStyle);
16264 
16265   WhitesmithsBraceStyle.IndentCaseLabels = false;
16266 
16267   verifyFormat("void switchTest4(int a)\n"
16268                "  {\n"
16269                "  switch (a)\n"
16270                "    {\n"
16271                "  case 2:\n"
16272                "    {\n"
16273                "    }\n"
16274                "    break;\n"
16275                "    }\n"
16276                "  }\n",
16277                WhitesmithsBraceStyle);
16278 
16279   verifyFormat("void switchTest5(int a)\n"
16280                "  {\n"
16281                "  switch (a)\n"
16282                "    {\n"
16283                "  case 0:\n"
16284                "    break;\n"
16285                "  case 1:\n"
16286                "    {\n"
16287                "    foo();\n"
16288                "    break;\n"
16289                "    }\n"
16290                "  case 2:\n"
16291                "    {\n"
16292                "    }\n"
16293                "    break;\n"
16294                "  default:\n"
16295                "    break;\n"
16296                "    }\n"
16297                "  }\n",
16298                WhitesmithsBraceStyle);
16299 
16300   verifyFormat("void switchTest6(int a)\n"
16301                "  {\n"
16302                "  switch (a)\n"
16303                "    {\n"
16304                "  case 0:\n"
16305                "    {\n"
16306                "    foo(x);\n"
16307                "    }\n"
16308                "    break;\n"
16309                "  default:\n"
16310                "    {\n"
16311                "    foo(1);\n"
16312                "    }\n"
16313                "    break;\n"
16314                "    }\n"
16315                "  }\n",
16316                WhitesmithsBraceStyle);
16317 
16318   verifyFormat("enum X\n"
16319                "  {\n"
16320                "  Y = 0, // testing\n"
16321                "  }\n",
16322                WhitesmithsBraceStyle);
16323 
16324   verifyFormat("enum X\n"
16325                "  {\n"
16326                "  Y = 0\n"
16327                "  }\n",
16328                WhitesmithsBraceStyle);
16329   verifyFormat("enum X\n"
16330                "  {\n"
16331                "  Y = 0,\n"
16332                "  Z = 1\n"
16333                "  };\n",
16334                WhitesmithsBraceStyle);
16335 
16336   verifyFormat("@interface BSApplicationController ()\n"
16337                "  {\n"
16338                "@private\n"
16339                "  id _extraIvar;\n"
16340                "  }\n"
16341                "@end\n",
16342                WhitesmithsBraceStyle);
16343 
16344   verifyFormat("#ifdef _DEBUG\n"
16345                "int foo(int i = 0)\n"
16346                "#else\n"
16347                "int foo(int i = 5)\n"
16348                "#endif\n"
16349                "  {\n"
16350                "  return i;\n"
16351                "  }",
16352                WhitesmithsBraceStyle);
16353 
16354   verifyFormat("void foo() {}\n"
16355                "void bar()\n"
16356                "#ifdef _DEBUG\n"
16357                "  {\n"
16358                "  foo();\n"
16359                "  }\n"
16360                "#else\n"
16361                "  {\n"
16362                "  }\n"
16363                "#endif",
16364                WhitesmithsBraceStyle);
16365 
16366   verifyFormat("void foobar()\n"
16367                "  {\n"
16368                "  int i = 5;\n"
16369                "  }\n"
16370                "#ifdef _DEBUG\n"
16371                "void bar()\n"
16372                "  {\n"
16373                "  }\n"
16374                "#else\n"
16375                "void bar()\n"
16376                "  {\n"
16377                "  foobar();\n"
16378                "  }\n"
16379                "#endif",
16380                WhitesmithsBraceStyle);
16381 
16382   // This shouldn't affect ObjC blocks..
16383   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
16384                "  // ...\n"
16385                "  int i;\n"
16386                "}];",
16387                WhitesmithsBraceStyle);
16388   verifyFormat("void (^block)(void) = ^{\n"
16389                "  // ...\n"
16390                "  int i;\n"
16391                "};",
16392                WhitesmithsBraceStyle);
16393   // .. or dict literals.
16394   verifyFormat("void f()\n"
16395                "  {\n"
16396                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
16397                "  }",
16398                WhitesmithsBraceStyle);
16399 
16400   verifyFormat("int f()\n"
16401                "  { // comment\n"
16402                "  return 42;\n"
16403                "  }",
16404                WhitesmithsBraceStyle);
16405 
16406   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
16407   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
16408       FormatStyle::SIS_OnlyFirstIf;
16409   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
16410   verifyFormat("void f(bool b)\n"
16411                "  {\n"
16412                "  if (b)\n"
16413                "    {\n"
16414                "    return;\n"
16415                "    }\n"
16416                "  }\n",
16417                BreakBeforeBraceShortIfs);
16418   verifyFormat("void f(bool b)\n"
16419                "  {\n"
16420                "  if (b) return;\n"
16421                "  }\n",
16422                BreakBeforeBraceShortIfs);
16423   verifyFormat("void f(bool b)\n"
16424                "  {\n"
16425                "  while (b)\n"
16426                "    {\n"
16427                "    return;\n"
16428                "    }\n"
16429                "  }\n",
16430                BreakBeforeBraceShortIfs);
16431 }
16432 
16433 TEST_F(FormatTest, GNUBraceBreaking) {
16434   FormatStyle GNUBraceStyle = getLLVMStyle();
16435   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
16436   verifyFormat("namespace a\n"
16437                "{\n"
16438                "class A\n"
16439                "{\n"
16440                "  void f()\n"
16441                "  {\n"
16442                "    int a;\n"
16443                "    {\n"
16444                "      int b;\n"
16445                "    }\n"
16446                "    if (true)\n"
16447                "      {\n"
16448                "        a();\n"
16449                "        b();\n"
16450                "      }\n"
16451                "  }\n"
16452                "  void g() { return; }\n"
16453                "}\n"
16454                "} // namespace a",
16455                GNUBraceStyle);
16456 
16457   verifyFormat("void f()\n"
16458                "{\n"
16459                "  if (true)\n"
16460                "    {\n"
16461                "      a();\n"
16462                "    }\n"
16463                "  else if (false)\n"
16464                "    {\n"
16465                "      b();\n"
16466                "    }\n"
16467                "  else\n"
16468                "    {\n"
16469                "      c();\n"
16470                "    }\n"
16471                "}\n",
16472                GNUBraceStyle);
16473 
16474   verifyFormat("void f()\n"
16475                "{\n"
16476                "  for (int i = 0; i < 10; ++i)\n"
16477                "    {\n"
16478                "      a();\n"
16479                "    }\n"
16480                "  while (false)\n"
16481                "    {\n"
16482                "      b();\n"
16483                "    }\n"
16484                "  do\n"
16485                "    {\n"
16486                "      c();\n"
16487                "    }\n"
16488                "  while (false);\n"
16489                "}\n",
16490                GNUBraceStyle);
16491 
16492   verifyFormat("void f(int a)\n"
16493                "{\n"
16494                "  switch (a)\n"
16495                "    {\n"
16496                "    case 0:\n"
16497                "      break;\n"
16498                "    case 1:\n"
16499                "      {\n"
16500                "        break;\n"
16501                "      }\n"
16502                "    case 2:\n"
16503                "      {\n"
16504                "      }\n"
16505                "      break;\n"
16506                "    default:\n"
16507                "      break;\n"
16508                "    }\n"
16509                "}\n",
16510                GNUBraceStyle);
16511 
16512   verifyFormat("enum X\n"
16513                "{\n"
16514                "  Y = 0,\n"
16515                "}\n",
16516                GNUBraceStyle);
16517 
16518   verifyFormat("@interface BSApplicationController ()\n"
16519                "{\n"
16520                "@private\n"
16521                "  id _extraIvar;\n"
16522                "}\n"
16523                "@end\n",
16524                GNUBraceStyle);
16525 
16526   verifyFormat("#ifdef _DEBUG\n"
16527                "int foo(int i = 0)\n"
16528                "#else\n"
16529                "int foo(int i = 5)\n"
16530                "#endif\n"
16531                "{\n"
16532                "  return i;\n"
16533                "}",
16534                GNUBraceStyle);
16535 
16536   verifyFormat("void foo() {}\n"
16537                "void bar()\n"
16538                "#ifdef _DEBUG\n"
16539                "{\n"
16540                "  foo();\n"
16541                "}\n"
16542                "#else\n"
16543                "{\n"
16544                "}\n"
16545                "#endif",
16546                GNUBraceStyle);
16547 
16548   verifyFormat("void foobar() { int i = 5; }\n"
16549                "#ifdef _DEBUG\n"
16550                "void bar() {}\n"
16551                "#else\n"
16552                "void bar() { foobar(); }\n"
16553                "#endif",
16554                GNUBraceStyle);
16555 }
16556 
16557 TEST_F(FormatTest, WebKitBraceBreaking) {
16558   FormatStyle WebKitBraceStyle = getLLVMStyle();
16559   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
16560   WebKitBraceStyle.FixNamespaceComments = false;
16561   verifyFormat("namespace a {\n"
16562                "class A {\n"
16563                "  void f()\n"
16564                "  {\n"
16565                "    if (true) {\n"
16566                "      a();\n"
16567                "      b();\n"
16568                "    }\n"
16569                "  }\n"
16570                "  void g() { return; }\n"
16571                "};\n"
16572                "enum E {\n"
16573                "  A,\n"
16574                "  // foo\n"
16575                "  B,\n"
16576                "  C\n"
16577                "};\n"
16578                "struct B {\n"
16579                "  int x;\n"
16580                "};\n"
16581                "}\n",
16582                WebKitBraceStyle);
16583   verifyFormat("struct S {\n"
16584                "  int Type;\n"
16585                "  union {\n"
16586                "    int x;\n"
16587                "    double y;\n"
16588                "  } Value;\n"
16589                "  class C {\n"
16590                "    MyFavoriteType Value;\n"
16591                "  } Class;\n"
16592                "};\n",
16593                WebKitBraceStyle);
16594 }
16595 
16596 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
16597   verifyFormat("void f() {\n"
16598                "  try {\n"
16599                "  } catch (const Exception &e) {\n"
16600                "  }\n"
16601                "}\n",
16602                getLLVMStyle());
16603 }
16604 
16605 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
16606   auto Style = getLLVMStyle();
16607   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
16608   Style.AlignConsecutiveAssignments =
16609       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
16610   Style.AlignConsecutiveDeclarations =
16611       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
16612   verifyFormat("struct test demo[] = {\n"
16613                "    {56,    23, \"hello\"},\n"
16614                "    {-1, 93463, \"world\"},\n"
16615                "    { 7,     5,    \"!!\"}\n"
16616                "};\n",
16617                Style);
16618 
16619   verifyFormat("struct test demo[] = {\n"
16620                "    {56,    23, \"hello\"}, // first line\n"
16621                "    {-1, 93463, \"world\"}, // second line\n"
16622                "    { 7,     5,    \"!!\"}  // third line\n"
16623                "};\n",
16624                Style);
16625 
16626   verifyFormat("struct test demo[4] = {\n"
16627                "    { 56,    23, 21,       \"oh\"}, // first line\n"
16628                "    { -1, 93463, 22,       \"my\"}, // second line\n"
16629                "    {  7,     5,  1, \"goodness\"}  // third line\n"
16630                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
16631                "};\n",
16632                Style);
16633 
16634   verifyFormat("struct test demo[3] = {\n"
16635                "    {56,    23, \"hello\"},\n"
16636                "    {-1, 93463, \"world\"},\n"
16637                "    { 7,     5,    \"!!\"}\n"
16638                "};\n",
16639                Style);
16640 
16641   verifyFormat("struct test demo[3] = {\n"
16642                "    {int{56},    23, \"hello\"},\n"
16643                "    {int{-1}, 93463, \"world\"},\n"
16644                "    { int{7},     5,    \"!!\"}\n"
16645                "};\n",
16646                Style);
16647 
16648   verifyFormat("struct test demo[] = {\n"
16649                "    {56,    23, \"hello\"},\n"
16650                "    {-1, 93463, \"world\"},\n"
16651                "    { 7,     5,    \"!!\"},\n"
16652                "};\n",
16653                Style);
16654 
16655   verifyFormat("test demo[] = {\n"
16656                "    {56,    23, \"hello\"},\n"
16657                "    {-1, 93463, \"world\"},\n"
16658                "    { 7,     5,    \"!!\"},\n"
16659                "};\n",
16660                Style);
16661 
16662   verifyFormat("demo = std::array<struct test, 3>{\n"
16663                "    test{56,    23, \"hello\"},\n"
16664                "    test{-1, 93463, \"world\"},\n"
16665                "    test{ 7,     5,    \"!!\"},\n"
16666                "};\n",
16667                Style);
16668 
16669   verifyFormat("test demo[] = {\n"
16670                "    {56,    23, \"hello\"},\n"
16671                "#if X\n"
16672                "    {-1, 93463, \"world\"},\n"
16673                "#endif\n"
16674                "    { 7,     5,    \"!!\"}\n"
16675                "};\n",
16676                Style);
16677 
16678   verifyFormat(
16679       "test demo[] = {\n"
16680       "    { 7,    23,\n"
16681       "     \"hello world i am a very long line that really, in any\"\n"
16682       "     \"just world, ought to be split over multiple lines\"},\n"
16683       "    {-1, 93463,                                  \"world\"},\n"
16684       "    {56,     5,                                     \"!!\"}\n"
16685       "};\n",
16686       Style);
16687 
16688   verifyFormat("return GradForUnaryCwise(g, {\n"
16689                "                                {{\"sign\"}, \"Sign\",  "
16690                "  {\"x\", \"dy\"}},\n"
16691                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
16692                ", \"sign\"}},\n"
16693                "});\n",
16694                Style);
16695 
16696   Style.ColumnLimit = 0;
16697   EXPECT_EQ(
16698       "test demo[] = {\n"
16699       "    {56,    23, \"hello world i am a very long line that really, "
16700       "in any just world, ought to be split over multiple lines\"},\n"
16701       "    {-1, 93463,                                                  "
16702       "                                                 \"world\"},\n"
16703       "    { 7,     5,                                                  "
16704       "                                                    \"!!\"},\n"
16705       "};",
16706       format("test demo[] = {{56, 23, \"hello world i am a very long line "
16707              "that really, in any just world, ought to be split over multiple "
16708              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
16709              Style));
16710 
16711   Style.ColumnLimit = 80;
16712   verifyFormat("test demo[] = {\n"
16713                "    {56,    23, /* a comment */ \"hello\"},\n"
16714                "    {-1, 93463,                 \"world\"},\n"
16715                "    { 7,     5,                    \"!!\"}\n"
16716                "};\n",
16717                Style);
16718 
16719   verifyFormat("test demo[] = {\n"
16720                "    {56,    23,                    \"hello\"},\n"
16721                "    {-1, 93463, \"world\" /* comment here */},\n"
16722                "    { 7,     5,                       \"!!\"}\n"
16723                "};\n",
16724                Style);
16725 
16726   verifyFormat("test demo[] = {\n"
16727                "    {56, /* a comment */ 23, \"hello\"},\n"
16728                "    {-1,              93463, \"world\"},\n"
16729                "    { 7,                  5,    \"!!\"}\n"
16730                "};\n",
16731                Style);
16732 
16733   Style.ColumnLimit = 20;
16734   EXPECT_EQ(
16735       "demo = std::array<\n"
16736       "    struct test, 3>{\n"
16737       "    test{\n"
16738       "         56,    23,\n"
16739       "         \"hello \"\n"
16740       "         \"world i \"\n"
16741       "         \"am a very \"\n"
16742       "         \"long line \"\n"
16743       "         \"that \"\n"
16744       "         \"really, \"\n"
16745       "         \"in any \"\n"
16746       "         \"just \"\n"
16747       "         \"world, \"\n"
16748       "         \"ought to \"\n"
16749       "         \"be split \"\n"
16750       "         \"over \"\n"
16751       "         \"multiple \"\n"
16752       "         \"lines\"},\n"
16753       "    test{-1, 93463,\n"
16754       "         \"world\"},\n"
16755       "    test{ 7,     5,\n"
16756       "         \"!!\"   },\n"
16757       "};",
16758       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
16759              "i am a very long line that really, in any just world, ought "
16760              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
16761              "test{7, 5, \"!!\"},};",
16762              Style));
16763   // This caused a core dump by enabling Alignment in the LLVMStyle globally
16764   Style = getLLVMStyleWithColumns(50);
16765   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
16766   verifyFormat("static A x = {\n"
16767                "    {{init1, init2, init3, init4},\n"
16768                "     {init1, init2, init3, init4}}\n"
16769                "};",
16770                Style);
16771   Style.ColumnLimit = 100;
16772   EXPECT_EQ(
16773       "test demo[] = {\n"
16774       "    {56,    23,\n"
16775       "     \"hello world i am a very long line that really, in any just world"
16776       ", ought to be split over \"\n"
16777       "     \"multiple lines\"  },\n"
16778       "    {-1, 93463, \"world\"},\n"
16779       "    { 7,     5,    \"!!\"},\n"
16780       "};",
16781       format("test demo[] = {{56, 23, \"hello world i am a very long line "
16782              "that really, in any just world, ought to be split over multiple "
16783              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
16784              Style));
16785 
16786   Style = getLLVMStyleWithColumns(50);
16787   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
16788   Style.AlignConsecutiveAssignments =
16789       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
16790   Style.AlignConsecutiveDeclarations =
16791       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
16792   verifyFormat("struct test demo[] = {\n"
16793                "    {56,    23, \"hello\"},\n"
16794                "    {-1, 93463, \"world\"},\n"
16795                "    { 7,     5,    \"!!\"}\n"
16796                "};\n"
16797                "static A x = {\n"
16798                "    {{init1, init2, init3, init4},\n"
16799                "     {init1, init2, init3, init4}}\n"
16800                "};",
16801                Style);
16802   Style.ColumnLimit = 100;
16803   Style.AlignConsecutiveAssignments =
16804       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
16805   Style.AlignConsecutiveDeclarations =
16806       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
16807   verifyFormat("struct test demo[] = {\n"
16808                "    {56,    23, \"hello\"},\n"
16809                "    {-1, 93463, \"world\"},\n"
16810                "    { 7,     5,    \"!!\"}\n"
16811                "};\n"
16812                "struct test demo[4] = {\n"
16813                "    { 56,    23, 21,       \"oh\"}, // first line\n"
16814                "    { -1, 93463, 22,       \"my\"}, // second line\n"
16815                "    {  7,     5,  1, \"goodness\"}  // third line\n"
16816                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
16817                "};\n",
16818                Style);
16819   EXPECT_EQ(
16820       "test demo[] = {\n"
16821       "    {56,\n"
16822       "     \"hello world i am a very long line that really, in any just world"
16823       ", ought to be split over \"\n"
16824       "     \"multiple lines\",    23},\n"
16825       "    {-1,      \"world\", 93463},\n"
16826       "    { 7,         \"!!\",     5},\n"
16827       "};",
16828       format("test demo[] = {{56, \"hello world i am a very long line "
16829              "that really, in any just world, ought to be split over multiple "
16830              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
16831              Style));
16832 }
16833 
16834 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
16835   auto Style = getLLVMStyle();
16836   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
16837   verifyFormat("struct test demo[] = {\n"
16838                "    {56, 23,    \"hello\"},\n"
16839                "    {-1, 93463, \"world\"},\n"
16840                "    {7,  5,     \"!!\"   }\n"
16841                "};\n",
16842                Style);
16843 
16844   verifyFormat("struct test demo[] = {\n"
16845                "    {56, 23,    \"hello\"}, // first line\n"
16846                "    {-1, 93463, \"world\"}, // second line\n"
16847                "    {7,  5,     \"!!\"   }  // third line\n"
16848                "};\n",
16849                Style);
16850   verifyFormat("struct test demo[4] = {\n"
16851                "    {56,  23,    21, \"oh\"      }, // first line\n"
16852                "    {-1,  93463, 22, \"my\"      }, // second line\n"
16853                "    {7,   5,     1,  \"goodness\"}  // third line\n"
16854                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
16855                "};\n",
16856                Style);
16857   verifyFormat("struct test demo[3] = {\n"
16858                "    {56, 23,    \"hello\"},\n"
16859                "    {-1, 93463, \"world\"},\n"
16860                "    {7,  5,     \"!!\"   }\n"
16861                "};\n",
16862                Style);
16863 
16864   verifyFormat("struct test demo[3] = {\n"
16865                "    {int{56}, 23,    \"hello\"},\n"
16866                "    {int{-1}, 93463, \"world\"},\n"
16867                "    {int{7},  5,     \"!!\"   }\n"
16868                "};\n",
16869                Style);
16870   verifyFormat("struct test demo[] = {\n"
16871                "    {56, 23,    \"hello\"},\n"
16872                "    {-1, 93463, \"world\"},\n"
16873                "    {7,  5,     \"!!\"   },\n"
16874                "};\n",
16875                Style);
16876   verifyFormat("test demo[] = {\n"
16877                "    {56, 23,    \"hello\"},\n"
16878                "    {-1, 93463, \"world\"},\n"
16879                "    {7,  5,     \"!!\"   },\n"
16880                "};\n",
16881                Style);
16882   verifyFormat("demo = std::array<struct test, 3>{\n"
16883                "    test{56, 23,    \"hello\"},\n"
16884                "    test{-1, 93463, \"world\"},\n"
16885                "    test{7,  5,     \"!!\"   },\n"
16886                "};\n",
16887                Style);
16888   verifyFormat("test demo[] = {\n"
16889                "    {56, 23,    \"hello\"},\n"
16890                "#if X\n"
16891                "    {-1, 93463, \"world\"},\n"
16892                "#endif\n"
16893                "    {7,  5,     \"!!\"   }\n"
16894                "};\n",
16895                Style);
16896   verifyFormat(
16897       "test demo[] = {\n"
16898       "    {7,  23,\n"
16899       "     \"hello world i am a very long line that really, in any\"\n"
16900       "     \"just world, ought to be split over multiple lines\"},\n"
16901       "    {-1, 93463, \"world\"                                 },\n"
16902       "    {56, 5,     \"!!\"                                    }\n"
16903       "};\n",
16904       Style);
16905 
16906   verifyFormat("return GradForUnaryCwise(g, {\n"
16907                "                                {{\"sign\"}, \"Sign\", {\"x\", "
16908                "\"dy\"}   },\n"
16909                "                                {{\"dx\"},   \"Mul\",  "
16910                "{\"dy\", \"sign\"}},\n"
16911                "});\n",
16912                Style);
16913 
16914   Style.ColumnLimit = 0;
16915   EXPECT_EQ(
16916       "test demo[] = {\n"
16917       "    {56, 23,    \"hello world i am a very long line that really, in any "
16918       "just world, ought to be split over multiple lines\"},\n"
16919       "    {-1, 93463, \"world\"                                               "
16920       "                                                   },\n"
16921       "    {7,  5,     \"!!\"                                                  "
16922       "                                                   },\n"
16923       "};",
16924       format("test demo[] = {{56, 23, \"hello world i am a very long line "
16925              "that really, in any just world, ought to be split over multiple "
16926              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
16927              Style));
16928 
16929   Style.ColumnLimit = 80;
16930   verifyFormat("test demo[] = {\n"
16931                "    {56, 23,    /* a comment */ \"hello\"},\n"
16932                "    {-1, 93463, \"world\"                },\n"
16933                "    {7,  5,     \"!!\"                   }\n"
16934                "};\n",
16935                Style);
16936 
16937   verifyFormat("test demo[] = {\n"
16938                "    {56, 23,    \"hello\"                   },\n"
16939                "    {-1, 93463, \"world\" /* comment here */},\n"
16940                "    {7,  5,     \"!!\"                      }\n"
16941                "};\n",
16942                Style);
16943 
16944   verifyFormat("test demo[] = {\n"
16945                "    {56, /* a comment */ 23, \"hello\"},\n"
16946                "    {-1, 93463,              \"world\"},\n"
16947                "    {7,  5,                  \"!!\"   }\n"
16948                "};\n",
16949                Style);
16950 
16951   Style.ColumnLimit = 20;
16952   EXPECT_EQ(
16953       "demo = std::array<\n"
16954       "    struct test, 3>{\n"
16955       "    test{\n"
16956       "         56, 23,\n"
16957       "         \"hello \"\n"
16958       "         \"world i \"\n"
16959       "         \"am a very \"\n"
16960       "         \"long line \"\n"
16961       "         \"that \"\n"
16962       "         \"really, \"\n"
16963       "         \"in any \"\n"
16964       "         \"just \"\n"
16965       "         \"world, \"\n"
16966       "         \"ought to \"\n"
16967       "         \"be split \"\n"
16968       "         \"over \"\n"
16969       "         \"multiple \"\n"
16970       "         \"lines\"},\n"
16971       "    test{-1, 93463,\n"
16972       "         \"world\"},\n"
16973       "    test{7,  5,\n"
16974       "         \"!!\"   },\n"
16975       "};",
16976       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
16977              "i am a very long line that really, in any just world, ought "
16978              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
16979              "test{7, 5, \"!!\"},};",
16980              Style));
16981 
16982   // This caused a core dump by enabling Alignment in the LLVMStyle globally
16983   Style = getLLVMStyleWithColumns(50);
16984   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
16985   verifyFormat("static A x = {\n"
16986                "    {{init1, init2, init3, init4},\n"
16987                "     {init1, init2, init3, init4}}\n"
16988                "};",
16989                Style);
16990   Style.ColumnLimit = 100;
16991   EXPECT_EQ(
16992       "test demo[] = {\n"
16993       "    {56, 23,\n"
16994       "     \"hello world i am a very long line that really, in any just world"
16995       ", ought to be split over \"\n"
16996       "     \"multiple lines\"  },\n"
16997       "    {-1, 93463, \"world\"},\n"
16998       "    {7,  5,     \"!!\"   },\n"
16999       "};",
17000       format("test demo[] = {{56, 23, \"hello world i am a very long line "
17001              "that really, in any just world, ought to be split over multiple "
17002              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17003              Style));
17004 }
17005 
17006 TEST_F(FormatTest, UnderstandsPragmas) {
17007   verifyFormat("#pragma omp reduction(| : var)");
17008   verifyFormat("#pragma omp reduction(+ : var)");
17009 
17010   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
17011             "(including parentheses).",
17012             format("#pragma    mark   Any non-hyphenated or hyphenated string "
17013                    "(including parentheses)."));
17014 }
17015 
17016 TEST_F(FormatTest, UnderstandPragmaOption) {
17017   verifyFormat("#pragma option -C -A");
17018 
17019   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
17020 }
17021 
17022 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
17023   FormatStyle Style = getLLVMStyle();
17024   Style.ColumnLimit = 20;
17025 
17026   // See PR41213
17027   EXPECT_EQ("/*\n"
17028             " *\t9012345\n"
17029             " * /8901\n"
17030             " */",
17031             format("/*\n"
17032                    " *\t9012345 /8901\n"
17033                    " */",
17034                    Style));
17035   EXPECT_EQ("/*\n"
17036             " *345678\n"
17037             " *\t/8901\n"
17038             " */",
17039             format("/*\n"
17040                    " *345678\t/8901\n"
17041                    " */",
17042                    Style));
17043 
17044   verifyFormat("int a; // the\n"
17045                "       // comment",
17046                Style);
17047   EXPECT_EQ("int a; /* first line\n"
17048             "        * second\n"
17049             "        * line third\n"
17050             "        * line\n"
17051             "        */",
17052             format("int a; /* first line\n"
17053                    "        * second\n"
17054                    "        * line third\n"
17055                    "        * line\n"
17056                    "        */",
17057                    Style));
17058   EXPECT_EQ("int a; // first line\n"
17059             "       // second\n"
17060             "       // line third\n"
17061             "       // line",
17062             format("int a; // first line\n"
17063                    "       // second line\n"
17064                    "       // third line",
17065                    Style));
17066 
17067   Style.PenaltyExcessCharacter = 90;
17068   verifyFormat("int a; // the comment", Style);
17069   EXPECT_EQ("int a; // the comment\n"
17070             "       // aaa",
17071             format("int a; // the comment aaa", Style));
17072   EXPECT_EQ("int a; /* first line\n"
17073             "        * second line\n"
17074             "        * third line\n"
17075             "        */",
17076             format("int a; /* first line\n"
17077                    "        * second line\n"
17078                    "        * third line\n"
17079                    "        */",
17080                    Style));
17081   EXPECT_EQ("int a; // first line\n"
17082             "       // second line\n"
17083             "       // third line",
17084             format("int a; // first line\n"
17085                    "       // second line\n"
17086                    "       // third line",
17087                    Style));
17088   // FIXME: Investigate why this is not getting the same layout as the test
17089   // above.
17090   EXPECT_EQ("int a; /* first line\n"
17091             "        * second line\n"
17092             "        * third line\n"
17093             "        */",
17094             format("int a; /* first line second line third line"
17095                    "\n*/",
17096                    Style));
17097 
17098   EXPECT_EQ("// foo bar baz bazfoo\n"
17099             "// foo bar foo bar\n",
17100             format("// foo bar baz bazfoo\n"
17101                    "// foo bar foo           bar\n",
17102                    Style));
17103   EXPECT_EQ("// foo bar baz bazfoo\n"
17104             "// foo bar foo bar\n",
17105             format("// foo bar baz      bazfoo\n"
17106                    "// foo            bar foo bar\n",
17107                    Style));
17108 
17109   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
17110   // next one.
17111   EXPECT_EQ("// foo bar baz bazfoo\n"
17112             "// bar foo bar\n",
17113             format("// foo bar baz      bazfoo bar\n"
17114                    "// foo            bar\n",
17115                    Style));
17116 
17117   EXPECT_EQ("// foo bar baz bazfoo\n"
17118             "// foo bar baz bazfoo\n"
17119             "// bar foo bar\n",
17120             format("// foo bar baz      bazfoo\n"
17121                    "// foo bar baz      bazfoo bar\n"
17122                    "// foo bar\n",
17123                    Style));
17124 
17125   EXPECT_EQ("// foo bar baz bazfoo\n"
17126             "// foo bar baz bazfoo\n"
17127             "// bar foo bar\n",
17128             format("// foo bar baz      bazfoo\n"
17129                    "// foo bar baz      bazfoo bar\n"
17130                    "// foo           bar\n",
17131                    Style));
17132 
17133   // Make sure we do not keep protruding characters if strict mode reflow is
17134   // cheaper than keeping protruding characters.
17135   Style.ColumnLimit = 21;
17136   EXPECT_EQ(
17137       "// foo foo foo foo\n"
17138       "// foo foo foo foo\n"
17139       "// foo foo foo foo\n",
17140       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
17141 
17142   EXPECT_EQ("int a = /* long block\n"
17143             "           comment */\n"
17144             "    42;",
17145             format("int a = /* long block comment */ 42;", Style));
17146 }
17147 
17148 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
17149   for (size_t i = 1; i < Styles.size(); ++i)                                   \
17150   EXPECT_EQ(Styles[0], Styles[i])                                              \
17151       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
17152 
17153 TEST_F(FormatTest, GetsPredefinedStyleByName) {
17154   SmallVector<FormatStyle, 3> Styles;
17155   Styles.resize(3);
17156 
17157   Styles[0] = getLLVMStyle();
17158   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
17159   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
17160   EXPECT_ALL_STYLES_EQUAL(Styles);
17161 
17162   Styles[0] = getGoogleStyle();
17163   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
17164   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
17165   EXPECT_ALL_STYLES_EQUAL(Styles);
17166 
17167   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
17168   EXPECT_TRUE(
17169       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
17170   EXPECT_TRUE(
17171       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
17172   EXPECT_ALL_STYLES_EQUAL(Styles);
17173 
17174   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
17175   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
17176   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
17177   EXPECT_ALL_STYLES_EQUAL(Styles);
17178 
17179   Styles[0] = getMozillaStyle();
17180   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
17181   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
17182   EXPECT_ALL_STYLES_EQUAL(Styles);
17183 
17184   Styles[0] = getWebKitStyle();
17185   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
17186   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
17187   EXPECT_ALL_STYLES_EQUAL(Styles);
17188 
17189   Styles[0] = getGNUStyle();
17190   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
17191   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
17192   EXPECT_ALL_STYLES_EQUAL(Styles);
17193 
17194   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
17195 }
17196 
17197 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
17198   SmallVector<FormatStyle, 8> Styles;
17199   Styles.resize(2);
17200 
17201   Styles[0] = getGoogleStyle();
17202   Styles[1] = getLLVMStyle();
17203   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
17204   EXPECT_ALL_STYLES_EQUAL(Styles);
17205 
17206   Styles.resize(5);
17207   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
17208   Styles[1] = getLLVMStyle();
17209   Styles[1].Language = FormatStyle::LK_JavaScript;
17210   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
17211 
17212   Styles[2] = getLLVMStyle();
17213   Styles[2].Language = FormatStyle::LK_JavaScript;
17214   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
17215                                   "BasedOnStyle: Google",
17216                                   &Styles[2])
17217                    .value());
17218 
17219   Styles[3] = getLLVMStyle();
17220   Styles[3].Language = FormatStyle::LK_JavaScript;
17221   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
17222                                   "Language: JavaScript",
17223                                   &Styles[3])
17224                    .value());
17225 
17226   Styles[4] = getLLVMStyle();
17227   Styles[4].Language = FormatStyle::LK_JavaScript;
17228   EXPECT_EQ(0, parseConfiguration("---\n"
17229                                   "BasedOnStyle: LLVM\n"
17230                                   "IndentWidth: 123\n"
17231                                   "---\n"
17232                                   "BasedOnStyle: Google\n"
17233                                   "Language: JavaScript",
17234                                   &Styles[4])
17235                    .value());
17236   EXPECT_ALL_STYLES_EQUAL(Styles);
17237 }
17238 
17239 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
17240   Style.FIELD = false;                                                         \
17241   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
17242   EXPECT_TRUE(Style.FIELD);                                                    \
17243   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
17244   EXPECT_FALSE(Style.FIELD);
17245 
17246 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
17247 
17248 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
17249   Style.STRUCT.FIELD = false;                                                  \
17250   EXPECT_EQ(0,                                                                 \
17251             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
17252                 .value());                                                     \
17253   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
17254   EXPECT_EQ(0,                                                                 \
17255             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
17256                 .value());                                                     \
17257   EXPECT_FALSE(Style.STRUCT.FIELD);
17258 
17259 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
17260   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
17261 
17262 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
17263   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
17264   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
17265   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
17266 
17267 TEST_F(FormatTest, ParsesConfigurationBools) {
17268   FormatStyle Style = {};
17269   Style.Language = FormatStyle::LK_Cpp;
17270   CHECK_PARSE_BOOL(AlignTrailingComments);
17271   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
17272   CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine);
17273   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
17274   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
17275   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
17276   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
17277   CHECK_PARSE_BOOL(BinPackArguments);
17278   CHECK_PARSE_BOOL(BinPackParameters);
17279   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
17280   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
17281   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
17282   CHECK_PARSE_BOOL(BreakStringLiterals);
17283   CHECK_PARSE_BOOL(CompactNamespaces);
17284   CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
17285   CHECK_PARSE_BOOL(DeriveLineEnding);
17286   CHECK_PARSE_BOOL(DerivePointerAlignment);
17287   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
17288   CHECK_PARSE_BOOL(DisableFormat);
17289   CHECK_PARSE_BOOL(IndentAccessModifiers);
17290   CHECK_PARSE_BOOL(IndentCaseLabels);
17291   CHECK_PARSE_BOOL(IndentCaseBlocks);
17292   CHECK_PARSE_BOOL(IndentGotoLabels);
17293   CHECK_PARSE_BOOL(IndentRequires);
17294   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
17295   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
17296   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
17297   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
17298   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
17299   CHECK_PARSE_BOOL(ReflowComments);
17300   CHECK_PARSE_BOOL(SortUsingDeclarations);
17301   CHECK_PARSE_BOOL(SpacesInParentheses);
17302   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
17303   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
17304   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
17305   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
17306   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
17307   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
17308   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
17309   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
17310   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
17311   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
17312   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
17313   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
17314   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
17315   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
17316   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
17317   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
17318   CHECK_PARSE_BOOL(UseCRLF);
17319 
17320   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
17321   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
17322   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
17323   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
17324   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
17325   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
17326   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
17327   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
17328   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
17329   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
17330   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
17331   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
17332   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
17333   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
17334   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
17335   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
17336   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
17337 }
17338 
17339 #undef CHECK_PARSE_BOOL
17340 
17341 TEST_F(FormatTest, ParsesConfiguration) {
17342   FormatStyle Style = {};
17343   Style.Language = FormatStyle::LK_Cpp;
17344   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
17345   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
17346               ConstructorInitializerIndentWidth, 1234u);
17347   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
17348   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
17349   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
17350   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
17351   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
17352               PenaltyBreakBeforeFirstCallParameter, 1234u);
17353   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
17354               PenaltyBreakTemplateDeclaration, 1234u);
17355   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
17356   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
17357               PenaltyReturnTypeOnItsOwnLine, 1234u);
17358   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
17359               SpacesBeforeTrailingComments, 1234u);
17360   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
17361   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
17362   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
17363 
17364   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
17365   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
17366               FormatStyle::ACS_None);
17367   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
17368               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
17369   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
17370               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
17371   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
17372               AlignConsecutiveAssignments,
17373               FormatStyle::ACS_AcrossEmptyLinesAndComments);
17374   // For backwards compability, false / true should still parse
17375   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
17376               FormatStyle::ACS_None);
17377   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
17378               FormatStyle::ACS_Consecutive);
17379 
17380   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
17381   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
17382               FormatStyle::ACS_None);
17383   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
17384               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
17385   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
17386               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
17387   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
17388               AlignConsecutiveBitFields,
17389               FormatStyle::ACS_AcrossEmptyLinesAndComments);
17390   // For backwards compability, false / true should still parse
17391   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
17392               FormatStyle::ACS_None);
17393   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
17394               FormatStyle::ACS_Consecutive);
17395 
17396   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
17397   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
17398               FormatStyle::ACS_None);
17399   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
17400               FormatStyle::ACS_Consecutive);
17401   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
17402               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
17403   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
17404               AlignConsecutiveMacros,
17405               FormatStyle::ACS_AcrossEmptyLinesAndComments);
17406   // For backwards compability, false / true should still parse
17407   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
17408               FormatStyle::ACS_None);
17409   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
17410               FormatStyle::ACS_Consecutive);
17411 
17412   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
17413   CHECK_PARSE("AlignConsecutiveDeclarations: None",
17414               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
17415   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
17416               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
17417   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
17418               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
17419   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
17420               AlignConsecutiveDeclarations,
17421               FormatStyle::ACS_AcrossEmptyLinesAndComments);
17422   // For backwards compability, false / true should still parse
17423   CHECK_PARSE("AlignConsecutiveDeclarations: false",
17424               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
17425   CHECK_PARSE("AlignConsecutiveDeclarations: true",
17426               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
17427 
17428   Style.PointerAlignment = FormatStyle::PAS_Middle;
17429   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
17430               FormatStyle::PAS_Left);
17431   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
17432               FormatStyle::PAS_Right);
17433   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
17434               FormatStyle::PAS_Middle);
17435   // For backward compatibility:
17436   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
17437               FormatStyle::PAS_Left);
17438   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
17439               FormatStyle::PAS_Right);
17440   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
17441               FormatStyle::PAS_Middle);
17442 
17443   Style.Standard = FormatStyle::LS_Auto;
17444   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
17445   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
17446   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
17447   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
17448   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
17449   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
17450   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
17451   // Legacy aliases:
17452   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
17453   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
17454   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
17455   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
17456 
17457   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17458   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
17459               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
17460   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
17461               FormatStyle::BOS_None);
17462   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
17463               FormatStyle::BOS_All);
17464   // For backward compatibility:
17465   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
17466               FormatStyle::BOS_None);
17467   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
17468               FormatStyle::BOS_All);
17469 
17470   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
17471   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
17472               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
17473   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
17474               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
17475   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
17476               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
17477   // For backward compatibility:
17478   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
17479               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
17480 
17481   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
17482   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
17483               FormatStyle::BILS_AfterComma);
17484   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
17485               FormatStyle::BILS_BeforeComma);
17486   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
17487               FormatStyle::BILS_AfterColon);
17488   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
17489               FormatStyle::BILS_BeforeColon);
17490   // For backward compatibility:
17491   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
17492               FormatStyle::BILS_BeforeComma);
17493 
17494   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
17495   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
17496               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
17497   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
17498               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
17499   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
17500               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
17501   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
17502               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
17503 
17504   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
17505   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
17506               FormatStyle::BAS_Align);
17507   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
17508               FormatStyle::BAS_DontAlign);
17509   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
17510               FormatStyle::BAS_AlwaysBreak);
17511   // For backward compatibility:
17512   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
17513               FormatStyle::BAS_DontAlign);
17514   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
17515               FormatStyle::BAS_Align);
17516 
17517   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17518   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
17519               FormatStyle::ENAS_DontAlign);
17520   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
17521               FormatStyle::ENAS_Left);
17522   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
17523               FormatStyle::ENAS_Right);
17524   // For backward compatibility:
17525   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
17526               FormatStyle::ENAS_Left);
17527   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
17528               FormatStyle::ENAS_Right);
17529 
17530   Style.AlignOperands = FormatStyle::OAS_Align;
17531   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
17532               FormatStyle::OAS_DontAlign);
17533   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
17534   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
17535               FormatStyle::OAS_AlignAfterOperator);
17536   // For backward compatibility:
17537   CHECK_PARSE("AlignOperands: false", AlignOperands,
17538               FormatStyle::OAS_DontAlign);
17539   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
17540 
17541   Style.UseTab = FormatStyle::UT_ForIndentation;
17542   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
17543   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
17544   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
17545   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
17546               FormatStyle::UT_ForContinuationAndIndentation);
17547   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
17548               FormatStyle::UT_AlignWithSpaces);
17549   // For backward compatibility:
17550   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
17551   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
17552 
17553   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
17554   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
17555               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
17556   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
17557               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
17558   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
17559               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
17560   // For backward compatibility:
17561   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
17562               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
17563   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
17564               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
17565 
17566   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
17567   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
17568               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
17569   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
17570               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
17571   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
17572               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
17573   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
17574               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
17575   // For backward compatibility:
17576   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
17577               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
17578   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
17579               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
17580 
17581   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
17582   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
17583               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
17584   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
17585               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
17586   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
17587               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
17588   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
17589               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
17590 
17591   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
17592   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
17593               FormatStyle::SBPO_Never);
17594   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
17595               FormatStyle::SBPO_Always);
17596   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
17597               FormatStyle::SBPO_ControlStatements);
17598   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
17599               FormatStyle::SBPO_NonEmptyParentheses);
17600   // For backward compatibility:
17601   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
17602               FormatStyle::SBPO_Never);
17603   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
17604               FormatStyle::SBPO_ControlStatements);
17605 
17606   Style.ColumnLimit = 123;
17607   FormatStyle BaseStyle = getLLVMStyle();
17608   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
17609   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
17610 
17611   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
17612   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
17613               FormatStyle::BS_Attach);
17614   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
17615               FormatStyle::BS_Linux);
17616   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
17617               FormatStyle::BS_Mozilla);
17618   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
17619               FormatStyle::BS_Stroustrup);
17620   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
17621               FormatStyle::BS_Allman);
17622   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
17623               FormatStyle::BS_Whitesmiths);
17624   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
17625   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
17626               FormatStyle::BS_WebKit);
17627   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
17628               FormatStyle::BS_Custom);
17629 
17630   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
17631   CHECK_PARSE("BraceWrapping:\n"
17632               "  AfterControlStatement: MultiLine",
17633               BraceWrapping.AfterControlStatement,
17634               FormatStyle::BWACS_MultiLine);
17635   CHECK_PARSE("BraceWrapping:\n"
17636               "  AfterControlStatement: Always",
17637               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
17638   CHECK_PARSE("BraceWrapping:\n"
17639               "  AfterControlStatement: Never",
17640               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
17641   // For backward compatibility:
17642   CHECK_PARSE("BraceWrapping:\n"
17643               "  AfterControlStatement: true",
17644               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
17645   CHECK_PARSE("BraceWrapping:\n"
17646               "  AfterControlStatement: false",
17647               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
17648 
17649   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
17650   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
17651               FormatStyle::RTBS_None);
17652   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
17653               FormatStyle::RTBS_All);
17654   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
17655               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
17656   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
17657               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
17658   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
17659               AlwaysBreakAfterReturnType,
17660               FormatStyle::RTBS_TopLevelDefinitions);
17661 
17662   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
17663   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
17664               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
17665   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
17666               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
17667   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
17668               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
17669   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
17670               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
17671   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
17672               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
17673 
17674   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
17675   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
17676               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
17677   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
17678               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
17679   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
17680               AlwaysBreakAfterDefinitionReturnType,
17681               FormatStyle::DRTBS_TopLevel);
17682 
17683   Style.NamespaceIndentation = FormatStyle::NI_All;
17684   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
17685               FormatStyle::NI_None);
17686   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
17687               FormatStyle::NI_Inner);
17688   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
17689               FormatStyle::NI_All);
17690 
17691   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
17692   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
17693               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
17694   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
17695               AllowShortIfStatementsOnASingleLine,
17696               FormatStyle::SIS_WithoutElse);
17697   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
17698               AllowShortIfStatementsOnASingleLine,
17699               FormatStyle::SIS_OnlyFirstIf);
17700   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
17701               AllowShortIfStatementsOnASingleLine,
17702               FormatStyle::SIS_AllIfsAndElse);
17703   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
17704               AllowShortIfStatementsOnASingleLine,
17705               FormatStyle::SIS_OnlyFirstIf);
17706   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
17707               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
17708   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
17709               AllowShortIfStatementsOnASingleLine,
17710               FormatStyle::SIS_WithoutElse);
17711 
17712   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
17713   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
17714               FormatStyle::IEBS_AfterExternBlock);
17715   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
17716               FormatStyle::IEBS_Indent);
17717   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
17718               FormatStyle::IEBS_NoIndent);
17719   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
17720               FormatStyle::IEBS_Indent);
17721   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
17722               FormatStyle::IEBS_NoIndent);
17723 
17724   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
17725   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
17726               FormatStyle::BFCS_Both);
17727   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
17728               FormatStyle::BFCS_None);
17729   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
17730               FormatStyle::BFCS_Before);
17731   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
17732               FormatStyle::BFCS_After);
17733 
17734   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
17735   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
17736               FormatStyle::SJSIO_After);
17737   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
17738               FormatStyle::SJSIO_Before);
17739 
17740   // FIXME: This is required because parsing a configuration simply overwrites
17741   // the first N elements of the list instead of resetting it.
17742   Style.ForEachMacros.clear();
17743   std::vector<std::string> BoostForeach;
17744   BoostForeach.push_back("BOOST_FOREACH");
17745   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
17746   std::vector<std::string> BoostAndQForeach;
17747   BoostAndQForeach.push_back("BOOST_FOREACH");
17748   BoostAndQForeach.push_back("Q_FOREACH");
17749   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
17750               BoostAndQForeach);
17751 
17752   Style.AttributeMacros.clear();
17753   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
17754               std::vector<std::string>{"__capability"});
17755   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
17756               std::vector<std::string>({"attr1", "attr2"}));
17757 
17758   Style.StatementAttributeLikeMacros.clear();
17759   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
17760               StatementAttributeLikeMacros,
17761               std::vector<std::string>({"emit", "Q_EMIT"}));
17762 
17763   Style.StatementMacros.clear();
17764   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
17765               std::vector<std::string>{"QUNUSED"});
17766   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
17767               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
17768 
17769   Style.NamespaceMacros.clear();
17770   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
17771               std::vector<std::string>{"TESTSUITE"});
17772   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
17773               std::vector<std::string>({"TESTSUITE", "SUITE"}));
17774 
17775   Style.WhitespaceSensitiveMacros.clear();
17776   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
17777               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
17778   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
17779               WhitespaceSensitiveMacros,
17780               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
17781   Style.WhitespaceSensitiveMacros.clear();
17782   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
17783               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
17784   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
17785               WhitespaceSensitiveMacros,
17786               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
17787 
17788   Style.IncludeStyle.IncludeCategories.clear();
17789   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
17790       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
17791   CHECK_PARSE("IncludeCategories:\n"
17792               "  - Regex: abc/.*\n"
17793               "    Priority: 2\n"
17794               "  - Regex: .*\n"
17795               "    Priority: 1\n"
17796               "    CaseSensitive: true\n",
17797               IncludeStyle.IncludeCategories, ExpectedCategories);
17798   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
17799               "abc$");
17800   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
17801               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
17802 
17803   Style.SortIncludes = FormatStyle::SI_Never;
17804   CHECK_PARSE("SortIncludes: true", SortIncludes,
17805               FormatStyle::SI_CaseSensitive);
17806   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
17807   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
17808               FormatStyle::SI_CaseInsensitive);
17809   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
17810               FormatStyle::SI_CaseSensitive);
17811   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
17812 
17813   Style.RawStringFormats.clear();
17814   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
17815       {
17816           FormatStyle::LK_TextProto,
17817           {"pb", "proto"},
17818           {"PARSE_TEXT_PROTO"},
17819           /*CanonicalDelimiter=*/"",
17820           "llvm",
17821       },
17822       {
17823           FormatStyle::LK_Cpp,
17824           {"cc", "cpp"},
17825           {"C_CODEBLOCK", "CPPEVAL"},
17826           /*CanonicalDelimiter=*/"cc",
17827           /*BasedOnStyle=*/"",
17828       },
17829   };
17830 
17831   CHECK_PARSE("RawStringFormats:\n"
17832               "  - Language: TextProto\n"
17833               "    Delimiters:\n"
17834               "      - 'pb'\n"
17835               "      - 'proto'\n"
17836               "    EnclosingFunctions:\n"
17837               "      - 'PARSE_TEXT_PROTO'\n"
17838               "    BasedOnStyle: llvm\n"
17839               "  - Language: Cpp\n"
17840               "    Delimiters:\n"
17841               "      - 'cc'\n"
17842               "      - 'cpp'\n"
17843               "    EnclosingFunctions:\n"
17844               "      - 'C_CODEBLOCK'\n"
17845               "      - 'CPPEVAL'\n"
17846               "    CanonicalDelimiter: 'cc'",
17847               RawStringFormats, ExpectedRawStringFormats);
17848 
17849   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
17850               "  Minimum: 0\n"
17851               "  Maximum: 0",
17852               SpacesInLineCommentPrefix.Minimum, 0u);
17853   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
17854   Style.SpacesInLineCommentPrefix.Minimum = 1;
17855   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
17856               "  Minimum: 2",
17857               SpacesInLineCommentPrefix.Minimum, 0u);
17858   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
17859               "  Maximum: -1",
17860               SpacesInLineCommentPrefix.Maximum, -1u);
17861   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
17862               "  Minimum: 2",
17863               SpacesInLineCommentPrefix.Minimum, 2u);
17864   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
17865               "  Maximum: 1",
17866               SpacesInLineCommentPrefix.Maximum, 1u);
17867   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
17868 
17869   Style.SpacesInAngles = FormatStyle::SIAS_Always;
17870   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
17871   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
17872               FormatStyle::SIAS_Always);
17873   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
17874   // For backward compatibility:
17875   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
17876   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
17877 }
17878 
17879 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
17880   FormatStyle Style = {};
17881   Style.Language = FormatStyle::LK_Cpp;
17882   CHECK_PARSE("Language: Cpp\n"
17883               "IndentWidth: 12",
17884               IndentWidth, 12u);
17885   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
17886                                "IndentWidth: 34",
17887                                &Style),
17888             ParseError::Unsuitable);
17889   FormatStyle BinPackedTCS = {};
17890   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
17891   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
17892                                "InsertTrailingCommas: Wrapped",
17893                                &BinPackedTCS),
17894             ParseError::BinPackTrailingCommaConflict);
17895   EXPECT_EQ(12u, Style.IndentWidth);
17896   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
17897   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
17898 
17899   Style.Language = FormatStyle::LK_JavaScript;
17900   CHECK_PARSE("Language: JavaScript\n"
17901               "IndentWidth: 12",
17902               IndentWidth, 12u);
17903   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
17904   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
17905                                "IndentWidth: 34",
17906                                &Style),
17907             ParseError::Unsuitable);
17908   EXPECT_EQ(23u, Style.IndentWidth);
17909   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
17910   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
17911 
17912   CHECK_PARSE("BasedOnStyle: LLVM\n"
17913               "IndentWidth: 67",
17914               IndentWidth, 67u);
17915 
17916   CHECK_PARSE("---\n"
17917               "Language: JavaScript\n"
17918               "IndentWidth: 12\n"
17919               "---\n"
17920               "Language: Cpp\n"
17921               "IndentWidth: 34\n"
17922               "...\n",
17923               IndentWidth, 12u);
17924 
17925   Style.Language = FormatStyle::LK_Cpp;
17926   CHECK_PARSE("---\n"
17927               "Language: JavaScript\n"
17928               "IndentWidth: 12\n"
17929               "---\n"
17930               "Language: Cpp\n"
17931               "IndentWidth: 34\n"
17932               "...\n",
17933               IndentWidth, 34u);
17934   CHECK_PARSE("---\n"
17935               "IndentWidth: 78\n"
17936               "---\n"
17937               "Language: JavaScript\n"
17938               "IndentWidth: 56\n"
17939               "...\n",
17940               IndentWidth, 78u);
17941 
17942   Style.ColumnLimit = 123;
17943   Style.IndentWidth = 234;
17944   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
17945   Style.TabWidth = 345;
17946   EXPECT_FALSE(parseConfiguration("---\n"
17947                                   "IndentWidth: 456\n"
17948                                   "BreakBeforeBraces: Allman\n"
17949                                   "---\n"
17950                                   "Language: JavaScript\n"
17951                                   "IndentWidth: 111\n"
17952                                   "TabWidth: 111\n"
17953                                   "---\n"
17954                                   "Language: Cpp\n"
17955                                   "BreakBeforeBraces: Stroustrup\n"
17956                                   "TabWidth: 789\n"
17957                                   "...\n",
17958                                   &Style));
17959   EXPECT_EQ(123u, Style.ColumnLimit);
17960   EXPECT_EQ(456u, Style.IndentWidth);
17961   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
17962   EXPECT_EQ(789u, Style.TabWidth);
17963 
17964   EXPECT_EQ(parseConfiguration("---\n"
17965                                "Language: JavaScript\n"
17966                                "IndentWidth: 56\n"
17967                                "---\n"
17968                                "IndentWidth: 78\n"
17969                                "...\n",
17970                                &Style),
17971             ParseError::Error);
17972   EXPECT_EQ(parseConfiguration("---\n"
17973                                "Language: JavaScript\n"
17974                                "IndentWidth: 56\n"
17975                                "---\n"
17976                                "Language: JavaScript\n"
17977                                "IndentWidth: 78\n"
17978                                "...\n",
17979                                &Style),
17980             ParseError::Error);
17981 
17982   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
17983 }
17984 
17985 #undef CHECK_PARSE
17986 
17987 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
17988   FormatStyle Style = {};
17989   Style.Language = FormatStyle::LK_JavaScript;
17990   Style.BreakBeforeTernaryOperators = true;
17991   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
17992   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
17993 
17994   Style.BreakBeforeTernaryOperators = true;
17995   EXPECT_EQ(0, parseConfiguration("---\n"
17996                                   "BasedOnStyle: Google\n"
17997                                   "---\n"
17998                                   "Language: JavaScript\n"
17999                                   "IndentWidth: 76\n"
18000                                   "...\n",
18001                                   &Style)
18002                    .value());
18003   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
18004   EXPECT_EQ(76u, Style.IndentWidth);
18005   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
18006 }
18007 
18008 TEST_F(FormatTest, ConfigurationRoundTripTest) {
18009   FormatStyle Style = getLLVMStyle();
18010   std::string YAML = configurationAsText(Style);
18011   FormatStyle ParsedStyle = {};
18012   ParsedStyle.Language = FormatStyle::LK_Cpp;
18013   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
18014   EXPECT_EQ(Style, ParsedStyle);
18015 }
18016 
18017 TEST_F(FormatTest, WorksFor8bitEncodings) {
18018   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
18019             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
18020             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
18021             "\"\xef\xee\xf0\xf3...\"",
18022             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
18023                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
18024                    "\xef\xee\xf0\xf3...\"",
18025                    getLLVMStyleWithColumns(12)));
18026 }
18027 
18028 TEST_F(FormatTest, HandlesUTF8BOM) {
18029   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
18030   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
18031             format("\xef\xbb\xbf#include <iostream>"));
18032   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
18033             format("\xef\xbb\xbf\n#include <iostream>"));
18034 }
18035 
18036 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
18037 #if !defined(_MSC_VER)
18038 
18039 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
18040   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
18041                getLLVMStyleWithColumns(35));
18042   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
18043                getLLVMStyleWithColumns(31));
18044   verifyFormat("// Однажды в студёную зимнюю пору...",
18045                getLLVMStyleWithColumns(36));
18046   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
18047   verifyFormat("/* Однажды в студёную зимнюю пору... */",
18048                getLLVMStyleWithColumns(39));
18049   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
18050                getLLVMStyleWithColumns(35));
18051 }
18052 
18053 TEST_F(FormatTest, SplitsUTF8Strings) {
18054   // Non-printable characters' width is currently considered to be the length in
18055   // bytes in UTF8. The characters can be displayed in very different manner
18056   // (zero-width, single width with a substitution glyph, expanded to their code
18057   // (e.g. "<8d>"), so there's no single correct way to handle them.
18058   EXPECT_EQ("\"aaaaÄ\"\n"
18059             "\"\xc2\x8d\";",
18060             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
18061   EXPECT_EQ("\"aaaaaaaÄ\"\n"
18062             "\"\xc2\x8d\";",
18063             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
18064   EXPECT_EQ("\"Однажды, в \"\n"
18065             "\"студёную \"\n"
18066             "\"зимнюю \"\n"
18067             "\"пору,\"",
18068             format("\"Однажды, в студёную зимнюю пору,\"",
18069                    getLLVMStyleWithColumns(13)));
18070   EXPECT_EQ(
18071       "\"一 二 三 \"\n"
18072       "\"四 五六 \"\n"
18073       "\"七 八 九 \"\n"
18074       "\"十\"",
18075       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
18076   EXPECT_EQ("\"一\t\"\n"
18077             "\"二 \t\"\n"
18078             "\"三 四 \"\n"
18079             "\"五\t\"\n"
18080             "\"六 \t\"\n"
18081             "\"七 \"\n"
18082             "\"八九十\tqq\"",
18083             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
18084                    getLLVMStyleWithColumns(11)));
18085 
18086   // UTF8 character in an escape sequence.
18087   EXPECT_EQ("\"aaaaaa\"\n"
18088             "\"\\\xC2\x8D\"",
18089             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
18090 }
18091 
18092 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
18093   EXPECT_EQ("const char *sssss =\n"
18094             "    \"一二三四五六七八\\\n"
18095             " 九 十\";",
18096             format("const char *sssss = \"一二三四五六七八\\\n"
18097                    " 九 十\";",
18098                    getLLVMStyleWithColumns(30)));
18099 }
18100 
18101 TEST_F(FormatTest, SplitsUTF8LineComments) {
18102   EXPECT_EQ("// aaaaÄ\xc2\x8d",
18103             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
18104   EXPECT_EQ("// Я из лесу\n"
18105             "// вышел; был\n"
18106             "// сильный\n"
18107             "// мороз.",
18108             format("// Я из лесу вышел; был сильный мороз.",
18109                    getLLVMStyleWithColumns(13)));
18110   EXPECT_EQ("// 一二三\n"
18111             "// 四五六七\n"
18112             "// 八  九\n"
18113             "// 十",
18114             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
18115 }
18116 
18117 TEST_F(FormatTest, SplitsUTF8BlockComments) {
18118   EXPECT_EQ("/* Гляжу,\n"
18119             " * поднимается\n"
18120             " * медленно в\n"
18121             " * гору\n"
18122             " * Лошадка,\n"
18123             " * везущая\n"
18124             " * хворосту\n"
18125             " * воз. */",
18126             format("/* Гляжу, поднимается медленно в гору\n"
18127                    " * Лошадка, везущая хворосту воз. */",
18128                    getLLVMStyleWithColumns(13)));
18129   EXPECT_EQ(
18130       "/* 一二三\n"
18131       " * 四五六七\n"
18132       " * 八  九\n"
18133       " * 十  */",
18134       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
18135   EXPECT_EQ("/* �������� ��������\n"
18136             " * ��������\n"
18137             " * ������-�� */",
18138             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
18139 }
18140 
18141 #endif // _MSC_VER
18142 
18143 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
18144   FormatStyle Style = getLLVMStyle();
18145 
18146   Style.ConstructorInitializerIndentWidth = 4;
18147   verifyFormat(
18148       "SomeClass::Constructor()\n"
18149       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
18150       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
18151       Style);
18152 
18153   Style.ConstructorInitializerIndentWidth = 2;
18154   verifyFormat(
18155       "SomeClass::Constructor()\n"
18156       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
18157       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
18158       Style);
18159 
18160   Style.ConstructorInitializerIndentWidth = 0;
18161   verifyFormat(
18162       "SomeClass::Constructor()\n"
18163       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
18164       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
18165       Style);
18166   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
18167   verifyFormat(
18168       "SomeLongTemplateVariableName<\n"
18169       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
18170       Style);
18171   verifyFormat("bool smaller = 1 < "
18172                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
18173                "                       "
18174                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
18175                Style);
18176 
18177   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
18178   verifyFormat("SomeClass::Constructor() :\n"
18179                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
18180                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
18181                Style);
18182 }
18183 
18184 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
18185   FormatStyle Style = getLLVMStyle();
18186   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
18187   Style.ConstructorInitializerIndentWidth = 4;
18188   verifyFormat("SomeClass::Constructor()\n"
18189                "    : a(a)\n"
18190                "    , b(b)\n"
18191                "    , c(c) {}",
18192                Style);
18193   verifyFormat("SomeClass::Constructor()\n"
18194                "    : a(a) {}",
18195                Style);
18196 
18197   Style.ColumnLimit = 0;
18198   verifyFormat("SomeClass::Constructor()\n"
18199                "    : a(a) {}",
18200                Style);
18201   verifyFormat("SomeClass::Constructor() noexcept\n"
18202                "    : a(a) {}",
18203                Style);
18204   verifyFormat("SomeClass::Constructor()\n"
18205                "    : a(a)\n"
18206                "    , b(b)\n"
18207                "    , c(c) {}",
18208                Style);
18209   verifyFormat("SomeClass::Constructor()\n"
18210                "    : a(a) {\n"
18211                "  foo();\n"
18212                "  bar();\n"
18213                "}",
18214                Style);
18215 
18216   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
18217   verifyFormat("SomeClass::Constructor()\n"
18218                "    : a(a)\n"
18219                "    , b(b)\n"
18220                "    , c(c) {\n}",
18221                Style);
18222   verifyFormat("SomeClass::Constructor()\n"
18223                "    : a(a) {\n}",
18224                Style);
18225 
18226   Style.ColumnLimit = 80;
18227   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
18228   Style.ConstructorInitializerIndentWidth = 2;
18229   verifyFormat("SomeClass::Constructor()\n"
18230                "  : a(a)\n"
18231                "  , b(b)\n"
18232                "  , c(c) {}",
18233                Style);
18234 
18235   Style.ConstructorInitializerIndentWidth = 0;
18236   verifyFormat("SomeClass::Constructor()\n"
18237                ": a(a)\n"
18238                ", b(b)\n"
18239                ", c(c) {}",
18240                Style);
18241 
18242   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
18243   Style.ConstructorInitializerIndentWidth = 4;
18244   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
18245   verifyFormat(
18246       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
18247       Style);
18248   verifyFormat(
18249       "SomeClass::Constructor()\n"
18250       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
18251       Style);
18252   Style.ConstructorInitializerIndentWidth = 4;
18253   Style.ColumnLimit = 60;
18254   verifyFormat("SomeClass::Constructor()\n"
18255                "    : aaaaaaaa(aaaaaaaa)\n"
18256                "    , aaaaaaaa(aaaaaaaa)\n"
18257                "    , aaaaaaaa(aaaaaaaa) {}",
18258                Style);
18259 }
18260 
18261 TEST_F(FormatTest, Destructors) {
18262   verifyFormat("void F(int &i) { i.~int(); }");
18263   verifyFormat("void F(int &i) { i->~int(); }");
18264 }
18265 
18266 TEST_F(FormatTest, FormatsWithWebKitStyle) {
18267   FormatStyle Style = getWebKitStyle();
18268 
18269   // Don't indent in outer namespaces.
18270   verifyFormat("namespace outer {\n"
18271                "int i;\n"
18272                "namespace inner {\n"
18273                "    int i;\n"
18274                "} // namespace inner\n"
18275                "} // namespace outer\n"
18276                "namespace other_outer {\n"
18277                "int i;\n"
18278                "}",
18279                Style);
18280 
18281   // Don't indent case labels.
18282   verifyFormat("switch (variable) {\n"
18283                "case 1:\n"
18284                "case 2:\n"
18285                "    doSomething();\n"
18286                "    break;\n"
18287                "default:\n"
18288                "    ++variable;\n"
18289                "}",
18290                Style);
18291 
18292   // Wrap before binary operators.
18293   EXPECT_EQ("void f()\n"
18294             "{\n"
18295             "    if (aaaaaaaaaaaaaaaa\n"
18296             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
18297             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
18298             "        return;\n"
18299             "}",
18300             format("void f() {\n"
18301                    "if (aaaaaaaaaaaaaaaa\n"
18302                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
18303                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
18304                    "return;\n"
18305                    "}",
18306                    Style));
18307 
18308   // Allow functions on a single line.
18309   verifyFormat("void f() { return; }", Style);
18310 
18311   // Allow empty blocks on a single line and insert a space in empty blocks.
18312   EXPECT_EQ("void f() { }", format("void f() {}", Style));
18313   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
18314   // However, don't merge non-empty short loops.
18315   EXPECT_EQ("while (true) {\n"
18316             "    continue;\n"
18317             "}",
18318             format("while (true) { continue; }", Style));
18319 
18320   // Constructor initializers are formatted one per line with the "," on the
18321   // new line.
18322   verifyFormat("Constructor()\n"
18323                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
18324                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
18325                "          aaaaaaaaaaaaaa)\n"
18326                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
18327                "{\n"
18328                "}",
18329                Style);
18330   verifyFormat("SomeClass::Constructor()\n"
18331                "    : a(a)\n"
18332                "{\n"
18333                "}",
18334                Style);
18335   EXPECT_EQ("SomeClass::Constructor()\n"
18336             "    : a(a)\n"
18337             "{\n"
18338             "}",
18339             format("SomeClass::Constructor():a(a){}", Style));
18340   verifyFormat("SomeClass::Constructor()\n"
18341                "    : a(a)\n"
18342                "    , b(b)\n"
18343                "    , c(c)\n"
18344                "{\n"
18345                "}",
18346                Style);
18347   verifyFormat("SomeClass::Constructor()\n"
18348                "    : a(a)\n"
18349                "{\n"
18350                "    foo();\n"
18351                "    bar();\n"
18352                "}",
18353                Style);
18354 
18355   // Access specifiers should be aligned left.
18356   verifyFormat("class C {\n"
18357                "public:\n"
18358                "    int i;\n"
18359                "};",
18360                Style);
18361 
18362   // Do not align comments.
18363   verifyFormat("int a; // Do not\n"
18364                "double b; // align comments.",
18365                Style);
18366 
18367   // Do not align operands.
18368   EXPECT_EQ("ASSERT(aaaa\n"
18369             "    || bbbb);",
18370             format("ASSERT ( aaaa\n||bbbb);", Style));
18371 
18372   // Accept input's line breaks.
18373   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
18374             "    || bbbbbbbbbbbbbbb) {\n"
18375             "    i++;\n"
18376             "}",
18377             format("if (aaaaaaaaaaaaaaa\n"
18378                    "|| bbbbbbbbbbbbbbb) { i++; }",
18379                    Style));
18380   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
18381             "    i++;\n"
18382             "}",
18383             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
18384 
18385   // Don't automatically break all macro definitions (llvm.org/PR17842).
18386   verifyFormat("#define aNumber 10", Style);
18387   // However, generally keep the line breaks that the user authored.
18388   EXPECT_EQ("#define aNumber \\\n"
18389             "    10",
18390             format("#define aNumber \\\n"
18391                    " 10",
18392                    Style));
18393 
18394   // Keep empty and one-element array literals on a single line.
18395   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
18396             "                                  copyItems:YES];",
18397             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
18398                    "copyItems:YES];",
18399                    Style));
18400   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
18401             "                                  copyItems:YES];",
18402             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
18403                    "             copyItems:YES];",
18404                    Style));
18405   // FIXME: This does not seem right, there should be more indentation before
18406   // the array literal's entries. Nested blocks have the same problem.
18407   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
18408             "    @\"a\",\n"
18409             "    @\"a\"\n"
18410             "]\n"
18411             "                                  copyItems:YES];",
18412             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
18413                    "     @\"a\",\n"
18414                    "     @\"a\"\n"
18415                    "     ]\n"
18416                    "       copyItems:YES];",
18417                    Style));
18418   EXPECT_EQ(
18419       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
18420       "                                  copyItems:YES];",
18421       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
18422              "   copyItems:YES];",
18423              Style));
18424 
18425   verifyFormat("[self.a b:c c:d];", Style);
18426   EXPECT_EQ("[self.a b:c\n"
18427             "        c:d];",
18428             format("[self.a b:c\n"
18429                    "c:d];",
18430                    Style));
18431 }
18432 
18433 TEST_F(FormatTest, FormatsLambdas) {
18434   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
18435   verifyFormat(
18436       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
18437   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
18438   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
18439   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
18440   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
18441   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
18442   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
18443   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
18444   verifyFormat("int x = f(*+[] {});");
18445   verifyFormat("void f() {\n"
18446                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
18447                "}\n");
18448   verifyFormat("void f() {\n"
18449                "  other(x.begin(), //\n"
18450                "        x.end(),   //\n"
18451                "        [&](int, int) { return 1; });\n"
18452                "}\n");
18453   verifyFormat("void f() {\n"
18454                "  other.other.other.other.other(\n"
18455                "      x.begin(), x.end(),\n"
18456                "      [something, rather](int, int, int, int, int, int, int) { "
18457                "return 1; });\n"
18458                "}\n");
18459   verifyFormat(
18460       "void f() {\n"
18461       "  other.other.other.other.other(\n"
18462       "      x.begin(), x.end(),\n"
18463       "      [something, rather](int, int, int, int, int, int, int) {\n"
18464       "        //\n"
18465       "      });\n"
18466       "}\n");
18467   verifyFormat("SomeFunction([]() { // A cool function...\n"
18468                "  return 43;\n"
18469                "});");
18470   EXPECT_EQ("SomeFunction([]() {\n"
18471             "#define A a\n"
18472             "  return 43;\n"
18473             "});",
18474             format("SomeFunction([](){\n"
18475                    "#define A a\n"
18476                    "return 43;\n"
18477                    "});"));
18478   verifyFormat("void f() {\n"
18479                "  SomeFunction([](decltype(x), A *a) {});\n"
18480                "  SomeFunction([](typeof(x), A *a) {});\n"
18481                "  SomeFunction([](_Atomic(x), A *a) {});\n"
18482                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
18483                "}");
18484   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
18485                "    [](const aaaaaaaaaa &a) { return a; });");
18486   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
18487                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
18488                "});");
18489   verifyFormat("Constructor()\n"
18490                "    : Field([] { // comment\n"
18491                "        int i;\n"
18492                "      }) {}");
18493   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
18494                "  return some_parameter.size();\n"
18495                "};");
18496   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
18497                "    [](const string &s) { return s; };");
18498   verifyFormat("int i = aaaaaa ? 1 //\n"
18499                "               : [] {\n"
18500                "                   return 2; //\n"
18501                "                 }();");
18502   verifyFormat("llvm::errs() << \"number of twos is \"\n"
18503                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
18504                "                  return x == 2; // force break\n"
18505                "                });");
18506   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
18507                "    [=](int iiiiiiiiiiii) {\n"
18508                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
18509                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
18510                "    });",
18511                getLLVMStyleWithColumns(60));
18512   verifyFormat("SomeFunction({[&] {\n"
18513                "                // comment\n"
18514                "              },\n"
18515                "              [&] {\n"
18516                "                // comment\n"
18517                "              }});");
18518   verifyFormat("SomeFunction({[&] {\n"
18519                "  // comment\n"
18520                "}});");
18521   verifyFormat(
18522       "virtual aaaaaaaaaaaaaaaa(\n"
18523       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
18524       "    aaaaa aaaaaaaaa);");
18525 
18526   // Lambdas with return types.
18527   verifyFormat("int c = []() -> int { return 2; }();\n");
18528   verifyFormat("int c = []() -> int * { return 2; }();\n");
18529   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
18530   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
18531   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
18532   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
18533   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
18534   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
18535   verifyFormat("[a, a]() -> a<1> {};");
18536   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
18537   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
18538   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
18539   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
18540   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
18541   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
18542   verifyFormat("[]() -> foo<!5> { return {}; };");
18543   verifyFormat("[]() -> foo<~5> { return {}; };");
18544   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
18545   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
18546   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
18547   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
18548   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
18549   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
18550   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
18551   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
18552   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
18553   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
18554   verifyFormat("namespace bar {\n"
18555                "// broken:\n"
18556                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
18557                "} // namespace bar");
18558   verifyFormat("namespace bar {\n"
18559                "// broken:\n"
18560                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
18561                "} // namespace bar");
18562   verifyFormat("namespace bar {\n"
18563                "// broken:\n"
18564                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
18565                "} // namespace bar");
18566   verifyFormat("namespace bar {\n"
18567                "// broken:\n"
18568                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
18569                "} // namespace bar");
18570   verifyFormat("namespace bar {\n"
18571                "// broken:\n"
18572                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
18573                "} // namespace bar");
18574   verifyFormat("namespace bar {\n"
18575                "// broken:\n"
18576                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
18577                "} // namespace bar");
18578   verifyFormat("namespace bar {\n"
18579                "// broken:\n"
18580                "auto foo{[]() -> foo<!5> { return {}; }};\n"
18581                "} // namespace bar");
18582   verifyFormat("namespace bar {\n"
18583                "// broken:\n"
18584                "auto foo{[]() -> foo<~5> { return {}; }};\n"
18585                "} // namespace bar");
18586   verifyFormat("namespace bar {\n"
18587                "// broken:\n"
18588                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
18589                "} // namespace bar");
18590   verifyFormat("namespace bar {\n"
18591                "// broken:\n"
18592                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
18593                "} // namespace bar");
18594   verifyFormat("namespace bar {\n"
18595                "// broken:\n"
18596                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
18597                "} // namespace bar");
18598   verifyFormat("namespace bar {\n"
18599                "// broken:\n"
18600                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
18601                "} // namespace bar");
18602   verifyFormat("namespace bar {\n"
18603                "// broken:\n"
18604                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
18605                "} // namespace bar");
18606   verifyFormat("namespace bar {\n"
18607                "// broken:\n"
18608                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
18609                "} // namespace bar");
18610   verifyFormat("namespace bar {\n"
18611                "// broken:\n"
18612                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
18613                "} // namespace bar");
18614   verifyFormat("namespace bar {\n"
18615                "// broken:\n"
18616                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
18617                "} // namespace bar");
18618   verifyFormat("namespace bar {\n"
18619                "// broken:\n"
18620                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
18621                "} // namespace bar");
18622   verifyFormat("namespace bar {\n"
18623                "// broken:\n"
18624                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
18625                "} // namespace bar");
18626   verifyFormat("[]() -> a<1> {};");
18627   verifyFormat("[]() -> a<1> { ; };");
18628   verifyFormat("[]() -> a<1> { ; }();");
18629   verifyFormat("[a, a]() -> a<true> {};");
18630   verifyFormat("[]() -> a<true> {};");
18631   verifyFormat("[]() -> a<true> { ; };");
18632   verifyFormat("[]() -> a<true> { ; }();");
18633   verifyFormat("[a, a]() -> a<false> {};");
18634   verifyFormat("[]() -> a<false> {};");
18635   verifyFormat("[]() -> a<false> { ; };");
18636   verifyFormat("[]() -> a<false> { ; }();");
18637   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
18638   verifyFormat("namespace bar {\n"
18639                "auto foo{[]() -> foo<false> { ; }};\n"
18640                "} // namespace bar");
18641   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
18642                "                   int j) -> int {\n"
18643                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
18644                "};");
18645   verifyFormat(
18646       "aaaaaaaaaaaaaaaaaaaaaa(\n"
18647       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
18648       "      return aaaaaaaaaaaaaaaaa;\n"
18649       "    });",
18650       getLLVMStyleWithColumns(70));
18651   verifyFormat("[]() //\n"
18652                "    -> int {\n"
18653                "  return 1; //\n"
18654                "};");
18655   verifyFormat("[]() -> Void<T...> {};");
18656   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
18657 
18658   // Lambdas with explicit template argument lists.
18659   verifyFormat(
18660       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
18661 
18662   // Multiple lambdas in the same parentheses change indentation rules. These
18663   // lambdas are forced to start on new lines.
18664   verifyFormat("SomeFunction(\n"
18665                "    []() {\n"
18666                "      //\n"
18667                "    },\n"
18668                "    []() {\n"
18669                "      //\n"
18670                "    });");
18671 
18672   // A lambda passed as arg0 is always pushed to the next line.
18673   verifyFormat("SomeFunction(\n"
18674                "    [this] {\n"
18675                "      //\n"
18676                "    },\n"
18677                "    1);\n");
18678 
18679   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
18680   // the arg0 case above.
18681   auto Style = getGoogleStyle();
18682   Style.BinPackArguments = false;
18683   verifyFormat("SomeFunction(\n"
18684                "    a,\n"
18685                "    [this] {\n"
18686                "      //\n"
18687                "    },\n"
18688                "    b);\n",
18689                Style);
18690   verifyFormat("SomeFunction(\n"
18691                "    a,\n"
18692                "    [this] {\n"
18693                "      //\n"
18694                "    },\n"
18695                "    b);\n");
18696 
18697   // A lambda with a very long line forces arg0 to be pushed out irrespective of
18698   // the BinPackArguments value (as long as the code is wide enough).
18699   verifyFormat(
18700       "something->SomeFunction(\n"
18701       "    a,\n"
18702       "    [this] {\n"
18703       "      "
18704       "D0000000000000000000000000000000000000000000000000000000000001();\n"
18705       "    },\n"
18706       "    b);\n");
18707 
18708   // A multi-line lambda is pulled up as long as the introducer fits on the
18709   // previous line and there are no further args.
18710   verifyFormat("function(1, [this, that] {\n"
18711                "  //\n"
18712                "});\n");
18713   verifyFormat("function([this, that] {\n"
18714                "  //\n"
18715                "});\n");
18716   // FIXME: this format is not ideal and we should consider forcing the first
18717   // arg onto its own line.
18718   verifyFormat("function(a, b, c, //\n"
18719                "         d, [this, that] {\n"
18720                "           //\n"
18721                "         });\n");
18722 
18723   // Multiple lambdas are treated correctly even when there is a short arg0.
18724   verifyFormat("SomeFunction(\n"
18725                "    1,\n"
18726                "    [this] {\n"
18727                "      //\n"
18728                "    },\n"
18729                "    [this] {\n"
18730                "      //\n"
18731                "    },\n"
18732                "    1);\n");
18733 
18734   // More complex introducers.
18735   verifyFormat("return [i, args...] {};");
18736 
18737   // Not lambdas.
18738   verifyFormat("constexpr char hello[]{\"hello\"};");
18739   verifyFormat("double &operator[](int i) { return 0; }\n"
18740                "int i;");
18741   verifyFormat("std::unique_ptr<int[]> foo() {}");
18742   verifyFormat("int i = a[a][a]->f();");
18743   verifyFormat("int i = (*b)[a]->f();");
18744 
18745   // Other corner cases.
18746   verifyFormat("void f() {\n"
18747                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
18748                "  );\n"
18749                "}");
18750 
18751   // Lambdas created through weird macros.
18752   verifyFormat("void f() {\n"
18753                "  MACRO((const AA &a) { return 1; });\n"
18754                "  MACRO((AA &a) { return 1; });\n"
18755                "}");
18756 
18757   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
18758                "      doo_dah();\n"
18759                "      doo_dah();\n"
18760                "    })) {\n"
18761                "}");
18762   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
18763                "                doo_dah();\n"
18764                "                doo_dah();\n"
18765                "              })) {\n"
18766                "}");
18767   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
18768                "                doo_dah();\n"
18769                "                doo_dah();\n"
18770                "              })) {\n"
18771                "}");
18772   verifyFormat("auto lambda = []() {\n"
18773                "  int a = 2\n"
18774                "#if A\n"
18775                "          + 2\n"
18776                "#endif\n"
18777                "      ;\n"
18778                "};");
18779 
18780   // Lambdas with complex multiline introducers.
18781   verifyFormat(
18782       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
18783       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
18784       "        -> ::std::unordered_set<\n"
18785       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
18786       "      //\n"
18787       "    });");
18788 
18789   FormatStyle DoNotMerge = getLLVMStyle();
18790   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18791   verifyFormat("auto c = []() {\n"
18792                "  return b;\n"
18793                "};",
18794                "auto c = []() { return b; };", DoNotMerge);
18795   verifyFormat("auto c = []() {\n"
18796                "};",
18797                " auto c = []() {};", DoNotMerge);
18798 
18799   FormatStyle MergeEmptyOnly = getLLVMStyle();
18800   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
18801   verifyFormat("auto c = []() {\n"
18802                "  return b;\n"
18803                "};",
18804                "auto c = []() {\n"
18805                "  return b;\n"
18806                " };",
18807                MergeEmptyOnly);
18808   verifyFormat("auto c = []() {};",
18809                "auto c = []() {\n"
18810                "};",
18811                MergeEmptyOnly);
18812 
18813   FormatStyle MergeInline = getLLVMStyle();
18814   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
18815   verifyFormat("auto c = []() {\n"
18816                "  return b;\n"
18817                "};",
18818                "auto c = []() { return b; };", MergeInline);
18819   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
18820                MergeInline);
18821   verifyFormat("function([]() { return b; }, a)",
18822                "function([]() { return b; }, a)", MergeInline);
18823   verifyFormat("function(a, []() { return b; })",
18824                "function(a, []() { return b; })", MergeInline);
18825 
18826   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
18827   // AllowShortLambdasOnASingleLine
18828   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
18829   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
18830   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
18831   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
18832       FormatStyle::ShortLambdaStyle::SLS_None;
18833   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
18834                "    []()\n"
18835                "    {\n"
18836                "      return 17;\n"
18837                "    });",
18838                LLVMWithBeforeLambdaBody);
18839   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
18840                "    []()\n"
18841                "    {\n"
18842                "    });",
18843                LLVMWithBeforeLambdaBody);
18844   verifyFormat("auto fct_SLS_None = []()\n"
18845                "{\n"
18846                "  return 17;\n"
18847                "};",
18848                LLVMWithBeforeLambdaBody);
18849   verifyFormat("TwoNestedLambdas_SLS_None(\n"
18850                "    []()\n"
18851                "    {\n"
18852                "      return Call(\n"
18853                "          []()\n"
18854                "          {\n"
18855                "            return 17;\n"
18856                "          });\n"
18857                "    });",
18858                LLVMWithBeforeLambdaBody);
18859   verifyFormat("void Fct()\n"
18860                "{\n"
18861                "  return {[]()\n"
18862                "          {\n"
18863                "            return 17;\n"
18864                "          }};\n"
18865                "}",
18866                LLVMWithBeforeLambdaBody);
18867 
18868   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
18869       FormatStyle::ShortLambdaStyle::SLS_Empty;
18870   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
18871                "    []()\n"
18872                "    {\n"
18873                "      return 17;\n"
18874                "    });",
18875                LLVMWithBeforeLambdaBody);
18876   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
18877                LLVMWithBeforeLambdaBody);
18878   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
18879                "ongFunctionName_SLS_Empty(\n"
18880                "    []() {});",
18881                LLVMWithBeforeLambdaBody);
18882   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
18883                "                                []()\n"
18884                "                                {\n"
18885                "                                  return 17;\n"
18886                "                                });",
18887                LLVMWithBeforeLambdaBody);
18888   verifyFormat("auto fct_SLS_Empty = []()\n"
18889                "{\n"
18890                "  return 17;\n"
18891                "};",
18892                LLVMWithBeforeLambdaBody);
18893   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
18894                "    []()\n"
18895                "    {\n"
18896                "      return Call([]() {});\n"
18897                "    });",
18898                LLVMWithBeforeLambdaBody);
18899   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
18900                "                           []()\n"
18901                "                           {\n"
18902                "                             return Call([]() {});\n"
18903                "                           });",
18904                LLVMWithBeforeLambdaBody);
18905   verifyFormat(
18906       "FctWithLongLineInLambda_SLS_Empty(\n"
18907       "    []()\n"
18908       "    {\n"
18909       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
18910       "                               AndShouldNotBeConsiderAsInline,\n"
18911       "                               LambdaBodyMustBeBreak);\n"
18912       "    });",
18913       LLVMWithBeforeLambdaBody);
18914 
18915   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
18916       FormatStyle::ShortLambdaStyle::SLS_Inline;
18917   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
18918                LLVMWithBeforeLambdaBody);
18919   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
18920                LLVMWithBeforeLambdaBody);
18921   verifyFormat("auto fct_SLS_Inline = []()\n"
18922                "{\n"
18923                "  return 17;\n"
18924                "};",
18925                LLVMWithBeforeLambdaBody);
18926   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
18927                "17; }); });",
18928                LLVMWithBeforeLambdaBody);
18929   verifyFormat(
18930       "FctWithLongLineInLambda_SLS_Inline(\n"
18931       "    []()\n"
18932       "    {\n"
18933       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
18934       "                               AndShouldNotBeConsiderAsInline,\n"
18935       "                               LambdaBodyMustBeBreak);\n"
18936       "    });",
18937       LLVMWithBeforeLambdaBody);
18938   verifyFormat("FctWithMultipleParams_SLS_Inline("
18939                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
18940                "                                 []() { return 17; });",
18941                LLVMWithBeforeLambdaBody);
18942   verifyFormat(
18943       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
18944       LLVMWithBeforeLambdaBody);
18945 
18946   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
18947       FormatStyle::ShortLambdaStyle::SLS_All;
18948   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
18949                LLVMWithBeforeLambdaBody);
18950   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
18951                LLVMWithBeforeLambdaBody);
18952   verifyFormat("auto fct_SLS_All = []() { return 17; };",
18953                LLVMWithBeforeLambdaBody);
18954   verifyFormat("FctWithOneParam_SLS_All(\n"
18955                "    []()\n"
18956                "    {\n"
18957                "      // A cool function...\n"
18958                "      return 43;\n"
18959                "    });",
18960                LLVMWithBeforeLambdaBody);
18961   verifyFormat("FctWithMultipleParams_SLS_All("
18962                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
18963                "                              []() { return 17; });",
18964                LLVMWithBeforeLambdaBody);
18965   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
18966                LLVMWithBeforeLambdaBody);
18967   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
18968                LLVMWithBeforeLambdaBody);
18969   verifyFormat(
18970       "FctWithLongLineInLambda_SLS_All(\n"
18971       "    []()\n"
18972       "    {\n"
18973       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
18974       "                               AndShouldNotBeConsiderAsInline,\n"
18975       "                               LambdaBodyMustBeBreak);\n"
18976       "    });",
18977       LLVMWithBeforeLambdaBody);
18978   verifyFormat(
18979       "auto fct_SLS_All = []()\n"
18980       "{\n"
18981       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
18982       "                           AndShouldNotBeConsiderAsInline,\n"
18983       "                           LambdaBodyMustBeBreak);\n"
18984       "};",
18985       LLVMWithBeforeLambdaBody);
18986   LLVMWithBeforeLambdaBody.BinPackParameters = false;
18987   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
18988                LLVMWithBeforeLambdaBody);
18989   verifyFormat(
18990       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
18991       "                                FirstParam,\n"
18992       "                                SecondParam,\n"
18993       "                                ThirdParam,\n"
18994       "                                FourthParam);",
18995       LLVMWithBeforeLambdaBody);
18996   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
18997                "    []() { return "
18998                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
18999                "    FirstParam,\n"
19000                "    SecondParam,\n"
19001                "    ThirdParam,\n"
19002                "    FourthParam);",
19003                LLVMWithBeforeLambdaBody);
19004   verifyFormat(
19005       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
19006       "                                SecondParam,\n"
19007       "                                ThirdParam,\n"
19008       "                                FourthParam,\n"
19009       "                                []() { return SomeValueNotSoLong; });",
19010       LLVMWithBeforeLambdaBody);
19011   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
19012                "    []()\n"
19013                "    {\n"
19014                "      return "
19015                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
19016                "eConsiderAsInline;\n"
19017                "    });",
19018                LLVMWithBeforeLambdaBody);
19019   verifyFormat(
19020       "FctWithLongLineInLambda_SLS_All(\n"
19021       "    []()\n"
19022       "    {\n"
19023       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
19024       "                               AndShouldNotBeConsiderAsInline,\n"
19025       "                               LambdaBodyMustBeBreak);\n"
19026       "    });",
19027       LLVMWithBeforeLambdaBody);
19028   verifyFormat("FctWithTwoParams_SLS_All(\n"
19029                "    []()\n"
19030                "    {\n"
19031                "      // A cool function...\n"
19032                "      return 43;\n"
19033                "    },\n"
19034                "    87);",
19035                LLVMWithBeforeLambdaBody);
19036   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
19037                LLVMWithBeforeLambdaBody);
19038   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
19039                LLVMWithBeforeLambdaBody);
19040   verifyFormat(
19041       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
19042       LLVMWithBeforeLambdaBody);
19043   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
19044                "}); }, x);",
19045                LLVMWithBeforeLambdaBody);
19046   verifyFormat("TwoNestedLambdas_SLS_All(\n"
19047                "    []()\n"
19048                "    {\n"
19049                "      // A cool function...\n"
19050                "      return Call([]() { return 17; });\n"
19051                "    });",
19052                LLVMWithBeforeLambdaBody);
19053   verifyFormat("TwoNestedLambdas_SLS_All(\n"
19054                "    []()\n"
19055                "    {\n"
19056                "      return Call(\n"
19057                "          []()\n"
19058                "          {\n"
19059                "            // A cool function...\n"
19060                "            return 17;\n"
19061                "          });\n"
19062                "    });",
19063                LLVMWithBeforeLambdaBody);
19064 }
19065 
19066 TEST_F(FormatTest, LambdaWithLineComments) {
19067   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
19068   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
19069   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
19070   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
19071       FormatStyle::ShortLambdaStyle::SLS_All;
19072 
19073   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
19074   verifyFormat("auto k = []() // comment\n"
19075                "{ return; }",
19076                LLVMWithBeforeLambdaBody);
19077   verifyFormat("auto k = []() /* comment */ { return; }",
19078                LLVMWithBeforeLambdaBody);
19079   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
19080                LLVMWithBeforeLambdaBody);
19081   verifyFormat("auto k = []() // X\n"
19082                "{ return; }",
19083                LLVMWithBeforeLambdaBody);
19084   verifyFormat(
19085       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
19086       "{ return; }",
19087       LLVMWithBeforeLambdaBody);
19088 }
19089 
19090 TEST_F(FormatTest, EmptyLinesInLambdas) {
19091   verifyFormat("auto lambda = []() {\n"
19092                "  x(); //\n"
19093                "};",
19094                "auto lambda = []() {\n"
19095                "\n"
19096                "  x(); //\n"
19097                "\n"
19098                "};");
19099 }
19100 
19101 TEST_F(FormatTest, FormatsBlocks) {
19102   FormatStyle ShortBlocks = getLLVMStyle();
19103   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
19104   verifyFormat("int (^Block)(int, int);", ShortBlocks);
19105   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
19106   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
19107   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
19108   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
19109   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
19110 
19111   verifyFormat("foo(^{ bar(); });", ShortBlocks);
19112   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
19113   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
19114 
19115   verifyFormat("[operation setCompletionBlock:^{\n"
19116                "  [self onOperationDone];\n"
19117                "}];");
19118   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
19119                "  [self onOperationDone];\n"
19120                "}]};");
19121   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
19122                "  f();\n"
19123                "}];");
19124   verifyFormat("int a = [operation block:^int(int *i) {\n"
19125                "  return 1;\n"
19126                "}];");
19127   verifyFormat("[myObject doSomethingWith:arg1\n"
19128                "                      aaa:^int(int *a) {\n"
19129                "                        return 1;\n"
19130                "                      }\n"
19131                "                      bbb:f(a * bbbbbbbb)];");
19132 
19133   verifyFormat("[operation setCompletionBlock:^{\n"
19134                "  [self.delegate newDataAvailable];\n"
19135                "}];",
19136                getLLVMStyleWithColumns(60));
19137   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
19138                "  NSString *path = [self sessionFilePath];\n"
19139                "  if (path) {\n"
19140                "    // ...\n"
19141                "  }\n"
19142                "});");
19143   verifyFormat("[[SessionService sharedService]\n"
19144                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
19145                "      if (window) {\n"
19146                "        [self windowDidLoad:window];\n"
19147                "      } else {\n"
19148                "        [self errorLoadingWindow];\n"
19149                "      }\n"
19150                "    }];");
19151   verifyFormat("void (^largeBlock)(void) = ^{\n"
19152                "  // ...\n"
19153                "};\n",
19154                getLLVMStyleWithColumns(40));
19155   verifyFormat("[[SessionService sharedService]\n"
19156                "    loadWindowWithCompletionBlock: //\n"
19157                "        ^(SessionWindow *window) {\n"
19158                "          if (window) {\n"
19159                "            [self windowDidLoad:window];\n"
19160                "          } else {\n"
19161                "            [self errorLoadingWindow];\n"
19162                "          }\n"
19163                "        }];",
19164                getLLVMStyleWithColumns(60));
19165   verifyFormat("[myObject doSomethingWith:arg1\n"
19166                "    firstBlock:^(Foo *a) {\n"
19167                "      // ...\n"
19168                "      int i;\n"
19169                "    }\n"
19170                "    secondBlock:^(Bar *b) {\n"
19171                "      // ...\n"
19172                "      int i;\n"
19173                "    }\n"
19174                "    thirdBlock:^Foo(Bar *b) {\n"
19175                "      // ...\n"
19176                "      int i;\n"
19177                "    }];");
19178   verifyFormat("[myObject doSomethingWith:arg1\n"
19179                "               firstBlock:-1\n"
19180                "              secondBlock:^(Bar *b) {\n"
19181                "                // ...\n"
19182                "                int i;\n"
19183                "              }];");
19184 
19185   verifyFormat("f(^{\n"
19186                "  @autoreleasepool {\n"
19187                "    if (a) {\n"
19188                "      g();\n"
19189                "    }\n"
19190                "  }\n"
19191                "});");
19192   verifyFormat("Block b = ^int *(A *a, B *b) {}");
19193   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
19194                "};");
19195 
19196   FormatStyle FourIndent = getLLVMStyle();
19197   FourIndent.ObjCBlockIndentWidth = 4;
19198   verifyFormat("[operation setCompletionBlock:^{\n"
19199                "    [self onOperationDone];\n"
19200                "}];",
19201                FourIndent);
19202 }
19203 
19204 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
19205   FormatStyle ZeroColumn = getLLVMStyle();
19206   ZeroColumn.ColumnLimit = 0;
19207 
19208   verifyFormat("[[SessionService sharedService] "
19209                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
19210                "  if (window) {\n"
19211                "    [self windowDidLoad:window];\n"
19212                "  } else {\n"
19213                "    [self errorLoadingWindow];\n"
19214                "  }\n"
19215                "}];",
19216                ZeroColumn);
19217   EXPECT_EQ("[[SessionService sharedService]\n"
19218             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
19219             "      if (window) {\n"
19220             "        [self windowDidLoad:window];\n"
19221             "      } else {\n"
19222             "        [self errorLoadingWindow];\n"
19223             "      }\n"
19224             "    }];",
19225             format("[[SessionService sharedService]\n"
19226                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
19227                    "                if (window) {\n"
19228                    "    [self windowDidLoad:window];\n"
19229                    "  } else {\n"
19230                    "    [self errorLoadingWindow];\n"
19231                    "  }\n"
19232                    "}];",
19233                    ZeroColumn));
19234   verifyFormat("[myObject doSomethingWith:arg1\n"
19235                "    firstBlock:^(Foo *a) {\n"
19236                "      // ...\n"
19237                "      int i;\n"
19238                "    }\n"
19239                "    secondBlock:^(Bar *b) {\n"
19240                "      // ...\n"
19241                "      int i;\n"
19242                "    }\n"
19243                "    thirdBlock:^Foo(Bar *b) {\n"
19244                "      // ...\n"
19245                "      int i;\n"
19246                "    }];",
19247                ZeroColumn);
19248   verifyFormat("f(^{\n"
19249                "  @autoreleasepool {\n"
19250                "    if (a) {\n"
19251                "      g();\n"
19252                "    }\n"
19253                "  }\n"
19254                "});",
19255                ZeroColumn);
19256   verifyFormat("void (^largeBlock)(void) = ^{\n"
19257                "  // ...\n"
19258                "};",
19259                ZeroColumn);
19260 
19261   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
19262   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
19263             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
19264   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
19265   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
19266             "  int i;\n"
19267             "};",
19268             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
19269 }
19270 
19271 TEST_F(FormatTest, SupportsCRLF) {
19272   EXPECT_EQ("int a;\r\n"
19273             "int b;\r\n"
19274             "int c;\r\n",
19275             format("int a;\r\n"
19276                    "  int b;\r\n"
19277                    "    int c;\r\n",
19278                    getLLVMStyle()));
19279   EXPECT_EQ("int a;\r\n"
19280             "int b;\r\n"
19281             "int c;\r\n",
19282             format("int a;\r\n"
19283                    "  int b;\n"
19284                    "    int c;\r\n",
19285                    getLLVMStyle()));
19286   EXPECT_EQ("int a;\n"
19287             "int b;\n"
19288             "int c;\n",
19289             format("int a;\r\n"
19290                    "  int b;\n"
19291                    "    int c;\n",
19292                    getLLVMStyle()));
19293   EXPECT_EQ("\"aaaaaaa \"\r\n"
19294             "\"bbbbbbb\";\r\n",
19295             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
19296   EXPECT_EQ("#define A \\\r\n"
19297             "  b;      \\\r\n"
19298             "  c;      \\\r\n"
19299             "  d;\r\n",
19300             format("#define A \\\r\n"
19301                    "  b; \\\r\n"
19302                    "  c; d; \r\n",
19303                    getGoogleStyle()));
19304 
19305   EXPECT_EQ("/*\r\n"
19306             "multi line block comments\r\n"
19307             "should not introduce\r\n"
19308             "an extra carriage return\r\n"
19309             "*/\r\n",
19310             format("/*\r\n"
19311                    "multi line block comments\r\n"
19312                    "should not introduce\r\n"
19313                    "an extra carriage return\r\n"
19314                    "*/\r\n"));
19315   EXPECT_EQ("/*\r\n"
19316             "\r\n"
19317             "*/",
19318             format("/*\r\n"
19319                    "    \r\r\r\n"
19320                    "*/"));
19321 
19322   FormatStyle style = getLLVMStyle();
19323 
19324   style.DeriveLineEnding = true;
19325   style.UseCRLF = false;
19326   EXPECT_EQ("union FooBarBazQux {\n"
19327             "  int foo;\n"
19328             "  int bar;\n"
19329             "  int baz;\n"
19330             "};",
19331             format("union FooBarBazQux {\r\n"
19332                    "  int foo;\n"
19333                    "  int bar;\r\n"
19334                    "  int baz;\n"
19335                    "};",
19336                    style));
19337   style.UseCRLF = true;
19338   EXPECT_EQ("union FooBarBazQux {\r\n"
19339             "  int foo;\r\n"
19340             "  int bar;\r\n"
19341             "  int baz;\r\n"
19342             "};",
19343             format("union FooBarBazQux {\r\n"
19344                    "  int foo;\n"
19345                    "  int bar;\r\n"
19346                    "  int baz;\n"
19347                    "};",
19348                    style));
19349 
19350   style.DeriveLineEnding = false;
19351   style.UseCRLF = false;
19352   EXPECT_EQ("union FooBarBazQux {\n"
19353             "  int foo;\n"
19354             "  int bar;\n"
19355             "  int baz;\n"
19356             "  int qux;\n"
19357             "};",
19358             format("union FooBarBazQux {\r\n"
19359                    "  int foo;\n"
19360                    "  int bar;\r\n"
19361                    "  int baz;\n"
19362                    "  int qux;\r\n"
19363                    "};",
19364                    style));
19365   style.UseCRLF = true;
19366   EXPECT_EQ("union FooBarBazQux {\r\n"
19367             "  int foo;\r\n"
19368             "  int bar;\r\n"
19369             "  int baz;\r\n"
19370             "  int qux;\r\n"
19371             "};",
19372             format("union FooBarBazQux {\r\n"
19373                    "  int foo;\n"
19374                    "  int bar;\r\n"
19375                    "  int baz;\n"
19376                    "  int qux;\n"
19377                    "};",
19378                    style));
19379 
19380   style.DeriveLineEnding = true;
19381   style.UseCRLF = false;
19382   EXPECT_EQ("union FooBarBazQux {\r\n"
19383             "  int foo;\r\n"
19384             "  int bar;\r\n"
19385             "  int baz;\r\n"
19386             "  int qux;\r\n"
19387             "};",
19388             format("union FooBarBazQux {\r\n"
19389                    "  int foo;\n"
19390                    "  int bar;\r\n"
19391                    "  int baz;\n"
19392                    "  int qux;\r\n"
19393                    "};",
19394                    style));
19395   style.UseCRLF = true;
19396   EXPECT_EQ("union FooBarBazQux {\n"
19397             "  int foo;\n"
19398             "  int bar;\n"
19399             "  int baz;\n"
19400             "  int qux;\n"
19401             "};",
19402             format("union FooBarBazQux {\r\n"
19403                    "  int foo;\n"
19404                    "  int bar;\r\n"
19405                    "  int baz;\n"
19406                    "  int qux;\n"
19407                    "};",
19408                    style));
19409 }
19410 
19411 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
19412   verifyFormat("MY_CLASS(C) {\n"
19413                "  int i;\n"
19414                "  int j;\n"
19415                "};");
19416 }
19417 
19418 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
19419   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
19420   TwoIndent.ContinuationIndentWidth = 2;
19421 
19422   EXPECT_EQ("int i =\n"
19423             "  longFunction(\n"
19424             "    arg);",
19425             format("int i = longFunction(arg);", TwoIndent));
19426 
19427   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
19428   SixIndent.ContinuationIndentWidth = 6;
19429 
19430   EXPECT_EQ("int i =\n"
19431             "      longFunction(\n"
19432             "            arg);",
19433             format("int i = longFunction(arg);", SixIndent));
19434 }
19435 
19436 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
19437   FormatStyle Style = getLLVMStyle();
19438   verifyFormat("int Foo::getter(\n"
19439                "    //\n"
19440                ") const {\n"
19441                "  return foo;\n"
19442                "}",
19443                Style);
19444   verifyFormat("void Foo::setter(\n"
19445                "    //\n"
19446                ") {\n"
19447                "  foo = 1;\n"
19448                "}",
19449                Style);
19450 }
19451 
19452 TEST_F(FormatTest, SpacesInAngles) {
19453   FormatStyle Spaces = getLLVMStyle();
19454   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
19455 
19456   verifyFormat("vector< ::std::string > x1;", Spaces);
19457   verifyFormat("Foo< int, Bar > x2;", Spaces);
19458   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
19459 
19460   verifyFormat("static_cast< int >(arg);", Spaces);
19461   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
19462   verifyFormat("f< int, float >();", Spaces);
19463   verifyFormat("template <> g() {}", Spaces);
19464   verifyFormat("template < std::vector< int > > f() {}", Spaces);
19465   verifyFormat("std::function< void(int, int) > fct;", Spaces);
19466   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
19467                Spaces);
19468 
19469   Spaces.Standard = FormatStyle::LS_Cpp03;
19470   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
19471   verifyFormat("A< A< int > >();", Spaces);
19472 
19473   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
19474   verifyFormat("A<A<int> >();", Spaces);
19475 
19476   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
19477   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
19478                Spaces);
19479   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
19480                Spaces);
19481 
19482   verifyFormat("A<A<int> >();", Spaces);
19483   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
19484   verifyFormat("A< A< int > >();", Spaces);
19485 
19486   Spaces.Standard = FormatStyle::LS_Cpp11;
19487   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
19488   verifyFormat("A< A< int > >();", Spaces);
19489 
19490   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
19491   verifyFormat("vector<::std::string> x4;", Spaces);
19492   verifyFormat("vector<int> x5;", Spaces);
19493   verifyFormat("Foo<int, Bar> x6;", Spaces);
19494   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
19495 
19496   verifyFormat("A<A<int>>();", Spaces);
19497 
19498   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
19499   verifyFormat("vector<::std::string> x4;", Spaces);
19500   verifyFormat("vector< ::std::string > x4;", Spaces);
19501   verifyFormat("vector<int> x5;", Spaces);
19502   verifyFormat("vector< int > x5;", Spaces);
19503   verifyFormat("Foo<int, Bar> x6;", Spaces);
19504   verifyFormat("Foo< int, Bar > x6;", Spaces);
19505   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
19506   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
19507 
19508   verifyFormat("A<A<int>>();", Spaces);
19509   verifyFormat("A< A< int > >();", Spaces);
19510   verifyFormat("A<A<int > >();", Spaces);
19511   verifyFormat("A< A< int>>();", Spaces);
19512 }
19513 
19514 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
19515   FormatStyle Style = getLLVMStyle();
19516   Style.SpaceAfterTemplateKeyword = false;
19517   verifyFormat("template<int> void foo();", Style);
19518 }
19519 
19520 TEST_F(FormatTest, TripleAngleBrackets) {
19521   verifyFormat("f<<<1, 1>>>();");
19522   verifyFormat("f<<<1, 1, 1, s>>>();");
19523   verifyFormat("f<<<a, b, c, d>>>();");
19524   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
19525   verifyFormat("f<param><<<1, 1>>>();");
19526   verifyFormat("f<1><<<1, 1>>>();");
19527   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
19528   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
19529                "aaaaaaaaaaa<<<\n    1, 1>>>();");
19530   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
19531                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
19532 }
19533 
19534 TEST_F(FormatTest, MergeLessLessAtEnd) {
19535   verifyFormat("<<");
19536   EXPECT_EQ("< < <", format("\\\n<<<"));
19537   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
19538                "aaallvm::outs() <<");
19539   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
19540                "aaaallvm::outs()\n    <<");
19541 }
19542 
19543 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
19544   std::string code = "#if A\n"
19545                      "#if B\n"
19546                      "a.\n"
19547                      "#endif\n"
19548                      "    a = 1;\n"
19549                      "#else\n"
19550                      "#endif\n"
19551                      "#if C\n"
19552                      "#else\n"
19553                      "#endif\n";
19554   EXPECT_EQ(code, format(code));
19555 }
19556 
19557 TEST_F(FormatTest, HandleConflictMarkers) {
19558   // Git/SVN conflict markers.
19559   EXPECT_EQ("int a;\n"
19560             "void f() {\n"
19561             "  callme(some(parameter1,\n"
19562             "<<<<<<< text by the vcs\n"
19563             "              parameter2),\n"
19564             "||||||| text by the vcs\n"
19565             "              parameter2),\n"
19566             "         parameter3,\n"
19567             "======= text by the vcs\n"
19568             "              parameter2, parameter3),\n"
19569             ">>>>>>> text by the vcs\n"
19570             "         otherparameter);\n",
19571             format("int a;\n"
19572                    "void f() {\n"
19573                    "  callme(some(parameter1,\n"
19574                    "<<<<<<< text by the vcs\n"
19575                    "  parameter2),\n"
19576                    "||||||| text by the vcs\n"
19577                    "  parameter2),\n"
19578                    "  parameter3,\n"
19579                    "======= text by the vcs\n"
19580                    "  parameter2,\n"
19581                    "  parameter3),\n"
19582                    ">>>>>>> text by the vcs\n"
19583                    "  otherparameter);\n"));
19584 
19585   // Perforce markers.
19586   EXPECT_EQ("void f() {\n"
19587             "  function(\n"
19588             ">>>> text by the vcs\n"
19589             "      parameter,\n"
19590             "==== text by the vcs\n"
19591             "      parameter,\n"
19592             "==== text by the vcs\n"
19593             "      parameter,\n"
19594             "<<<< text by the vcs\n"
19595             "      parameter);\n",
19596             format("void f() {\n"
19597                    "  function(\n"
19598                    ">>>> text by the vcs\n"
19599                    "  parameter,\n"
19600                    "==== text by the vcs\n"
19601                    "  parameter,\n"
19602                    "==== text by the vcs\n"
19603                    "  parameter,\n"
19604                    "<<<< text by the vcs\n"
19605                    "  parameter);\n"));
19606 
19607   EXPECT_EQ("<<<<<<<\n"
19608             "|||||||\n"
19609             "=======\n"
19610             ">>>>>>>",
19611             format("<<<<<<<\n"
19612                    "|||||||\n"
19613                    "=======\n"
19614                    ">>>>>>>"));
19615 
19616   EXPECT_EQ("<<<<<<<\n"
19617             "|||||||\n"
19618             "int i;\n"
19619             "=======\n"
19620             ">>>>>>>",
19621             format("<<<<<<<\n"
19622                    "|||||||\n"
19623                    "int i;\n"
19624                    "=======\n"
19625                    ">>>>>>>"));
19626 
19627   // FIXME: Handle parsing of macros around conflict markers correctly:
19628   EXPECT_EQ("#define Macro \\\n"
19629             "<<<<<<<\n"
19630             "Something \\\n"
19631             "|||||||\n"
19632             "Else \\\n"
19633             "=======\n"
19634             "Other \\\n"
19635             ">>>>>>>\n"
19636             "    End int i;\n",
19637             format("#define Macro \\\n"
19638                    "<<<<<<<\n"
19639                    "  Something \\\n"
19640                    "|||||||\n"
19641                    "  Else \\\n"
19642                    "=======\n"
19643                    "  Other \\\n"
19644                    ">>>>>>>\n"
19645                    "  End\n"
19646                    "int i;\n"));
19647 }
19648 
19649 TEST_F(FormatTest, DisableRegions) {
19650   EXPECT_EQ("int i;\n"
19651             "// clang-format off\n"
19652             "  int j;\n"
19653             "// clang-format on\n"
19654             "int k;",
19655             format(" int  i;\n"
19656                    "   // clang-format off\n"
19657                    "  int j;\n"
19658                    " // clang-format on\n"
19659                    "   int   k;"));
19660   EXPECT_EQ("int i;\n"
19661             "/* clang-format off */\n"
19662             "  int j;\n"
19663             "/* clang-format on */\n"
19664             "int k;",
19665             format(" int  i;\n"
19666                    "   /* clang-format off */\n"
19667                    "  int j;\n"
19668                    " /* clang-format on */\n"
19669                    "   int   k;"));
19670 
19671   // Don't reflow comments within disabled regions.
19672   EXPECT_EQ("// clang-format off\n"
19673             "// long long long long long long line\n"
19674             "/* clang-format on */\n"
19675             "/* long long long\n"
19676             " * long long long\n"
19677             " * line */\n"
19678             "int i;\n"
19679             "/* clang-format off */\n"
19680             "/* long long long long long long line */\n",
19681             format("// clang-format off\n"
19682                    "// long long long long long long line\n"
19683                    "/* clang-format on */\n"
19684                    "/* long long long long long long line */\n"
19685                    "int i;\n"
19686                    "/* clang-format off */\n"
19687                    "/* long long long long long long line */\n",
19688                    getLLVMStyleWithColumns(20)));
19689 }
19690 
19691 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
19692   format("? ) =");
19693   verifyNoCrash("#define a\\\n /**/}");
19694 }
19695 
19696 TEST_F(FormatTest, FormatsTableGenCode) {
19697   FormatStyle Style = getLLVMStyle();
19698   Style.Language = FormatStyle::LK_TableGen;
19699   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
19700 }
19701 
19702 TEST_F(FormatTest, ArrayOfTemplates) {
19703   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
19704             format("auto a = new unique_ptr<int > [ 10];"));
19705 
19706   FormatStyle Spaces = getLLVMStyle();
19707   Spaces.SpacesInSquareBrackets = true;
19708   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
19709             format("auto a = new unique_ptr<int > [10];", Spaces));
19710 }
19711 
19712 TEST_F(FormatTest, ArrayAsTemplateType) {
19713   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
19714             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
19715 
19716   FormatStyle Spaces = getLLVMStyle();
19717   Spaces.SpacesInSquareBrackets = true;
19718   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
19719             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
19720 }
19721 
19722 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
19723 
19724 TEST(FormatStyle, GetStyleWithEmptyFileName) {
19725   llvm::vfs::InMemoryFileSystem FS;
19726   auto Style1 = getStyle("file", "", "Google", "", &FS);
19727   ASSERT_TRUE((bool)Style1);
19728   ASSERT_EQ(*Style1, getGoogleStyle());
19729 }
19730 
19731 TEST(FormatStyle, GetStyleOfFile) {
19732   llvm::vfs::InMemoryFileSystem FS;
19733   // Test 1: format file in the same directory.
19734   ASSERT_TRUE(
19735       FS.addFile("/a/.clang-format", 0,
19736                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
19737   ASSERT_TRUE(
19738       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
19739   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
19740   ASSERT_TRUE((bool)Style1);
19741   ASSERT_EQ(*Style1, getLLVMStyle());
19742 
19743   // Test 2.1: fallback to default.
19744   ASSERT_TRUE(
19745       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
19746   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
19747   ASSERT_TRUE((bool)Style2);
19748   ASSERT_EQ(*Style2, getMozillaStyle());
19749 
19750   // Test 2.2: no format on 'none' fallback style.
19751   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
19752   ASSERT_TRUE((bool)Style2);
19753   ASSERT_EQ(*Style2, getNoStyle());
19754 
19755   // Test 2.3: format if config is found with no based style while fallback is
19756   // 'none'.
19757   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
19758                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
19759   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
19760   ASSERT_TRUE((bool)Style2);
19761   ASSERT_EQ(*Style2, getLLVMStyle());
19762 
19763   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
19764   Style2 = getStyle("{}", "a.h", "none", "", &FS);
19765   ASSERT_TRUE((bool)Style2);
19766   ASSERT_EQ(*Style2, getLLVMStyle());
19767 
19768   // Test 3: format file in parent directory.
19769   ASSERT_TRUE(
19770       FS.addFile("/c/.clang-format", 0,
19771                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
19772   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
19773                          llvm::MemoryBuffer::getMemBuffer("int i;")));
19774   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
19775   ASSERT_TRUE((bool)Style3);
19776   ASSERT_EQ(*Style3, getGoogleStyle());
19777 
19778   // Test 4: error on invalid fallback style
19779   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
19780   ASSERT_FALSE((bool)Style4);
19781   llvm::consumeError(Style4.takeError());
19782 
19783   // Test 5: error on invalid yaml on command line
19784   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
19785   ASSERT_FALSE((bool)Style5);
19786   llvm::consumeError(Style5.takeError());
19787 
19788   // Test 6: error on invalid style
19789   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
19790   ASSERT_FALSE((bool)Style6);
19791   llvm::consumeError(Style6.takeError());
19792 
19793   // Test 7: found config file, error on parsing it
19794   ASSERT_TRUE(
19795       FS.addFile("/d/.clang-format", 0,
19796                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
19797                                                   "InvalidKey: InvalidValue")));
19798   ASSERT_TRUE(
19799       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
19800   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
19801   ASSERT_FALSE((bool)Style7a);
19802   llvm::consumeError(Style7a.takeError());
19803 
19804   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
19805   ASSERT_TRUE((bool)Style7b);
19806 
19807   // Test 8: inferred per-language defaults apply.
19808   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
19809   ASSERT_TRUE((bool)StyleTd);
19810   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
19811 
19812   // Test 9.1: overwriting a file style, when parent no file exists with no
19813   // fallback style
19814   ASSERT_TRUE(FS.addFile(
19815       "/e/sub/.clang-format", 0,
19816       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
19817                                        "ColumnLimit: 20")));
19818   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
19819                          llvm::MemoryBuffer::getMemBuffer("int i;")));
19820   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
19821   ASSERT_TRUE(static_cast<bool>(Style9));
19822   ASSERT_EQ(*Style9, [] {
19823     auto Style = getNoStyle();
19824     Style.ColumnLimit = 20;
19825     return Style;
19826   }());
19827 
19828   // Test 9.2: with LLVM fallback style
19829   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
19830   ASSERT_TRUE(static_cast<bool>(Style9));
19831   ASSERT_EQ(*Style9, [] {
19832     auto Style = getLLVMStyle();
19833     Style.ColumnLimit = 20;
19834     return Style;
19835   }());
19836 
19837   // Test 9.3: with a parent file
19838   ASSERT_TRUE(
19839       FS.addFile("/e/.clang-format", 0,
19840                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
19841                                                   "UseTab: Always")));
19842   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
19843   ASSERT_TRUE(static_cast<bool>(Style9));
19844   ASSERT_EQ(*Style9, [] {
19845     auto Style = getGoogleStyle();
19846     Style.ColumnLimit = 20;
19847     Style.UseTab = FormatStyle::UT_Always;
19848     return Style;
19849   }());
19850 
19851   // Test 9.4: propagate more than one level
19852   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
19853                          llvm::MemoryBuffer::getMemBuffer("int i;")));
19854   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
19855                          llvm::MemoryBuffer::getMemBuffer(
19856                              "BasedOnStyle: InheritParentConfig\n"
19857                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
19858   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
19859 
19860   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
19861     auto Style = getGoogleStyle();
19862     Style.ColumnLimit = 20;
19863     Style.UseTab = FormatStyle::UT_Always;
19864     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
19865     return Style;
19866   }();
19867 
19868   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
19869   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
19870   ASSERT_TRUE(static_cast<bool>(Style9));
19871   ASSERT_EQ(*Style9, SubSubStyle);
19872 
19873   // Test 9.5: use InheritParentConfig as style name
19874   Style9 =
19875       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
19876   ASSERT_TRUE(static_cast<bool>(Style9));
19877   ASSERT_EQ(*Style9, SubSubStyle);
19878 
19879   // Test 9.6: use command line style with inheritance
19880   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
19881                     "none", "", &FS);
19882   ASSERT_TRUE(static_cast<bool>(Style9));
19883   ASSERT_EQ(*Style9, SubSubStyle);
19884 
19885   // Test 9.7: use command line style with inheritance and own config
19886   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
19887                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
19888                     "/e/sub/code.cpp", "none", "", &FS);
19889   ASSERT_TRUE(static_cast<bool>(Style9));
19890   ASSERT_EQ(*Style9, SubSubStyle);
19891 
19892   // Test 9.8: use inheritance from a file without BasedOnStyle
19893   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
19894                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
19895   ASSERT_TRUE(
19896       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
19897                  llvm::MemoryBuffer::getMemBuffer(
19898                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
19899   // Make sure we do not use the fallback style
19900   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
19901   ASSERT_TRUE(static_cast<bool>(Style9));
19902   ASSERT_EQ(*Style9, [] {
19903     auto Style = getLLVMStyle();
19904     Style.ColumnLimit = 123;
19905     return Style;
19906   }());
19907 
19908   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
19909   ASSERT_TRUE(static_cast<bool>(Style9));
19910   ASSERT_EQ(*Style9, [] {
19911     auto Style = getLLVMStyle();
19912     Style.ColumnLimit = 123;
19913     Style.IndentWidth = 7;
19914     return Style;
19915   }());
19916 }
19917 
19918 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
19919   // Column limit is 20.
19920   std::string Code = "Type *a =\n"
19921                      "    new Type();\n"
19922                      "g(iiiii, 0, jjjjj,\n"
19923                      "  0, kkkkk, 0, mm);\n"
19924                      "int  bad     = format   ;";
19925   std::string Expected = "auto a = new Type();\n"
19926                          "g(iiiii, nullptr,\n"
19927                          "  jjjjj, nullptr,\n"
19928                          "  kkkkk, nullptr,\n"
19929                          "  mm);\n"
19930                          "int  bad     = format   ;";
19931   FileID ID = Context.createInMemoryFile("format.cpp", Code);
19932   tooling::Replacements Replaces = toReplacements(
19933       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
19934                             "auto "),
19935        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
19936                             "nullptr"),
19937        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
19938                             "nullptr"),
19939        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
19940                             "nullptr")});
19941 
19942   format::FormatStyle Style = format::getLLVMStyle();
19943   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
19944   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
19945   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
19946       << llvm::toString(FormattedReplaces.takeError()) << "\n";
19947   auto Result = applyAllReplacements(Code, *FormattedReplaces);
19948   EXPECT_TRUE(static_cast<bool>(Result));
19949   EXPECT_EQ(Expected, *Result);
19950 }
19951 
19952 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
19953   std::string Code = "#include \"a.h\"\n"
19954                      "#include \"c.h\"\n"
19955                      "\n"
19956                      "int main() {\n"
19957                      "  return 0;\n"
19958                      "}";
19959   std::string Expected = "#include \"a.h\"\n"
19960                          "#include \"b.h\"\n"
19961                          "#include \"c.h\"\n"
19962                          "\n"
19963                          "int main() {\n"
19964                          "  return 0;\n"
19965                          "}";
19966   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
19967   tooling::Replacements Replaces = toReplacements(
19968       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
19969                             "#include \"b.h\"\n")});
19970 
19971   format::FormatStyle Style = format::getLLVMStyle();
19972   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
19973   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
19974   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
19975       << llvm::toString(FormattedReplaces.takeError()) << "\n";
19976   auto Result = applyAllReplacements(Code, *FormattedReplaces);
19977   EXPECT_TRUE(static_cast<bool>(Result));
19978   EXPECT_EQ(Expected, *Result);
19979 }
19980 
19981 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
19982   EXPECT_EQ("using std::cin;\n"
19983             "using std::cout;",
19984             format("using std::cout;\n"
19985                    "using std::cin;",
19986                    getGoogleStyle()));
19987 }
19988 
19989 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
19990   format::FormatStyle Style = format::getLLVMStyle();
19991   Style.Standard = FormatStyle::LS_Cpp03;
19992   // cpp03 recognize this string as identifier u8 and literal character 'a'
19993   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
19994 }
19995 
19996 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
19997   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
19998   // all modes, including C++11, C++14 and C++17
19999   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
20000 }
20001 
20002 TEST_F(FormatTest, DoNotFormatLikelyXml) {
20003   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
20004   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
20005 }
20006 
20007 TEST_F(FormatTest, StructuredBindings) {
20008   // Structured bindings is a C++17 feature.
20009   // all modes, including C++11, C++14 and C++17
20010   verifyFormat("auto [a, b] = f();");
20011   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
20012   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
20013   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
20014   EXPECT_EQ("auto const volatile [a, b] = f();",
20015             format("auto  const   volatile[a, b] = f();"));
20016   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
20017   EXPECT_EQ("auto &[a, b, c] = f();",
20018             format("auto   &[  a  ,  b,c   ] = f();"));
20019   EXPECT_EQ("auto &&[a, b, c] = f();",
20020             format("auto   &&[  a  ,  b,c   ] = f();"));
20021   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
20022   EXPECT_EQ("auto const volatile &&[a, b] = f();",
20023             format("auto  const  volatile  &&[a, b] = f();"));
20024   EXPECT_EQ("auto const &&[a, b] = f();",
20025             format("auto  const   &&  [a, b] = f();"));
20026   EXPECT_EQ("const auto &[a, b] = f();",
20027             format("const  auto  &  [a, b] = f();"));
20028   EXPECT_EQ("const auto volatile &&[a, b] = f();",
20029             format("const  auto   volatile  &&[a, b] = f();"));
20030   EXPECT_EQ("volatile const auto &&[a, b] = f();",
20031             format("volatile  const  auto   &&[a, b] = f();"));
20032   EXPECT_EQ("const auto &&[a, b] = f();",
20033             format("const  auto  &&  [a, b] = f();"));
20034 
20035   // Make sure we don't mistake structured bindings for lambdas.
20036   FormatStyle PointerMiddle = getLLVMStyle();
20037   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
20038   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
20039   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
20040   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
20041   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
20042   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
20043   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
20044   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
20045   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
20046   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
20047   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
20048   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
20049   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
20050 
20051   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
20052             format("for (const auto   &&   [a, b] : some_range) {\n}"));
20053   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
20054             format("for (const auto   &   [a, b] : some_range) {\n}"));
20055   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
20056             format("for (const auto[a, b] : some_range) {\n}"));
20057   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
20058   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
20059   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
20060   EXPECT_EQ("auto const &[x, y](expr);",
20061             format("auto  const  &  [x,y]  (expr);"));
20062   EXPECT_EQ("auto const &&[x, y](expr);",
20063             format("auto  const  &&  [x,y]  (expr);"));
20064   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
20065   EXPECT_EQ("auto const &[x, y]{expr};",
20066             format("auto  const  &  [x,y]  {expr};"));
20067   EXPECT_EQ("auto const &&[x, y]{expr};",
20068             format("auto  const  &&  [x,y]  {expr};"));
20069 
20070   format::FormatStyle Spaces = format::getLLVMStyle();
20071   Spaces.SpacesInSquareBrackets = true;
20072   verifyFormat("auto [ a, b ] = f();", Spaces);
20073   verifyFormat("auto &&[ a, b ] = f();", Spaces);
20074   verifyFormat("auto &[ a, b ] = f();", Spaces);
20075   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
20076   verifyFormat("auto const &[ a, b ] = f();", Spaces);
20077 }
20078 
20079 TEST_F(FormatTest, FileAndCode) {
20080   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
20081   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
20082   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
20083   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
20084   EXPECT_EQ(FormatStyle::LK_ObjC,
20085             guessLanguage("foo.h", "@interface Foo\n@end\n"));
20086   EXPECT_EQ(
20087       FormatStyle::LK_ObjC,
20088       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
20089   EXPECT_EQ(FormatStyle::LK_ObjC,
20090             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
20091   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
20092   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
20093   EXPECT_EQ(FormatStyle::LK_ObjC,
20094             guessLanguage("foo", "@interface Foo\n@end\n"));
20095   EXPECT_EQ(FormatStyle::LK_ObjC,
20096             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
20097   EXPECT_EQ(
20098       FormatStyle::LK_ObjC,
20099       guessLanguage("foo.h",
20100                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
20101   EXPECT_EQ(
20102       FormatStyle::LK_Cpp,
20103       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
20104 }
20105 
20106 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
20107   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
20108   EXPECT_EQ(FormatStyle::LK_ObjC,
20109             guessLanguage("foo.h", "array[[calculator getIndex]];"));
20110   EXPECT_EQ(FormatStyle::LK_Cpp,
20111             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
20112   EXPECT_EQ(
20113       FormatStyle::LK_Cpp,
20114       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
20115   EXPECT_EQ(FormatStyle::LK_ObjC,
20116             guessLanguage("foo.h", "[[noreturn foo] bar];"));
20117   EXPECT_EQ(FormatStyle::LK_Cpp,
20118             guessLanguage("foo.h", "[[clang::fallthrough]];"));
20119   EXPECT_EQ(FormatStyle::LK_ObjC,
20120             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
20121   EXPECT_EQ(FormatStyle::LK_Cpp,
20122             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
20123   EXPECT_EQ(FormatStyle::LK_Cpp,
20124             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
20125   EXPECT_EQ(FormatStyle::LK_ObjC,
20126             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
20127   EXPECT_EQ(FormatStyle::LK_Cpp,
20128             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
20129   EXPECT_EQ(
20130       FormatStyle::LK_Cpp,
20131       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
20132   EXPECT_EQ(
20133       FormatStyle::LK_Cpp,
20134       guessLanguage("foo.h",
20135                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
20136   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
20137 }
20138 
20139 TEST_F(FormatTest, GuessLanguageWithCaret) {
20140   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
20141   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
20142   EXPECT_EQ(FormatStyle::LK_ObjC,
20143             guessLanguage("foo.h", "int(^)(char, float);"));
20144   EXPECT_EQ(FormatStyle::LK_ObjC,
20145             guessLanguage("foo.h", "int(^foo)(char, float);"));
20146   EXPECT_EQ(FormatStyle::LK_ObjC,
20147             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
20148   EXPECT_EQ(FormatStyle::LK_ObjC,
20149             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
20150   EXPECT_EQ(
20151       FormatStyle::LK_ObjC,
20152       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
20153 }
20154 
20155 TEST_F(FormatTest, GuessLanguageWithPragmas) {
20156   EXPECT_EQ(FormatStyle::LK_Cpp,
20157             guessLanguage("foo.h", "__pragma(warning(disable:))"));
20158   EXPECT_EQ(FormatStyle::LK_Cpp,
20159             guessLanguage("foo.h", "#pragma(warning(disable:))"));
20160   EXPECT_EQ(FormatStyle::LK_Cpp,
20161             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
20162 }
20163 
20164 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
20165   // ASM symbolic names are identifiers that must be surrounded by [] without
20166   // space in between:
20167   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
20168 
20169   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
20170   verifyFormat(R"(//
20171 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
20172 )");
20173 
20174   // A list of several ASM symbolic names.
20175   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
20176 
20177   // ASM symbolic names in inline ASM with inputs and outputs.
20178   verifyFormat(R"(//
20179 asm("cmoveq %1, %2, %[result]"
20180     : [result] "=r"(result)
20181     : "r"(test), "r"(new), "[result]"(old));
20182 )");
20183 
20184   // ASM symbolic names in inline ASM with no outputs.
20185   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
20186 }
20187 
20188 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
20189   EXPECT_EQ(FormatStyle::LK_Cpp,
20190             guessLanguage("foo.h", "void f() {\n"
20191                                    "  asm (\"mov %[e], %[d]\"\n"
20192                                    "     : [d] \"=rm\" (d)\n"
20193                                    "       [e] \"rm\" (*e));\n"
20194                                    "}"));
20195   EXPECT_EQ(FormatStyle::LK_Cpp,
20196             guessLanguage("foo.h", "void f() {\n"
20197                                    "  _asm (\"mov %[e], %[d]\"\n"
20198                                    "     : [d] \"=rm\" (d)\n"
20199                                    "       [e] \"rm\" (*e));\n"
20200                                    "}"));
20201   EXPECT_EQ(FormatStyle::LK_Cpp,
20202             guessLanguage("foo.h", "void f() {\n"
20203                                    "  __asm (\"mov %[e], %[d]\"\n"
20204                                    "     : [d] \"=rm\" (d)\n"
20205                                    "       [e] \"rm\" (*e));\n"
20206                                    "}"));
20207   EXPECT_EQ(FormatStyle::LK_Cpp,
20208             guessLanguage("foo.h", "void f() {\n"
20209                                    "  __asm__ (\"mov %[e], %[d]\"\n"
20210                                    "     : [d] \"=rm\" (d)\n"
20211                                    "       [e] \"rm\" (*e));\n"
20212                                    "}"));
20213   EXPECT_EQ(FormatStyle::LK_Cpp,
20214             guessLanguage("foo.h", "void f() {\n"
20215                                    "  asm (\"mov %[e], %[d]\"\n"
20216                                    "     : [d] \"=rm\" (d),\n"
20217                                    "       [e] \"rm\" (*e));\n"
20218                                    "}"));
20219   EXPECT_EQ(FormatStyle::LK_Cpp,
20220             guessLanguage("foo.h", "void f() {\n"
20221                                    "  asm volatile (\"mov %[e], %[d]\"\n"
20222                                    "     : [d] \"=rm\" (d)\n"
20223                                    "       [e] \"rm\" (*e));\n"
20224                                    "}"));
20225 }
20226 
20227 TEST_F(FormatTest, GuessLanguageWithChildLines) {
20228   EXPECT_EQ(FormatStyle::LK_Cpp,
20229             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
20230   EXPECT_EQ(FormatStyle::LK_ObjC,
20231             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
20232   EXPECT_EQ(
20233       FormatStyle::LK_Cpp,
20234       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
20235   EXPECT_EQ(
20236       FormatStyle::LK_ObjC,
20237       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
20238 }
20239 
20240 TEST_F(FormatTest, TypenameMacros) {
20241   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
20242 
20243   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
20244   FormatStyle Google = getGoogleStyleWithColumns(0);
20245   Google.TypenameMacros = TypenameMacros;
20246   verifyFormat("struct foo {\n"
20247                "  int bar;\n"
20248                "  TAILQ_ENTRY(a) bleh;\n"
20249                "};",
20250                Google);
20251 
20252   FormatStyle Macros = getLLVMStyle();
20253   Macros.TypenameMacros = TypenameMacros;
20254 
20255   verifyFormat("STACK_OF(int) a;", Macros);
20256   verifyFormat("STACK_OF(int) *a;", Macros);
20257   verifyFormat("STACK_OF(int const *) *a;", Macros);
20258   verifyFormat("STACK_OF(int *const) *a;", Macros);
20259   verifyFormat("STACK_OF(int, string) a;", Macros);
20260   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
20261   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
20262   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
20263   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
20264   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
20265   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
20266 
20267   Macros.PointerAlignment = FormatStyle::PAS_Left;
20268   verifyFormat("STACK_OF(int)* a;", Macros);
20269   verifyFormat("STACK_OF(int*)* a;", Macros);
20270   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
20271   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
20272   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
20273 }
20274 
20275 TEST_F(FormatTest, AtomicQualifier) {
20276   // Check that we treate _Atomic as a type and not a function call
20277   FormatStyle Google = getGoogleStyleWithColumns(0);
20278   verifyFormat("struct foo {\n"
20279                "  int a1;\n"
20280                "  _Atomic(a) a2;\n"
20281                "  _Atomic(_Atomic(int) *const) a3;\n"
20282                "};",
20283                Google);
20284   verifyFormat("_Atomic(uint64_t) a;");
20285   verifyFormat("_Atomic(uint64_t) *a;");
20286   verifyFormat("_Atomic(uint64_t const *) *a;");
20287   verifyFormat("_Atomic(uint64_t *const) *a;");
20288   verifyFormat("_Atomic(const uint64_t *) *a;");
20289   verifyFormat("_Atomic(uint64_t) a;");
20290   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
20291   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
20292   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
20293   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
20294 
20295   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
20296   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
20297   FormatStyle Style = getLLVMStyle();
20298   Style.PointerAlignment = FormatStyle::PAS_Left;
20299   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
20300   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
20301   verifyFormat("_Atomic(int)* a;", Style);
20302   verifyFormat("_Atomic(int*)* a;", Style);
20303   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
20304 
20305   Style.SpacesInCStyleCastParentheses = true;
20306   Style.SpacesInParentheses = false;
20307   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
20308   Style.SpacesInCStyleCastParentheses = false;
20309   Style.SpacesInParentheses = true;
20310   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
20311   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
20312 }
20313 
20314 TEST_F(FormatTest, AmbersandInLamda) {
20315   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
20316   FormatStyle AlignStyle = getLLVMStyle();
20317   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
20318   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
20319   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
20320   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
20321 }
20322 
20323 TEST_F(FormatTest, SpacesInConditionalStatement) {
20324   FormatStyle Spaces = getLLVMStyle();
20325   Spaces.SpacesInConditionalStatement = true;
20326   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
20327   verifyFormat("if ( !a )\n  return;", Spaces);
20328   verifyFormat("if ( a )\n  return;", Spaces);
20329   verifyFormat("if constexpr ( a )\n  return;", Spaces);
20330   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
20331   verifyFormat("while ( a )\n  return;", Spaces);
20332   verifyFormat("while ( (a && b) )\n  return;", Spaces);
20333   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
20334   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
20335   // Check that space on the left of "::" is inserted as expected at beginning
20336   // of condition.
20337   verifyFormat("while ( ::func() )\n  return;", Spaces);
20338 }
20339 
20340 TEST_F(FormatTest, AlternativeOperators) {
20341   // Test case for ensuring alternate operators are not
20342   // combined with their right most neighbour.
20343   verifyFormat("int a and b;");
20344   verifyFormat("int a and_eq b;");
20345   verifyFormat("int a bitand b;");
20346   verifyFormat("int a bitor b;");
20347   verifyFormat("int a compl b;");
20348   verifyFormat("int a not b;");
20349   verifyFormat("int a not_eq b;");
20350   verifyFormat("int a or b;");
20351   verifyFormat("int a xor b;");
20352   verifyFormat("int a xor_eq b;");
20353   verifyFormat("return this not_eq bitand other;");
20354   verifyFormat("bool operator not_eq(const X bitand other)");
20355 
20356   verifyFormat("int a and 5;");
20357   verifyFormat("int a and_eq 5;");
20358   verifyFormat("int a bitand 5;");
20359   verifyFormat("int a bitor 5;");
20360   verifyFormat("int a compl 5;");
20361   verifyFormat("int a not 5;");
20362   verifyFormat("int a not_eq 5;");
20363   verifyFormat("int a or 5;");
20364   verifyFormat("int a xor 5;");
20365   verifyFormat("int a xor_eq 5;");
20366 
20367   verifyFormat("int a compl(5);");
20368   verifyFormat("int a not(5);");
20369 
20370   /* FIXME handle alternate tokens
20371    * https://en.cppreference.com/w/cpp/language/operator_alternative
20372   // alternative tokens
20373   verifyFormat("compl foo();");     //  ~foo();
20374   verifyFormat("foo() <%%>;");      // foo();
20375   verifyFormat("void foo() <%%>;"); // void foo(){}
20376   verifyFormat("int a <:1:>;");     // int a[1];[
20377   verifyFormat("%:define ABC abc"); // #define ABC abc
20378   verifyFormat("%:%:");             // ##
20379   */
20380 }
20381 
20382 TEST_F(FormatTest, STLWhileNotDefineChed) {
20383   verifyFormat("#if defined(while)\n"
20384                "#define while EMIT WARNING C4005\n"
20385                "#endif // while");
20386 }
20387 
20388 TEST_F(FormatTest, OperatorSpacing) {
20389   FormatStyle Style = getLLVMStyle();
20390   Style.PointerAlignment = FormatStyle::PAS_Right;
20391   verifyFormat("Foo::operator*();", Style);
20392   verifyFormat("Foo::operator void *();", Style);
20393   verifyFormat("Foo::operator void **();", Style);
20394   verifyFormat("Foo::operator void *&();", Style);
20395   verifyFormat("Foo::operator void *&&();", Style);
20396   verifyFormat("Foo::operator void const *();", Style);
20397   verifyFormat("Foo::operator void const **();", Style);
20398   verifyFormat("Foo::operator void const *&();", Style);
20399   verifyFormat("Foo::operator void const *&&();", Style);
20400   verifyFormat("Foo::operator()(void *);", Style);
20401   verifyFormat("Foo::operator*(void *);", Style);
20402   verifyFormat("Foo::operator*();", Style);
20403   verifyFormat("Foo::operator**();", Style);
20404   verifyFormat("Foo::operator&();", Style);
20405   verifyFormat("Foo::operator<int> *();", Style);
20406   verifyFormat("Foo::operator<Foo> *();", Style);
20407   verifyFormat("Foo::operator<int> **();", Style);
20408   verifyFormat("Foo::operator<Foo> **();", Style);
20409   verifyFormat("Foo::operator<int> &();", Style);
20410   verifyFormat("Foo::operator<Foo> &();", Style);
20411   verifyFormat("Foo::operator<int> &&();", Style);
20412   verifyFormat("Foo::operator<Foo> &&();", Style);
20413   verifyFormat("Foo::operator<int> *&();", Style);
20414   verifyFormat("Foo::operator<Foo> *&();", Style);
20415   verifyFormat("Foo::operator<int> *&&();", Style);
20416   verifyFormat("Foo::operator<Foo> *&&();", Style);
20417   verifyFormat("operator*(int (*)(), class Foo);", Style);
20418 
20419   verifyFormat("Foo::operator&();", Style);
20420   verifyFormat("Foo::operator void &();", Style);
20421   verifyFormat("Foo::operator void const &();", Style);
20422   verifyFormat("Foo::operator()(void &);", Style);
20423   verifyFormat("Foo::operator&(void &);", Style);
20424   verifyFormat("Foo::operator&();", Style);
20425   verifyFormat("operator&(int (&)(), class Foo);", Style);
20426 
20427   verifyFormat("Foo::operator&&();", Style);
20428   verifyFormat("Foo::operator**();", Style);
20429   verifyFormat("Foo::operator void &&();", Style);
20430   verifyFormat("Foo::operator void const &&();", Style);
20431   verifyFormat("Foo::operator()(void &&);", Style);
20432   verifyFormat("Foo::operator&&(void &&);", Style);
20433   verifyFormat("Foo::operator&&();", Style);
20434   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
20435   verifyFormat("operator const nsTArrayRight<E> &()", Style);
20436   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
20437                Style);
20438   verifyFormat("operator void **()", Style);
20439   verifyFormat("operator const FooRight<Object> &()", Style);
20440   verifyFormat("operator const FooRight<Object> *()", Style);
20441   verifyFormat("operator const FooRight<Object> **()", Style);
20442   verifyFormat("operator const FooRight<Object> *&()", Style);
20443   verifyFormat("operator const FooRight<Object> *&&()", Style);
20444 
20445   Style.PointerAlignment = FormatStyle::PAS_Left;
20446   verifyFormat("Foo::operator*();", Style);
20447   verifyFormat("Foo::operator**();", Style);
20448   verifyFormat("Foo::operator void*();", Style);
20449   verifyFormat("Foo::operator void**();", Style);
20450   verifyFormat("Foo::operator void*&();", Style);
20451   verifyFormat("Foo::operator void*&&();", Style);
20452   verifyFormat("Foo::operator void const*();", Style);
20453   verifyFormat("Foo::operator void const**();", Style);
20454   verifyFormat("Foo::operator void const*&();", Style);
20455   verifyFormat("Foo::operator void const*&&();", Style);
20456   verifyFormat("Foo::operator/*comment*/ void*();", Style);
20457   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
20458   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
20459   verifyFormat("Foo::operator()(void*);", Style);
20460   verifyFormat("Foo::operator*(void*);", Style);
20461   verifyFormat("Foo::operator*();", Style);
20462   verifyFormat("Foo::operator<int>*();", Style);
20463   verifyFormat("Foo::operator<Foo>*();", Style);
20464   verifyFormat("Foo::operator<int>**();", Style);
20465   verifyFormat("Foo::operator<Foo>**();", Style);
20466   verifyFormat("Foo::operator<Foo>*&();", Style);
20467   verifyFormat("Foo::operator<int>&();", Style);
20468   verifyFormat("Foo::operator<Foo>&();", Style);
20469   verifyFormat("Foo::operator<int>&&();", Style);
20470   verifyFormat("Foo::operator<Foo>&&();", Style);
20471   verifyFormat("Foo::operator<int>*&();", Style);
20472   verifyFormat("Foo::operator<Foo>*&();", Style);
20473   verifyFormat("operator*(int (*)(), class Foo);", Style);
20474 
20475   verifyFormat("Foo::operator&();", Style);
20476   verifyFormat("Foo::operator void&();", Style);
20477   verifyFormat("Foo::operator void const&();", Style);
20478   verifyFormat("Foo::operator/*comment*/ void&();", Style);
20479   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
20480   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
20481   verifyFormat("Foo::operator()(void&);", Style);
20482   verifyFormat("Foo::operator&(void&);", Style);
20483   verifyFormat("Foo::operator&();", Style);
20484   verifyFormat("operator&(int (&)(), class Foo);", Style);
20485 
20486   verifyFormat("Foo::operator&&();", Style);
20487   verifyFormat("Foo::operator void&&();", Style);
20488   verifyFormat("Foo::operator void const&&();", Style);
20489   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
20490   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
20491   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
20492   verifyFormat("Foo::operator()(void&&);", Style);
20493   verifyFormat("Foo::operator&&(void&&);", Style);
20494   verifyFormat("Foo::operator&&();", Style);
20495   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
20496   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
20497   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
20498                Style);
20499   verifyFormat("operator void**()", Style);
20500   verifyFormat("operator const FooLeft<Object>&()", Style);
20501   verifyFormat("operator const FooLeft<Object>*()", Style);
20502   verifyFormat("operator const FooLeft<Object>**()", Style);
20503   verifyFormat("operator const FooLeft<Object>*&()", Style);
20504   verifyFormat("operator const FooLeft<Object>*&&()", Style);
20505 
20506   // PR45107
20507   verifyFormat("operator Vector<String>&();", Style);
20508   verifyFormat("operator const Vector<String>&();", Style);
20509   verifyFormat("operator foo::Bar*();", Style);
20510   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
20511   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
20512                Style);
20513 
20514   Style.PointerAlignment = FormatStyle::PAS_Middle;
20515   verifyFormat("Foo::operator*();", Style);
20516   verifyFormat("Foo::operator void *();", Style);
20517   verifyFormat("Foo::operator()(void *);", Style);
20518   verifyFormat("Foo::operator*(void *);", Style);
20519   verifyFormat("Foo::operator*();", Style);
20520   verifyFormat("operator*(int (*)(), class Foo);", Style);
20521 
20522   verifyFormat("Foo::operator&();", Style);
20523   verifyFormat("Foo::operator void &();", Style);
20524   verifyFormat("Foo::operator void const &();", Style);
20525   verifyFormat("Foo::operator()(void &);", Style);
20526   verifyFormat("Foo::operator&(void &);", Style);
20527   verifyFormat("Foo::operator&();", Style);
20528   verifyFormat("operator&(int (&)(), class Foo);", Style);
20529 
20530   verifyFormat("Foo::operator&&();", Style);
20531   verifyFormat("Foo::operator void &&();", Style);
20532   verifyFormat("Foo::operator void const &&();", Style);
20533   verifyFormat("Foo::operator()(void &&);", Style);
20534   verifyFormat("Foo::operator&&(void &&);", Style);
20535   verifyFormat("Foo::operator&&();", Style);
20536   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
20537 }
20538 
20539 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
20540   FormatStyle Style = getLLVMStyle();
20541   // PR46157
20542   verifyFormat("foo(operator+, -42);", Style);
20543   verifyFormat("foo(operator++, -42);", Style);
20544   verifyFormat("foo(operator--, -42);", Style);
20545   verifyFormat("foo(-42, operator--);", Style);
20546   verifyFormat("foo(-42, operator, );", Style);
20547   verifyFormat("foo(operator, , -42);", Style);
20548 }
20549 
20550 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
20551   FormatStyle Style = getLLVMStyle();
20552   Style.WhitespaceSensitiveMacros.push_back("FOO");
20553 
20554   // Don't use the helpers here, since 'mess up' will change the whitespace
20555   // and these are all whitespace sensitive by definition
20556   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
20557             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
20558   EXPECT_EQ(
20559       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
20560       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
20561   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
20562             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
20563   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
20564             "       Still=Intentional);",
20565             format("FOO(String-ized&Messy+But,: :\n"
20566                    "       Still=Intentional);",
20567                    Style));
20568   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
20569   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
20570             "       Still=Intentional);",
20571             format("FOO(String-ized=&Messy+But,: :\n"
20572                    "       Still=Intentional);",
20573                    Style));
20574 
20575   Style.ColumnLimit = 21;
20576   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
20577             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
20578 }
20579 
20580 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
20581   // These tests are not in NamespaceFixer because that doesn't
20582   // test its interaction with line wrapping
20583   FormatStyle Style = getLLVMStyle();
20584   Style.ColumnLimit = 80;
20585   verifyFormat("namespace {\n"
20586                "int i;\n"
20587                "int j;\n"
20588                "} // namespace",
20589                Style);
20590 
20591   verifyFormat("namespace AAA {\n"
20592                "int i;\n"
20593                "int j;\n"
20594                "} // namespace AAA",
20595                Style);
20596 
20597   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
20598             "int i;\n"
20599             "int j;\n"
20600             "} // namespace Averyveryveryverylongnamespace",
20601             format("namespace Averyveryveryverylongnamespace {\n"
20602                    "int i;\n"
20603                    "int j;\n"
20604                    "}",
20605                    Style));
20606 
20607   EXPECT_EQ(
20608       "namespace "
20609       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
20610       "    went::mad::now {\n"
20611       "int i;\n"
20612       "int j;\n"
20613       "} // namespace\n"
20614       "  // "
20615       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
20616       "went::mad::now",
20617       format("namespace "
20618              "would::it::save::you::a::lot::of::time::if_::i::"
20619              "just::gave::up::and_::went::mad::now {\n"
20620              "int i;\n"
20621              "int j;\n"
20622              "}",
20623              Style));
20624 
20625   // This used to duplicate the comment again and again on subsequent runs
20626   EXPECT_EQ(
20627       "namespace "
20628       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
20629       "    went::mad::now {\n"
20630       "int i;\n"
20631       "int j;\n"
20632       "} // namespace\n"
20633       "  // "
20634       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
20635       "went::mad::now",
20636       format("namespace "
20637              "would::it::save::you::a::lot::of::time::if_::i::"
20638              "just::gave::up::and_::went::mad::now {\n"
20639              "int i;\n"
20640              "int j;\n"
20641              "} // namespace\n"
20642              "  // "
20643              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
20644              "and_::went::mad::now",
20645              Style));
20646 }
20647 
20648 TEST_F(FormatTest, LikelyUnlikely) {
20649   FormatStyle Style = getLLVMStyle();
20650 
20651   verifyFormat("if (argc > 5) [[unlikely]] {\n"
20652                "  return 29;\n"
20653                "}",
20654                Style);
20655 
20656   verifyFormat("if (argc > 5) [[likely]] {\n"
20657                "  return 29;\n"
20658                "}",
20659                Style);
20660 
20661   verifyFormat("if (argc > 5) [[unlikely]] {\n"
20662                "  return 29;\n"
20663                "} else [[likely]] {\n"
20664                "  return 42;\n"
20665                "}\n",
20666                Style);
20667 
20668   verifyFormat("if (argc > 5) [[unlikely]] {\n"
20669                "  return 29;\n"
20670                "} else if (argc > 10) [[likely]] {\n"
20671                "  return 99;\n"
20672                "} else {\n"
20673                "  return 42;\n"
20674                "}\n",
20675                Style);
20676 
20677   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
20678                "  return 29;\n"
20679                "}",
20680                Style);
20681 }
20682 
20683 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
20684   verifyFormat("Constructor()\n"
20685                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20686                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
20687                "aaaaaaaaaaaaaaaaaat))");
20688   verifyFormat("Constructor()\n"
20689                "    : aaaaaaaaaaaaa(aaaaaa), "
20690                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
20691 
20692   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
20693   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
20694   verifyFormat("Constructor()\n"
20695                "    : aaaaaa(aaaaaa),\n"
20696                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
20697                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
20698                StyleWithWhitespacePenalty);
20699   verifyFormat("Constructor()\n"
20700                "    : aaaaaaaaaaaaa(aaaaaa), "
20701                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
20702                StyleWithWhitespacePenalty);
20703 }
20704 
20705 TEST_F(FormatTest, LLVMDefaultStyle) {
20706   FormatStyle Style = getLLVMStyle();
20707   verifyFormat("extern \"C\" {\n"
20708                "int foo();\n"
20709                "}",
20710                Style);
20711 }
20712 TEST_F(FormatTest, GNUDefaultStyle) {
20713   FormatStyle Style = getGNUStyle();
20714   verifyFormat("extern \"C\"\n"
20715                "{\n"
20716                "  int foo ();\n"
20717                "}",
20718                Style);
20719 }
20720 TEST_F(FormatTest, MozillaDefaultStyle) {
20721   FormatStyle Style = getMozillaStyle();
20722   verifyFormat("extern \"C\"\n"
20723                "{\n"
20724                "  int foo();\n"
20725                "}",
20726                Style);
20727 }
20728 TEST_F(FormatTest, GoogleDefaultStyle) {
20729   FormatStyle Style = getGoogleStyle();
20730   verifyFormat("extern \"C\" {\n"
20731                "int foo();\n"
20732                "}",
20733                Style);
20734 }
20735 TEST_F(FormatTest, ChromiumDefaultStyle) {
20736   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
20737   verifyFormat("extern \"C\" {\n"
20738                "int foo();\n"
20739                "}",
20740                Style);
20741 }
20742 TEST_F(FormatTest, MicrosoftDefaultStyle) {
20743   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
20744   verifyFormat("extern \"C\"\n"
20745                "{\n"
20746                "    int foo();\n"
20747                "}",
20748                Style);
20749 }
20750 TEST_F(FormatTest, WebKitDefaultStyle) {
20751   FormatStyle Style = getWebKitStyle();
20752   verifyFormat("extern \"C\" {\n"
20753                "int foo();\n"
20754                "}",
20755                Style);
20756 }
20757 
20758 TEST_F(FormatTest, ConceptsAndRequires) {
20759   FormatStyle Style = getLLVMStyle();
20760   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
20761 
20762   verifyFormat("template <typename T>\n"
20763                "concept Hashable = requires(T a) {\n"
20764                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
20765                "};",
20766                Style);
20767   verifyFormat("template <typename T>\n"
20768                "concept EqualityComparable = requires(T a, T b) {\n"
20769                "  { a == b } -> bool;\n"
20770                "};",
20771                Style);
20772   verifyFormat("template <typename T>\n"
20773                "concept EqualityComparable = requires(T a, T b) {\n"
20774                "  { a == b } -> bool;\n"
20775                "  { a != b } -> bool;\n"
20776                "};",
20777                Style);
20778   verifyFormat("template <typename T>\n"
20779                "concept EqualityComparable = requires(T a, T b) {\n"
20780                "  { a == b } -> bool;\n"
20781                "  { a != b } -> bool;\n"
20782                "};",
20783                Style);
20784 
20785   verifyFormat("template <typename It>\n"
20786                "requires Iterator<It>\n"
20787                "void sort(It begin, It end) {\n"
20788                "  //....\n"
20789                "}",
20790                Style);
20791 
20792   verifyFormat("template <typename T>\n"
20793                "concept Large = sizeof(T) > 10;",
20794                Style);
20795 
20796   verifyFormat("template <typename T, typename U>\n"
20797                "concept FooableWith = requires(T t, U u) {\n"
20798                "  typename T::foo_type;\n"
20799                "  { t.foo(u) } -> typename T::foo_type;\n"
20800                "  t++;\n"
20801                "};\n"
20802                "void doFoo(FooableWith<int> auto t) {\n"
20803                "  t.foo(3);\n"
20804                "}",
20805                Style);
20806   verifyFormat("template <typename T>\n"
20807                "concept Context = sizeof(T) == 1;",
20808                Style);
20809   verifyFormat("template <typename T>\n"
20810                "concept Context = is_specialization_of_v<context, T>;",
20811                Style);
20812   verifyFormat("template <typename T>\n"
20813                "concept Node = std::is_object_v<T>;",
20814                Style);
20815   verifyFormat("template <typename T>\n"
20816                "concept Tree = true;",
20817                Style);
20818 
20819   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
20820                "  //...\n"
20821                "}",
20822                Style);
20823 
20824   verifyFormat(
20825       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
20826       "  //...\n"
20827       "}",
20828       Style);
20829 
20830   verifyFormat(
20831       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
20832       "  //...\n"
20833       "}",
20834       Style);
20835 
20836   verifyFormat("template <typename T>\n"
20837                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
20838                "Concept2<I> {\n"
20839                "  //...\n"
20840                "}",
20841                Style);
20842 
20843   verifyFormat("template <typename T>\n"
20844                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
20845                "Concept2<I> {\n"
20846                "  //...\n"
20847                "}",
20848                Style);
20849 
20850   verifyFormat(
20851       "template <typename T>\n"
20852       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
20853       "  //...\n"
20854       "}",
20855       Style);
20856 
20857   verifyFormat(
20858       "template <typename T>\n"
20859       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
20860       "  //...\n"
20861       "}",
20862       Style);
20863 
20864   verifyFormat("template <typename It>\n"
20865                "requires Foo<It>() && Bar<It> {\n"
20866                "  //....\n"
20867                "}",
20868                Style);
20869 
20870   verifyFormat("template <typename It>\n"
20871                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
20872                "  //....\n"
20873                "}",
20874                Style);
20875 
20876   verifyFormat("template <typename It>\n"
20877                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
20878                "  //....\n"
20879                "}",
20880                Style);
20881 
20882   verifyFormat(
20883       "template <typename It>\n"
20884       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
20885       "  //....\n"
20886       "}",
20887       Style);
20888 
20889   Style.IndentRequires = true;
20890   verifyFormat("template <typename It>\n"
20891                "  requires Iterator<It>\n"
20892                "void sort(It begin, It end) {\n"
20893                "  //....\n"
20894                "}",
20895                Style);
20896   verifyFormat("template <std::size index_>\n"
20897                "  requires(index_ < sizeof...(Children_))\n"
20898                "Tree auto &child() {\n"
20899                "  // ...\n"
20900                "}",
20901                Style);
20902 
20903   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
20904   verifyFormat("template <typename T>\n"
20905                "concept Hashable = requires (T a) {\n"
20906                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
20907                "};",
20908                Style);
20909 
20910   verifyFormat("template <class T = void>\n"
20911                "  requires EqualityComparable<T> || Same<T, void>\n"
20912                "struct equal_to;",
20913                Style);
20914 
20915   verifyFormat("template <class T>\n"
20916                "  requires requires {\n"
20917                "    T{};\n"
20918                "    T (int);\n"
20919                "  }\n",
20920                Style);
20921 
20922   Style.ColumnLimit = 78;
20923   verifyFormat("template <typename T>\n"
20924                "concept Context = Traits<typename T::traits_type> and\n"
20925                "    Interface<typename T::interface_type> and\n"
20926                "    Request<typename T::request_type> and\n"
20927                "    Response<typename T::response_type> and\n"
20928                "    ContextExtension<typename T::extension_type> and\n"
20929                "    ::std::is_copy_constructable<T> and "
20930                "::std::is_move_constructable<T> and\n"
20931                "    requires (T c) {\n"
20932                "  { c.response; } -> Response;\n"
20933                "} and requires (T c) {\n"
20934                "  { c.request; } -> Request;\n"
20935                "}\n",
20936                Style);
20937 
20938   verifyFormat("template <typename T>\n"
20939                "concept Context = Traits<typename T::traits_type> or\n"
20940                "    Interface<typename T::interface_type> or\n"
20941                "    Request<typename T::request_type> or\n"
20942                "    Response<typename T::response_type> or\n"
20943                "    ContextExtension<typename T::extension_type> or\n"
20944                "    ::std::is_copy_constructable<T> or "
20945                "::std::is_move_constructable<T> or\n"
20946                "    requires (T c) {\n"
20947                "  { c.response; } -> Response;\n"
20948                "} or requires (T c) {\n"
20949                "  { c.request; } -> Request;\n"
20950                "}\n",
20951                Style);
20952 
20953   verifyFormat("template <typename T>\n"
20954                "concept Context = Traits<typename T::traits_type> &&\n"
20955                "    Interface<typename T::interface_type> &&\n"
20956                "    Request<typename T::request_type> &&\n"
20957                "    Response<typename T::response_type> &&\n"
20958                "    ContextExtension<typename T::extension_type> &&\n"
20959                "    ::std::is_copy_constructable<T> && "
20960                "::std::is_move_constructable<T> &&\n"
20961                "    requires (T c) {\n"
20962                "  { c.response; } -> Response;\n"
20963                "} && requires (T c) {\n"
20964                "  { c.request; } -> Request;\n"
20965                "}\n",
20966                Style);
20967 
20968   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
20969                "Constraint2<T>;");
20970 
20971   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
20972   Style.BraceWrapping.AfterFunction = true;
20973   Style.BraceWrapping.AfterClass = true;
20974   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
20975   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
20976   verifyFormat("void Foo () requires (std::copyable<T>)\n"
20977                "{\n"
20978                "  return\n"
20979                "}\n",
20980                Style);
20981 
20982   verifyFormat("void Foo () requires std::copyable<T>\n"
20983                "{\n"
20984                "  return\n"
20985                "}\n",
20986                Style);
20987 
20988   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
20989                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
20990                "struct constant;",
20991                Style);
20992 
20993   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
20994                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
20995                "struct constant;",
20996                Style);
20997 
20998   verifyFormat("template <class T>\n"
20999                "class plane_with_very_very_very_long_name\n"
21000                "{\n"
21001                "  constexpr plane_with_very_very_very_long_name () requires "
21002                "std::copyable<T>\n"
21003                "      : plane_with_very_very_very_long_name (1)\n"
21004                "  {\n"
21005                "  }\n"
21006                "}\n",
21007                Style);
21008 
21009   verifyFormat("template <class T>\n"
21010                "class plane_with_long_name\n"
21011                "{\n"
21012                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
21013                "      : plane_with_long_name (1)\n"
21014                "  {\n"
21015                "  }\n"
21016                "}\n",
21017                Style);
21018 
21019   Style.BreakBeforeConceptDeclarations = false;
21020   verifyFormat("template <typename T> concept Tree = true;", Style);
21021 
21022   Style.IndentRequires = false;
21023   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
21024                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
21025                "struct constant;",
21026                Style);
21027 }
21028 
21029 TEST_F(FormatTest, StatementAttributeLikeMacros) {
21030   FormatStyle Style = getLLVMStyle();
21031   StringRef Source = "void Foo::slot() {\n"
21032                      "  unsigned char MyChar = 'x';\n"
21033                      "  emit signal(MyChar);\n"
21034                      "  Q_EMIT signal(MyChar);\n"
21035                      "}";
21036 
21037   EXPECT_EQ(Source, format(Source, Style));
21038 
21039   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
21040   EXPECT_EQ("void Foo::slot() {\n"
21041             "  unsigned char MyChar = 'x';\n"
21042             "  emit          signal(MyChar);\n"
21043             "  Q_EMIT signal(MyChar);\n"
21044             "}",
21045             format(Source, Style));
21046 
21047   Style.StatementAttributeLikeMacros.push_back("emit");
21048   EXPECT_EQ(Source, format(Source, Style));
21049 
21050   Style.StatementAttributeLikeMacros = {};
21051   EXPECT_EQ("void Foo::slot() {\n"
21052             "  unsigned char MyChar = 'x';\n"
21053             "  emit          signal(MyChar);\n"
21054             "  Q_EMIT        signal(MyChar);\n"
21055             "}",
21056             format(Source, Style));
21057 }
21058 
21059 TEST_F(FormatTest, IndentAccessModifiers) {
21060   FormatStyle Style = getLLVMStyle();
21061   Style.IndentAccessModifiers = true;
21062   // Members are *two* levels below the record;
21063   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
21064   verifyFormat("class C {\n"
21065                "    int i;\n"
21066                "};\n",
21067                Style);
21068   verifyFormat("union C {\n"
21069                "    int i;\n"
21070                "    unsigned u;\n"
21071                "};\n",
21072                Style);
21073   // Access modifiers should be indented one level below the record.
21074   verifyFormat("class C {\n"
21075                "  public:\n"
21076                "    int i;\n"
21077                "};\n",
21078                Style);
21079   verifyFormat("struct S {\n"
21080                "  private:\n"
21081                "    class C {\n"
21082                "        int j;\n"
21083                "\n"
21084                "      public:\n"
21085                "        C();\n"
21086                "    };\n"
21087                "\n"
21088                "  public:\n"
21089                "    int i;\n"
21090                "};\n",
21091                Style);
21092   // Enumerations are not records and should be unaffected.
21093   Style.AllowShortEnumsOnASingleLine = false;
21094   verifyFormat("enum class E\n"
21095                "{\n"
21096                "  A,\n"
21097                "  B\n"
21098                "};\n",
21099                Style);
21100   // Test with a different indentation width;
21101   // also proves that the result is Style.AccessModifierOffset agnostic.
21102   Style.IndentWidth = 3;
21103   verifyFormat("class C {\n"
21104                "   public:\n"
21105                "      int i;\n"
21106                "};\n",
21107                Style);
21108 }
21109 
21110 TEST_F(FormatTest, LimitlessStringsAndComments) {
21111   auto Style = getLLVMStyleWithColumns(0);
21112   constexpr StringRef Code =
21113       "/**\n"
21114       " * This is a multiline comment with quite some long lines, at least for "
21115       "the LLVM Style.\n"
21116       " * We will redo this with strings and line comments. Just to  check if "
21117       "everything is working.\n"
21118       " */\n"
21119       "bool foo() {\n"
21120       "  /* Single line multi line comment. */\n"
21121       "  const std::string String = \"This is a multiline string with quite "
21122       "some long lines, at least for the LLVM Style.\"\n"
21123       "                             \"We already did it with multi line "
21124       "comments, and we will do it with line comments. Just to check if "
21125       "everything is working.\";\n"
21126       "  // This is a line comment (block) with quite some long lines, at "
21127       "least for the LLVM Style.\n"
21128       "  // We already did this with multi line comments and strings. Just to "
21129       "check if everything is working.\n"
21130       "  const std::string SmallString = \"Hello World\";\n"
21131       "  // Small line comment\n"
21132       "  return String.size() > SmallString.size();\n"
21133       "}";
21134   EXPECT_EQ(Code, format(Code, Style));
21135 }
21136 } // namespace
21137 } // namespace format
21138 } // namespace clang
21139