1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Format/Format.h"
10 
11 #include "../Tooling/ReplacementTest.h"
12 #include "FormatTestUtils.h"
13 
14 #include "clang/Frontend/TextDiagnosticPrinter.h"
15 #include "llvm/Support/Debug.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "gtest/gtest.h"
18 
19 #define DEBUG_TYPE "format-test"
20 
21 using clang::tooling::ReplacementTest;
22 using clang::tooling::toReplacements;
23 
24 namespace clang {
25 namespace format {
26 namespace {
27 
getGoogleStyle()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 
format(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle (),StatusCheck CheckComplete=SC_ExpectComplete)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 
getStyleWithColumns(FormatStyle Style,unsigned ColumnLimit)55   FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) {
56     Style.ColumnLimit = ColumnLimit;
57     return Style;
58   }
59 
getLLVMStyleWithColumns(unsigned ColumnLimit)60   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
61     return getStyleWithColumns(getLLVMStyle(), ColumnLimit);
62   }
63 
getGoogleStyleWithColumns(unsigned ColumnLimit)64   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
65     return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
66   }
67 
verifyFormat(llvm::StringRef Expected,llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())68   void verifyFormat(llvm::StringRef Expected, llvm::StringRef Code,
69                     const FormatStyle &Style = getLLVMStyle()) {
70     EXPECT_EQ(Expected.str(), format(Expected, Style))
71         << "Expected code is not stable";
72     EXPECT_EQ(Expected.str(), format(Code, Style));
73     if (Style.Language == FormatStyle::LK_Cpp) {
74       // Objective-C++ is a superset of C++, so everything checked for C++
75       // needs to be checked for Objective-C++ as well.
76       FormatStyle ObjCStyle = Style;
77       ObjCStyle.Language = FormatStyle::LK_ObjC;
78       EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle));
79     }
80   }
81 
verifyFormat(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())82   void verifyFormat(llvm::StringRef Code,
83                     const FormatStyle &Style = getLLVMStyle()) {
84     verifyFormat(Code, test::messUp(Code), Style);
85   }
86 
verifyIncompleteFormat(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())87   void verifyIncompleteFormat(llvm::StringRef Code,
88                               const FormatStyle &Style = getLLVMStyle()) {
89     EXPECT_EQ(Code.str(),
90               format(test::messUp(Code), Style, SC_ExpectIncomplete));
91   }
92 
verifyGoogleFormat(llvm::StringRef Code)93   void verifyGoogleFormat(llvm::StringRef Code) {
94     verifyFormat(Code, getGoogleStyle());
95   }
96 
verifyIndependentOfContext(llvm::StringRef text)97   void verifyIndependentOfContext(llvm::StringRef text) {
98     verifyFormat(text);
99     verifyFormat(llvm::Twine("void f() { " + text + " }").str());
100   }
101 
102   /// \brief Verify that clang-format does not crash on the given input.
verifyNoCrash(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())103   void verifyNoCrash(llvm::StringRef Code,
104                      const FormatStyle &Style = getLLVMStyle()) {
105     format(Code, Style, SC_DoNotCheck);
106   }
107 
108   int ReplacementCount;
109 };
110 
TEST_F(FormatTest,MessUp)111 TEST_F(FormatTest, MessUp) {
112   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
113   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
114   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
115   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
116   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
117 }
118 
TEST_F(FormatTest,DefaultLLVMStyleIsCpp)119 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
120   EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
121 }
122 
TEST_F(FormatTest,LLVMStyleOverride)123 TEST_F(FormatTest, LLVMStyleOverride) {
124   EXPECT_EQ(FormatStyle::LK_Proto,
125             getLLVMStyle(FormatStyle::LK_Proto).Language);
126 }
127 
128 //===----------------------------------------------------------------------===//
129 // Basic function tests.
130 //===----------------------------------------------------------------------===//
131 
TEST_F(FormatTest,DoesNotChangeCorrectlyFormattedCode)132 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
133   EXPECT_EQ(";", format(";"));
134 }
135 
TEST_F(FormatTest,FormatsGlobalStatementsAt0)136 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
137   EXPECT_EQ("int i;", format("  int i;"));
138   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
139   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
140   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
141 }
142 
TEST_F(FormatTest,FormatsUnwrappedLinesAtFirstFormat)143 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
144   EXPECT_EQ("int i;", format("int\ni;"));
145 }
146 
TEST_F(FormatTest,FormatsNestedBlockStatements)147 TEST_F(FormatTest, FormatsNestedBlockStatements) {
148   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
149 }
150 
TEST_F(FormatTest,FormatsNestedCall)151 TEST_F(FormatTest, FormatsNestedCall) {
152   verifyFormat("Method(f1, f2(f3));");
153   verifyFormat("Method(f1(f2, f3()));");
154   verifyFormat("Method(f1(f2, (f3())));");
155 }
156 
TEST_F(FormatTest,NestedNameSpecifiers)157 TEST_F(FormatTest, NestedNameSpecifiers) {
158   verifyFormat("vector<::Type> v;");
159   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
160   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
161   verifyFormat("bool a = 2 < ::SomeFunction();");
162   verifyFormat("ALWAYS_INLINE ::std::string getName();");
163   verifyFormat("some::string getName();");
164 }
165 
TEST_F(FormatTest,OnlyGeneratesNecessaryReplacements)166 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
167   EXPECT_EQ("if (a) {\n"
168             "  f();\n"
169             "}",
170             format("if(a){f();}"));
171   EXPECT_EQ(4, ReplacementCount);
172   EXPECT_EQ("if (a) {\n"
173             "  f();\n"
174             "}",
175             format("if (a) {\n"
176                    "  f();\n"
177                    "}"));
178   EXPECT_EQ(0, ReplacementCount);
179   EXPECT_EQ("/*\r\n"
180             "\r\n"
181             "*/\r\n",
182             format("/*\r\n"
183                    "\r\n"
184                    "*/\r\n"));
185   EXPECT_EQ(0, ReplacementCount);
186 }
187 
TEST_F(FormatTest,RemovesEmptyLines)188 TEST_F(FormatTest, RemovesEmptyLines) {
189   EXPECT_EQ("class C {\n"
190             "  int i;\n"
191             "};",
192             format("class C {\n"
193                    " int i;\n"
194                    "\n"
195                    "};"));
196 
197   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
198   EXPECT_EQ("namespace N {\n"
199             "\n"
200             "int i;\n"
201             "}",
202             format("namespace N {\n"
203                    "\n"
204                    "int    i;\n"
205                    "}",
206                    getGoogleStyle()));
207   EXPECT_EQ("/* something */ namespace N {\n"
208             "\n"
209             "int i;\n"
210             "}",
211             format("/* something */ namespace N {\n"
212                    "\n"
213                    "int    i;\n"
214                    "}",
215                    getGoogleStyle()));
216   EXPECT_EQ("inline namespace N {\n"
217             "\n"
218             "int i;\n"
219             "}",
220             format("inline namespace N {\n"
221                    "\n"
222                    "int    i;\n"
223                    "}",
224                    getGoogleStyle()));
225   EXPECT_EQ("/* something */ inline namespace N {\n"
226             "\n"
227             "int i;\n"
228             "}",
229             format("/* something */ inline namespace N {\n"
230                    "\n"
231                    "int    i;\n"
232                    "}",
233                    getGoogleStyle()));
234   EXPECT_EQ("export namespace N {\n"
235             "\n"
236             "int i;\n"
237             "}",
238             format("export namespace N {\n"
239                    "\n"
240                    "int    i;\n"
241                    "}",
242                    getGoogleStyle()));
243   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
244             "\n"
245             "int i;\n"
246             "}",
247             format("extern /**/ \"C\" /**/ {\n"
248                    "\n"
249                    "int    i;\n"
250                    "}",
251                    getGoogleStyle()));
252 
253   // ...but do keep inlining and removing empty lines for non-block extern "C"
254   // functions.
255   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
256   EXPECT_EQ("extern \"C\" int f() {\n"
257             "  int i = 42;\n"
258             "  return i;\n"
259             "}",
260             format("extern \"C\" int f() {\n"
261                    "\n"
262                    "  int i = 42;\n"
263                    "  return i;\n"
264                    "}",
265                    getGoogleStyle()));
266 
267   // Remove empty lines at the beginning and end of blocks.
268   EXPECT_EQ("void f() {\n"
269             "\n"
270             "  if (a) {\n"
271             "\n"
272             "    f();\n"
273             "  }\n"
274             "}",
275             format("void f() {\n"
276                    "\n"
277                    "  if (a) {\n"
278                    "\n"
279                    "    f();\n"
280                    "\n"
281                    "  }\n"
282                    "\n"
283                    "}",
284                    getLLVMStyle()));
285   EXPECT_EQ("void f() {\n"
286             "  if (a) {\n"
287             "    f();\n"
288             "  }\n"
289             "}",
290             format("void f() {\n"
291                    "\n"
292                    "  if (a) {\n"
293                    "\n"
294                    "    f();\n"
295                    "\n"
296                    "  }\n"
297                    "\n"
298                    "}",
299                    getGoogleStyle()));
300 
301   // Don't remove empty lines in more complex control statements.
302   EXPECT_EQ("void f() {\n"
303             "  if (a) {\n"
304             "    f();\n"
305             "\n"
306             "  } else if (b) {\n"
307             "    f();\n"
308             "  }\n"
309             "}",
310             format("void f() {\n"
311                    "  if (a) {\n"
312                    "    f();\n"
313                    "\n"
314                    "  } else if (b) {\n"
315                    "    f();\n"
316                    "\n"
317                    "  }\n"
318                    "\n"
319                    "}"));
320 
321   // Don't remove empty lines before namespace endings.
322   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
323   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
324   EXPECT_EQ("namespace {\n"
325             "int i;\n"
326             "\n"
327             "}",
328             format("namespace {\n"
329                    "int i;\n"
330                    "\n"
331                    "}",
332                    LLVMWithNoNamespaceFix));
333   EXPECT_EQ("namespace {\n"
334             "int i;\n"
335             "}",
336             format("namespace {\n"
337                    "int i;\n"
338                    "}",
339                    LLVMWithNoNamespaceFix));
340   EXPECT_EQ("namespace {\n"
341             "int i;\n"
342             "\n"
343             "};",
344             format("namespace {\n"
345                    "int i;\n"
346                    "\n"
347                    "};",
348                    LLVMWithNoNamespaceFix));
349   EXPECT_EQ("namespace {\n"
350             "int i;\n"
351             "};",
352             format("namespace {\n"
353                    "int i;\n"
354                    "};",
355                    LLVMWithNoNamespaceFix));
356   EXPECT_EQ("namespace {\n"
357             "int i;\n"
358             "\n"
359             "}",
360             format("namespace {\n"
361                    "int i;\n"
362                    "\n"
363                    "}"));
364   EXPECT_EQ("namespace {\n"
365             "int i;\n"
366             "\n"
367             "} // namespace",
368             format("namespace {\n"
369                    "int i;\n"
370                    "\n"
371                    "}  // namespace"));
372 
373   FormatStyle Style = getLLVMStyle();
374   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
375   Style.MaxEmptyLinesToKeep = 2;
376   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
377   Style.BraceWrapping.AfterClass = true;
378   Style.BraceWrapping.AfterFunction = true;
379   Style.KeepEmptyLinesAtTheStartOfBlocks = false;
380 
381   EXPECT_EQ("class Foo\n"
382             "{\n"
383             "  Foo() {}\n"
384             "\n"
385             "  void funk() {}\n"
386             "};",
387             format("class Foo\n"
388                    "{\n"
389                    "  Foo()\n"
390                    "  {\n"
391                    "  }\n"
392                    "\n"
393                    "  void funk() {}\n"
394                    "};",
395                    Style));
396 }
397 
TEST_F(FormatTest,RecognizesBinaryOperatorKeywords)398 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
399   verifyFormat("x = (a) and (b);");
400   verifyFormat("x = (a) or (b);");
401   verifyFormat("x = (a) bitand (b);");
402   verifyFormat("x = (a) bitor (b);");
403   verifyFormat("x = (a) not_eq (b);");
404   verifyFormat("x = (a) and_eq (b);");
405   verifyFormat("x = (a) or_eq (b);");
406   verifyFormat("x = (a) xor (b);");
407 }
408 
TEST_F(FormatTest,RecognizesUnaryOperatorKeywords)409 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
410   verifyFormat("x = compl(a);");
411   verifyFormat("x = not(a);");
412   verifyFormat("x = bitand(a);");
413   // Unary operator must not be merged with the next identifier
414   verifyFormat("x = compl a;");
415   verifyFormat("x = not a;");
416   verifyFormat("x = bitand a;");
417 }
418 
419 //===----------------------------------------------------------------------===//
420 // Tests for control statements.
421 //===----------------------------------------------------------------------===//
422 
TEST_F(FormatTest,FormatIfWithoutCompoundStatement)423 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
424   verifyFormat("if (true)\n  f();\ng();");
425   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
426   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
427   verifyFormat("if constexpr (true)\n"
428                "  f();\ng();");
429   verifyFormat("if CONSTEXPR (true)\n"
430                "  f();\ng();");
431   verifyFormat("if constexpr (a)\n"
432                "  if constexpr (b)\n"
433                "    if constexpr (c)\n"
434                "      g();\n"
435                "h();");
436   verifyFormat("if CONSTEXPR (a)\n"
437                "  if CONSTEXPR (b)\n"
438                "    if CONSTEXPR (c)\n"
439                "      g();\n"
440                "h();");
441   verifyFormat("if constexpr (a)\n"
442                "  if constexpr (b) {\n"
443                "    f();\n"
444                "  }\n"
445                "g();");
446   verifyFormat("if CONSTEXPR (a)\n"
447                "  if CONSTEXPR (b) {\n"
448                "    f();\n"
449                "  }\n"
450                "g();");
451 
452   FormatStyle AllowsMergedIf = getLLVMStyle();
453   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
454   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
455       FormatStyle::SIS_WithoutElse;
456   verifyFormat("if (a)\n"
457                "  // comment\n"
458                "  f();",
459                AllowsMergedIf);
460   verifyFormat("{\n"
461                "  if (a)\n"
462                "  label:\n"
463                "    f();\n"
464                "}",
465                AllowsMergedIf);
466   verifyFormat("#define A \\\n"
467                "  if (a)  \\\n"
468                "  label:  \\\n"
469                "    f()",
470                AllowsMergedIf);
471   verifyFormat("if (a)\n"
472                "  ;",
473                AllowsMergedIf);
474   verifyFormat("if (a)\n"
475                "  if (b) return;",
476                AllowsMergedIf);
477 
478   verifyFormat("if (a) // Can't merge this\n"
479                "  f();\n",
480                AllowsMergedIf);
481   verifyFormat("if (a) /* still don't merge */\n"
482                "  f();",
483                AllowsMergedIf);
484   verifyFormat("if (a) { // Never merge this\n"
485                "  f();\n"
486                "}",
487                AllowsMergedIf);
488   verifyFormat("if (a) { /* Never merge this */\n"
489                "  f();\n"
490                "}",
491                AllowsMergedIf);
492 
493   AllowsMergedIf.ColumnLimit = 14;
494   verifyFormat("if (a) return;", AllowsMergedIf);
495   verifyFormat("if (aaaaaaaaa)\n"
496                "  return;",
497                AllowsMergedIf);
498 
499   AllowsMergedIf.ColumnLimit = 13;
500   verifyFormat("if (a)\n  return;", AllowsMergedIf);
501 }
502 
TEST_F(FormatTest,FormatIfWithoutCompoundStatementButElseWith)503 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
504   FormatStyle AllowsMergedIf = getLLVMStyle();
505   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
506   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
507       FormatStyle::SIS_WithoutElse;
508   verifyFormat("if (a)\n"
509                "  f();\n"
510                "else {\n"
511                "  g();\n"
512                "}",
513                AllowsMergedIf);
514   verifyFormat("if (a)\n"
515                "  f();\n"
516                "else\n"
517                "  g();\n",
518                AllowsMergedIf);
519 
520   AllowsMergedIf.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
521 
522   verifyFormat("if (a) f();\n"
523                "else {\n"
524                "  g();\n"
525                "}",
526                AllowsMergedIf);
527   verifyFormat("if (a) f();\n"
528                "else {\n"
529                "  if (a) f();\n"
530                "  else {\n"
531                "    g();\n"
532                "  }\n"
533                "  g();\n"
534                "}",
535                AllowsMergedIf);
536 }
537 
TEST_F(FormatTest,FormatLoopsWithoutCompoundStatement)538 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
539   FormatStyle AllowsMergedLoops = getLLVMStyle();
540   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
541   verifyFormat("while (true) continue;", AllowsMergedLoops);
542   verifyFormat("for (;;) continue;", AllowsMergedLoops);
543   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
544   verifyFormat("while (true)\n"
545                "  ;",
546                AllowsMergedLoops);
547   verifyFormat("for (;;)\n"
548                "  ;",
549                AllowsMergedLoops);
550   verifyFormat("for (;;)\n"
551                "  for (;;) continue;",
552                AllowsMergedLoops);
553   verifyFormat("for (;;) // Can't merge this\n"
554                "  continue;",
555                AllowsMergedLoops);
556   verifyFormat("for (;;) /* still don't merge */\n"
557                "  continue;",
558                AllowsMergedLoops);
559 }
560 
TEST_F(FormatTest,FormatShortBracedStatements)561 TEST_F(FormatTest, FormatShortBracedStatements) {
562   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
563   AllowSimpleBracedStatements.ColumnLimit = 40;
564   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
565       FormatStyle::SBS_Always;
566 
567   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
568       FormatStyle::SIS_WithoutElse;
569   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
570 
571   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
572   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
573   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
574 
575   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
576   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
577   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
578   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
579   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
580   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
581   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
582   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
583   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
584   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
585   verifyFormat("if (true) {\n"
586                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
587                "}",
588                AllowSimpleBracedStatements);
589   verifyFormat("if (true) { //\n"
590                "  f();\n"
591                "}",
592                AllowSimpleBracedStatements);
593   verifyFormat("if (true) {\n"
594                "  f();\n"
595                "  f();\n"
596                "}",
597                AllowSimpleBracedStatements);
598   verifyFormat("if (true) {\n"
599                "  f();\n"
600                "} else {\n"
601                "  f();\n"
602                "}",
603                AllowSimpleBracedStatements);
604 
605   verifyFormat("struct A2 {\n"
606                "  int X;\n"
607                "};",
608                AllowSimpleBracedStatements);
609   verifyFormat("typedef struct A2 {\n"
610                "  int X;\n"
611                "} A2_t;",
612                AllowSimpleBracedStatements);
613   verifyFormat("template <int> struct A2 {\n"
614                "  struct B {};\n"
615                "};",
616                AllowSimpleBracedStatements);
617 
618   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
619       FormatStyle::SIS_Never;
620   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
621   verifyFormat("if (true) {\n"
622                "  f();\n"
623                "}",
624                AllowSimpleBracedStatements);
625   verifyFormat("if (true) {\n"
626                "  f();\n"
627                "} else {\n"
628                "  f();\n"
629                "}",
630                AllowSimpleBracedStatements);
631 
632   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
633   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
634   verifyFormat("while (true) {\n"
635                "  f();\n"
636                "}",
637                AllowSimpleBracedStatements);
638   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
639   verifyFormat("for (;;) {\n"
640                "  f();\n"
641                "}",
642                AllowSimpleBracedStatements);
643 
644   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
645       FormatStyle::SIS_WithoutElse;
646   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
647   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
648       FormatStyle::BWACS_Always;
649 
650   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
651   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
652   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
653   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
654   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
655   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
656   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
657   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
658   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
659   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
660   verifyFormat("if (true)\n"
661                "{\n"
662                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
663                "}",
664                AllowSimpleBracedStatements);
665   verifyFormat("if (true)\n"
666                "{ //\n"
667                "  f();\n"
668                "}",
669                AllowSimpleBracedStatements);
670   verifyFormat("if (true)\n"
671                "{\n"
672                "  f();\n"
673                "  f();\n"
674                "}",
675                AllowSimpleBracedStatements);
676   verifyFormat("if (true)\n"
677                "{\n"
678                "  f();\n"
679                "} else\n"
680                "{\n"
681                "  f();\n"
682                "}",
683                AllowSimpleBracedStatements);
684 
685   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
686       FormatStyle::SIS_Never;
687   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
688   verifyFormat("if (true)\n"
689                "{\n"
690                "  f();\n"
691                "}",
692                AllowSimpleBracedStatements);
693   verifyFormat("if (true)\n"
694                "{\n"
695                "  f();\n"
696                "} else\n"
697                "{\n"
698                "  f();\n"
699                "}",
700                AllowSimpleBracedStatements);
701 
702   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
703   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
704   verifyFormat("while (true)\n"
705                "{\n"
706                "  f();\n"
707                "}",
708                AllowSimpleBracedStatements);
709   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
710   verifyFormat("for (;;)\n"
711                "{\n"
712                "  f();\n"
713                "}",
714                AllowSimpleBracedStatements);
715 }
716 
TEST_F(FormatTest,ShortBlocksInMacrosDontMergeWithCodeAfterMacro)717 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
718   FormatStyle Style = getLLVMStyleWithColumns(60);
719   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
720   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
721   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
722   EXPECT_EQ("#define A                                                  \\\n"
723             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
724             "  { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n"
725             "X;",
726             format("#define A \\\n"
727                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
728                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
729                    "   }\n"
730                    "X;",
731                    Style));
732 }
733 
TEST_F(FormatTest,ParseIfElse)734 TEST_F(FormatTest, ParseIfElse) {
735   verifyFormat("if (true)\n"
736                "  if (true)\n"
737                "    if (true)\n"
738                "      f();\n"
739                "    else\n"
740                "      g();\n"
741                "  else\n"
742                "    h();\n"
743                "else\n"
744                "  i();");
745   verifyFormat("if (true)\n"
746                "  if (true)\n"
747                "    if (true) {\n"
748                "      if (true)\n"
749                "        f();\n"
750                "    } else {\n"
751                "      g();\n"
752                "    }\n"
753                "  else\n"
754                "    h();\n"
755                "else {\n"
756                "  i();\n"
757                "}");
758   verifyFormat("if (true)\n"
759                "  if constexpr (true)\n"
760                "    if (true) {\n"
761                "      if constexpr (true)\n"
762                "        f();\n"
763                "    } else {\n"
764                "      g();\n"
765                "    }\n"
766                "  else\n"
767                "    h();\n"
768                "else {\n"
769                "  i();\n"
770                "}");
771   verifyFormat("if (true)\n"
772                "  if CONSTEXPR (true)\n"
773                "    if (true) {\n"
774                "      if CONSTEXPR (true)\n"
775                "        f();\n"
776                "    } else {\n"
777                "      g();\n"
778                "    }\n"
779                "  else\n"
780                "    h();\n"
781                "else {\n"
782                "  i();\n"
783                "}");
784   verifyFormat("void f() {\n"
785                "  if (a) {\n"
786                "  } else {\n"
787                "  }\n"
788                "}");
789 }
790 
TEST_F(FormatTest,ElseIf)791 TEST_F(FormatTest, ElseIf) {
792   verifyFormat("if (a) {\n} else if (b) {\n}");
793   verifyFormat("if (a)\n"
794                "  f();\n"
795                "else if (b)\n"
796                "  g();\n"
797                "else\n"
798                "  h();");
799   verifyFormat("if constexpr (a)\n"
800                "  f();\n"
801                "else if constexpr (b)\n"
802                "  g();\n"
803                "else\n"
804                "  h();");
805   verifyFormat("if CONSTEXPR (a)\n"
806                "  f();\n"
807                "else if CONSTEXPR (b)\n"
808                "  g();\n"
809                "else\n"
810                "  h();");
811   verifyFormat("if (a) {\n"
812                "  f();\n"
813                "}\n"
814                "// or else ..\n"
815                "else {\n"
816                "  g()\n"
817                "}");
818 
819   verifyFormat("if (a) {\n"
820                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
821                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
822                "}");
823   verifyFormat("if (a) {\n"
824                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
825                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
826                "}");
827   verifyFormat("if (a) {\n"
828                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
829                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
830                "}");
831   verifyFormat("if (a) {\n"
832                "} else if (\n"
833                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
834                "}",
835                getLLVMStyleWithColumns(62));
836   verifyFormat("if (a) {\n"
837                "} else if constexpr (\n"
838                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
839                "}",
840                getLLVMStyleWithColumns(62));
841   verifyFormat("if (a) {\n"
842                "} else if CONSTEXPR (\n"
843                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
844                "}",
845                getLLVMStyleWithColumns(62));
846 }
847 
TEST_F(FormatTest,FormatsForLoop)848 TEST_F(FormatTest, FormatsForLoop) {
849   verifyFormat(
850       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
851       "     ++VeryVeryLongLoopVariable)\n"
852       "  ;");
853   verifyFormat("for (;;)\n"
854                "  f();");
855   verifyFormat("for (;;) {\n}");
856   verifyFormat("for (;;) {\n"
857                "  f();\n"
858                "}");
859   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
860 
861   verifyFormat(
862       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
863       "                                          E = UnwrappedLines.end();\n"
864       "     I != E; ++I) {\n}");
865 
866   verifyFormat(
867       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
868       "     ++IIIII) {\n}");
869   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
870                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
871                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
872   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
873                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
874                "         E = FD->getDeclsInPrototypeScope().end();\n"
875                "     I != E; ++I) {\n}");
876   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
877                "         I = Container.begin(),\n"
878                "         E = Container.end();\n"
879                "     I != E; ++I) {\n}",
880                getLLVMStyleWithColumns(76));
881 
882   verifyFormat(
883       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
884       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
885       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
886       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
887       "     ++aaaaaaaaaaa) {\n}");
888   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
889                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
890                "     ++i) {\n}");
891   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
892                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
893                "}");
894   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
895                "         aaaaaaaaaa);\n"
896                "     iter; ++iter) {\n"
897                "}");
898   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
899                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
900                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
901                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
902 
903   // These should not be formatted as Objective-C for-in loops.
904   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
905   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
906   verifyFormat("Foo *x;\nfor (x in y) {\n}");
907   verifyFormat(
908       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
909 
910   FormatStyle NoBinPacking = getLLVMStyle();
911   NoBinPacking.BinPackParameters = false;
912   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
913                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
914                "                                           aaaaaaaaaaaaaaaa,\n"
915                "                                           aaaaaaaaaaaaaaaa,\n"
916                "                                           aaaaaaaaaaaaaaaa);\n"
917                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
918                "}",
919                NoBinPacking);
920   verifyFormat(
921       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
922       "                                          E = UnwrappedLines.end();\n"
923       "     I != E;\n"
924       "     ++I) {\n}",
925       NoBinPacking);
926 
927   FormatStyle AlignLeft = getLLVMStyle();
928   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
929   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
930 }
931 
TEST_F(FormatTest,RangeBasedForLoops)932 TEST_F(FormatTest, RangeBasedForLoops) {
933   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
934                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
935   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
936                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
937   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
938                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
939   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
940                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
941 }
942 
TEST_F(FormatTest,ForEachLoops)943 TEST_F(FormatTest, ForEachLoops) {
944   verifyFormat("void f() {\n"
945                "  foreach (Item *item, itemlist) {}\n"
946                "  Q_FOREACH (Item *item, itemlist) {}\n"
947                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
948                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
949                "}");
950 
951   // As function-like macros.
952   verifyFormat("#define foreach(x, y)\n"
953                "#define Q_FOREACH(x, y)\n"
954                "#define BOOST_FOREACH(x, y)\n"
955                "#define UNKNOWN_FOREACH(x, y)\n");
956 
957   // Not as function-like macros.
958   verifyFormat("#define foreach (x, y)\n"
959                "#define Q_FOREACH (x, y)\n"
960                "#define BOOST_FOREACH (x, y)\n"
961                "#define UNKNOWN_FOREACH (x, y)\n");
962 }
963 
TEST_F(FormatTest,FormatsWhileLoop)964 TEST_F(FormatTest, FormatsWhileLoop) {
965   verifyFormat("while (true) {\n}");
966   verifyFormat("while (true)\n"
967                "  f();");
968   verifyFormat("while () {\n}");
969   verifyFormat("while () {\n"
970                "  f();\n"
971                "}");
972 }
973 
TEST_F(FormatTest,FormatsDoWhile)974 TEST_F(FormatTest, FormatsDoWhile) {
975   verifyFormat("do {\n"
976                "  do_something();\n"
977                "} while (something());");
978   verifyFormat("do\n"
979                "  do_something();\n"
980                "while (something());");
981 }
982 
TEST_F(FormatTest,FormatsSwitchStatement)983 TEST_F(FormatTest, FormatsSwitchStatement) {
984   verifyFormat("switch (x) {\n"
985                "case 1:\n"
986                "  f();\n"
987                "  break;\n"
988                "case kFoo:\n"
989                "case ns::kBar:\n"
990                "case kBaz:\n"
991                "  break;\n"
992                "default:\n"
993                "  g();\n"
994                "  break;\n"
995                "}");
996   verifyFormat("switch (x) {\n"
997                "case 1: {\n"
998                "  f();\n"
999                "  break;\n"
1000                "}\n"
1001                "case 2: {\n"
1002                "  break;\n"
1003                "}\n"
1004                "}");
1005   verifyFormat("switch (x) {\n"
1006                "case 1: {\n"
1007                "  f();\n"
1008                "  {\n"
1009                "    g();\n"
1010                "    h();\n"
1011                "  }\n"
1012                "  break;\n"
1013                "}\n"
1014                "}");
1015   verifyFormat("switch (x) {\n"
1016                "case 1: {\n"
1017                "  f();\n"
1018                "  if (foo) {\n"
1019                "    g();\n"
1020                "    h();\n"
1021                "  }\n"
1022                "  break;\n"
1023                "}\n"
1024                "}");
1025   verifyFormat("switch (x) {\n"
1026                "case 1: {\n"
1027                "  f();\n"
1028                "  g();\n"
1029                "} break;\n"
1030                "}");
1031   verifyFormat("switch (test)\n"
1032                "  ;");
1033   verifyFormat("switch (x) {\n"
1034                "default: {\n"
1035                "  // Do nothing.\n"
1036                "}\n"
1037                "}");
1038   verifyFormat("switch (x) {\n"
1039                "// comment\n"
1040                "// if 1, do f()\n"
1041                "case 1:\n"
1042                "  f();\n"
1043                "}");
1044   verifyFormat("switch (x) {\n"
1045                "case 1:\n"
1046                "  // Do amazing stuff\n"
1047                "  {\n"
1048                "    f();\n"
1049                "    g();\n"
1050                "  }\n"
1051                "  break;\n"
1052                "}");
1053   verifyFormat("#define A          \\\n"
1054                "  switch (x) {     \\\n"
1055                "  case a:          \\\n"
1056                "    foo = b;       \\\n"
1057                "  }",
1058                getLLVMStyleWithColumns(20));
1059   verifyFormat("#define OPERATION_CASE(name)           \\\n"
1060                "  case OP_name:                        \\\n"
1061                "    return operations::Operation##name\n",
1062                getLLVMStyleWithColumns(40));
1063   verifyFormat("switch (x) {\n"
1064                "case 1:;\n"
1065                "default:;\n"
1066                "  int i;\n"
1067                "}");
1068 
1069   verifyGoogleFormat("switch (x) {\n"
1070                      "  case 1:\n"
1071                      "    f();\n"
1072                      "    break;\n"
1073                      "  case kFoo:\n"
1074                      "  case ns::kBar:\n"
1075                      "  case kBaz:\n"
1076                      "    break;\n"
1077                      "  default:\n"
1078                      "    g();\n"
1079                      "    break;\n"
1080                      "}");
1081   verifyGoogleFormat("switch (x) {\n"
1082                      "  case 1: {\n"
1083                      "    f();\n"
1084                      "    break;\n"
1085                      "  }\n"
1086                      "}");
1087   verifyGoogleFormat("switch (test)\n"
1088                      "  ;");
1089 
1090   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
1091                      "  case OP_name:              \\\n"
1092                      "    return operations::Operation##name\n");
1093   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
1094                      "  // Get the correction operation class.\n"
1095                      "  switch (OpCode) {\n"
1096                      "    CASE(Add);\n"
1097                      "    CASE(Subtract);\n"
1098                      "    default:\n"
1099                      "      return operations::Unknown;\n"
1100                      "  }\n"
1101                      "#undef OPERATION_CASE\n"
1102                      "}");
1103   verifyFormat("DEBUG({\n"
1104                "  switch (x) {\n"
1105                "  case A:\n"
1106                "    f();\n"
1107                "    break;\n"
1108                "    // fallthrough\n"
1109                "  case B:\n"
1110                "    g();\n"
1111                "    break;\n"
1112                "  }\n"
1113                "});");
1114   EXPECT_EQ("DEBUG({\n"
1115             "  switch (x) {\n"
1116             "  case A:\n"
1117             "    f();\n"
1118             "    break;\n"
1119             "  // On B:\n"
1120             "  case B:\n"
1121             "    g();\n"
1122             "    break;\n"
1123             "  }\n"
1124             "});",
1125             format("DEBUG({\n"
1126                    "  switch (x) {\n"
1127                    "  case A:\n"
1128                    "    f();\n"
1129                    "    break;\n"
1130                    "  // On B:\n"
1131                    "  case B:\n"
1132                    "    g();\n"
1133                    "    break;\n"
1134                    "  }\n"
1135                    "});",
1136                    getLLVMStyle()));
1137   EXPECT_EQ("switch (n) {\n"
1138             "case 0: {\n"
1139             "  return false;\n"
1140             "}\n"
1141             "default: {\n"
1142             "  return true;\n"
1143             "}\n"
1144             "}",
1145             format("switch (n)\n"
1146                    "{\n"
1147                    "case 0: {\n"
1148                    "  return false;\n"
1149                    "}\n"
1150                    "default: {\n"
1151                    "  return true;\n"
1152                    "}\n"
1153                    "}",
1154                    getLLVMStyle()));
1155   verifyFormat("switch (a) {\n"
1156                "case (b):\n"
1157                "  return;\n"
1158                "}");
1159 
1160   verifyFormat("switch (a) {\n"
1161                "case some_namespace::\n"
1162                "    some_constant:\n"
1163                "  return;\n"
1164                "}",
1165                getLLVMStyleWithColumns(34));
1166 
1167   FormatStyle Style = getLLVMStyle();
1168   Style.IndentCaseLabels = true;
1169   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1170   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1171   Style.BraceWrapping.AfterCaseLabel = true;
1172   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1173   EXPECT_EQ("switch (n)\n"
1174             "{\n"
1175             "  case 0:\n"
1176             "  {\n"
1177             "    return false;\n"
1178             "  }\n"
1179             "  default:\n"
1180             "  {\n"
1181             "    return true;\n"
1182             "  }\n"
1183             "}",
1184             format("switch (n) {\n"
1185                    "  case 0: {\n"
1186                    "    return false;\n"
1187                    "  }\n"
1188                    "  default: {\n"
1189                    "    return true;\n"
1190                    "  }\n"
1191                    "}",
1192                    Style));
1193   Style.BraceWrapping.AfterCaseLabel = false;
1194   EXPECT_EQ("switch (n)\n"
1195             "{\n"
1196             "  case 0: {\n"
1197             "    return false;\n"
1198             "  }\n"
1199             "  default: {\n"
1200             "    return true;\n"
1201             "  }\n"
1202             "}",
1203             format("switch (n) {\n"
1204                    "  case 0:\n"
1205                    "  {\n"
1206                    "    return false;\n"
1207                    "  }\n"
1208                    "  default:\n"
1209                    "  {\n"
1210                    "    return true;\n"
1211                    "  }\n"
1212                    "}",
1213                    Style));
1214 }
1215 
TEST_F(FormatTest,CaseRanges)1216 TEST_F(FormatTest, CaseRanges) {
1217   verifyFormat("switch (x) {\n"
1218                "case 'A' ... 'Z':\n"
1219                "case 1 ... 5:\n"
1220                "case a ... b:\n"
1221                "  break;\n"
1222                "}");
1223 }
1224 
TEST_F(FormatTest,ShortCaseLabels)1225 TEST_F(FormatTest, ShortCaseLabels) {
1226   FormatStyle Style = getLLVMStyle();
1227   Style.AllowShortCaseLabelsOnASingleLine = true;
1228   verifyFormat("switch (a) {\n"
1229                "case 1: x = 1; break;\n"
1230                "case 2: return;\n"
1231                "case 3:\n"
1232                "case 4:\n"
1233                "case 5: return;\n"
1234                "case 6: // comment\n"
1235                "  return;\n"
1236                "case 7:\n"
1237                "  // comment\n"
1238                "  return;\n"
1239                "case 8:\n"
1240                "  x = 8; // comment\n"
1241                "  break;\n"
1242                "default: y = 1; break;\n"
1243                "}",
1244                Style);
1245   verifyFormat("switch (a) {\n"
1246                "case 0: return; // comment\n"
1247                "case 1: break;  // comment\n"
1248                "case 2: return;\n"
1249                "// comment\n"
1250                "case 3: return;\n"
1251                "// comment 1\n"
1252                "// comment 2\n"
1253                "// comment 3\n"
1254                "case 4: break; /* comment */\n"
1255                "case 5:\n"
1256                "  // comment\n"
1257                "  break;\n"
1258                "case 6: /* comment */ x = 1; break;\n"
1259                "case 7: x = /* comment */ 1; break;\n"
1260                "case 8:\n"
1261                "  x = 1; /* comment */\n"
1262                "  break;\n"
1263                "case 9:\n"
1264                "  break; // comment line 1\n"
1265                "         // comment line 2\n"
1266                "}",
1267                Style);
1268   EXPECT_EQ("switch (a) {\n"
1269             "case 1:\n"
1270             "  x = 8;\n"
1271             "  // fall through\n"
1272             "case 2: x = 8;\n"
1273             "// comment\n"
1274             "case 3:\n"
1275             "  return; /* comment line 1\n"
1276             "           * comment line 2 */\n"
1277             "case 4: i = 8;\n"
1278             "// something else\n"
1279             "#if FOO\n"
1280             "case 5: break;\n"
1281             "#endif\n"
1282             "}",
1283             format("switch (a) {\n"
1284                    "case 1: x = 8;\n"
1285                    "  // fall through\n"
1286                    "case 2:\n"
1287                    "  x = 8;\n"
1288                    "// comment\n"
1289                    "case 3:\n"
1290                    "  return; /* comment line 1\n"
1291                    "           * comment line 2 */\n"
1292                    "case 4:\n"
1293                    "  i = 8;\n"
1294                    "// something else\n"
1295                    "#if FOO\n"
1296                    "case 5: break;\n"
1297                    "#endif\n"
1298                    "}",
1299                    Style));
1300   EXPECT_EQ("switch (a) {\n"
1301             "case 0:\n"
1302             "  return; // long long long long long long long long long long "
1303             "long long comment\n"
1304             "          // line\n"
1305             "}",
1306             format("switch (a) {\n"
1307                    "case 0: return; // long long long long long long long long "
1308                    "long long long long comment line\n"
1309                    "}",
1310                    Style));
1311   EXPECT_EQ("switch (a) {\n"
1312             "case 0:\n"
1313             "  return; /* long long long long long long long long long long "
1314             "long long comment\n"
1315             "             line */\n"
1316             "}",
1317             format("switch (a) {\n"
1318                    "case 0: return; /* long long long long long long long long "
1319                    "long long long long comment line */\n"
1320                    "}",
1321                    Style));
1322   verifyFormat("switch (a) {\n"
1323                "#if FOO\n"
1324                "case 0: return 0;\n"
1325                "#endif\n"
1326                "}",
1327                Style);
1328   verifyFormat("switch (a) {\n"
1329                "case 1: {\n"
1330                "}\n"
1331                "case 2: {\n"
1332                "  return;\n"
1333                "}\n"
1334                "case 3: {\n"
1335                "  x = 1;\n"
1336                "  return;\n"
1337                "}\n"
1338                "case 4:\n"
1339                "  if (x)\n"
1340                "    return;\n"
1341                "}",
1342                Style);
1343   Style.ColumnLimit = 21;
1344   verifyFormat("switch (a) {\n"
1345                "case 1: x = 1; break;\n"
1346                "case 2: return;\n"
1347                "case 3:\n"
1348                "case 4:\n"
1349                "case 5: return;\n"
1350                "default:\n"
1351                "  y = 1;\n"
1352                "  break;\n"
1353                "}",
1354                Style);
1355   Style.ColumnLimit = 80;
1356   Style.AllowShortCaseLabelsOnASingleLine = false;
1357   Style.IndentCaseLabels = true;
1358   EXPECT_EQ("switch (n) {\n"
1359             "  default /*comments*/:\n"
1360             "    return true;\n"
1361             "  case 0:\n"
1362             "    return false;\n"
1363             "}",
1364             format("switch (n) {\n"
1365                    "default/*comments*/:\n"
1366                    "  return true;\n"
1367                    "case 0:\n"
1368                    "  return false;\n"
1369                    "}",
1370                    Style));
1371   Style.AllowShortCaseLabelsOnASingleLine = true;
1372   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1373   Style.BraceWrapping.AfterCaseLabel = true;
1374   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1375   EXPECT_EQ("switch (n)\n"
1376             "{\n"
1377             "  case 0:\n"
1378             "  {\n"
1379             "    return false;\n"
1380             "  }\n"
1381             "  default:\n"
1382             "  {\n"
1383             "    return true;\n"
1384             "  }\n"
1385             "}",
1386             format("switch (n) {\n"
1387                    "  case 0: {\n"
1388                    "    return false;\n"
1389                    "  }\n"
1390                    "  default:\n"
1391                    "  {\n"
1392                    "    return true;\n"
1393                    "  }\n"
1394                    "}",
1395                    Style));
1396 }
1397 
TEST_F(FormatTest,FormatsLabels)1398 TEST_F(FormatTest, FormatsLabels) {
1399   verifyFormat("void f() {\n"
1400                "  some_code();\n"
1401                "test_label:\n"
1402                "  some_other_code();\n"
1403                "  {\n"
1404                "    some_more_code();\n"
1405                "  another_label:\n"
1406                "    some_more_code();\n"
1407                "  }\n"
1408                "}");
1409   verifyFormat("{\n"
1410                "  some_code();\n"
1411                "test_label:\n"
1412                "  some_other_code();\n"
1413                "}");
1414   verifyFormat("{\n"
1415                "  some_code();\n"
1416                "test_label:;\n"
1417                "  int i = 0;\n"
1418                "}");
1419   FormatStyle Style = getLLVMStyle();
1420   Style.IndentGotoLabels = false;
1421   verifyFormat("void f() {\n"
1422                "  some_code();\n"
1423                "test_label:\n"
1424                "  some_other_code();\n"
1425                "  {\n"
1426                "    some_more_code();\n"
1427                "another_label:\n"
1428                "    some_more_code();\n"
1429                "  }\n"
1430                "}",
1431                Style);
1432   verifyFormat("{\n"
1433                "  some_code();\n"
1434                "test_label:\n"
1435                "  some_other_code();\n"
1436                "}",
1437                Style);
1438   verifyFormat("{\n"
1439                "  some_code();\n"
1440                "test_label:;\n"
1441                "  int i = 0;\n"
1442                "}");
1443 }
1444 
TEST_F(FormatTest,MultiLineControlStatements)1445 TEST_F(FormatTest, MultiLineControlStatements) {
1446   FormatStyle Style = getLLVMStyle();
1447   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
1448   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
1449   Style.ColumnLimit = 20;
1450   // Short lines should keep opening brace on same line.
1451   EXPECT_EQ("if (foo) {\n"
1452             "  bar();\n"
1453             "}",
1454             format("if(foo){bar();}", Style));
1455   EXPECT_EQ("if (foo) {\n"
1456             "  bar();\n"
1457             "} else {\n"
1458             "  baz();\n"
1459             "}",
1460             format("if(foo){bar();}else{baz();}", Style));
1461   EXPECT_EQ("if (foo && bar) {\n"
1462             "  baz();\n"
1463             "}",
1464             format("if(foo&&bar){baz();}", Style));
1465   EXPECT_EQ("if (foo) {\n"
1466             "  bar();\n"
1467             "} else if (baz) {\n"
1468             "  quux();\n"
1469             "}",
1470             format("if(foo){bar();}else if(baz){quux();}", Style));
1471   EXPECT_EQ(
1472       "if (foo) {\n"
1473       "  bar();\n"
1474       "} else if (baz) {\n"
1475       "  quux();\n"
1476       "} else {\n"
1477       "  foobar();\n"
1478       "}",
1479       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
1480   EXPECT_EQ("for (;;) {\n"
1481             "  foo();\n"
1482             "}",
1483             format("for(;;){foo();}"));
1484   EXPECT_EQ("while (1) {\n"
1485             "  foo();\n"
1486             "}",
1487             format("while(1){foo();}", Style));
1488   EXPECT_EQ("switch (foo) {\n"
1489             "case bar:\n"
1490             "  return;\n"
1491             "}",
1492             format("switch(foo){case bar:return;}", Style));
1493   EXPECT_EQ("try {\n"
1494             "  foo();\n"
1495             "} catch (...) {\n"
1496             "  bar();\n"
1497             "}",
1498             format("try{foo();}catch(...){bar();}", Style));
1499   EXPECT_EQ("do {\n"
1500             "  foo();\n"
1501             "} while (bar &&\n"
1502             "         baz);",
1503             format("do{foo();}while(bar&&baz);", Style));
1504   // Long lines should put opening brace on new line.
1505   EXPECT_EQ("if (foo && bar &&\n"
1506             "    baz)\n"
1507             "{\n"
1508             "  quux();\n"
1509             "}",
1510             format("if(foo&&bar&&baz){quux();}", Style));
1511   EXPECT_EQ("if (foo && bar &&\n"
1512             "    baz)\n"
1513             "{\n"
1514             "  quux();\n"
1515             "}",
1516             format("if (foo && bar &&\n"
1517                    "    baz) {\n"
1518                    "  quux();\n"
1519                    "}",
1520                    Style));
1521   EXPECT_EQ("if (foo) {\n"
1522             "  bar();\n"
1523             "} else if (baz ||\n"
1524             "           quux)\n"
1525             "{\n"
1526             "  foobar();\n"
1527             "}",
1528             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
1529   EXPECT_EQ(
1530       "if (foo) {\n"
1531       "  bar();\n"
1532       "} else if (baz ||\n"
1533       "           quux)\n"
1534       "{\n"
1535       "  foobar();\n"
1536       "} else {\n"
1537       "  barbaz();\n"
1538       "}",
1539       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1540              Style));
1541   EXPECT_EQ("for (int i = 0;\n"
1542             "     i < 10; ++i)\n"
1543             "{\n"
1544             "  foo();\n"
1545             "}",
1546             format("for(int i=0;i<10;++i){foo();}", Style));
1547   EXPECT_EQ("while (foo || bar ||\n"
1548             "       baz)\n"
1549             "{\n"
1550             "  quux();\n"
1551             "}",
1552             format("while(foo||bar||baz){quux();}", Style));
1553   EXPECT_EQ("switch (\n"
1554             "    foo = barbaz)\n"
1555             "{\n"
1556             "case quux:\n"
1557             "  return;\n"
1558             "}",
1559             format("switch(foo=barbaz){case quux:return;}", Style));
1560   EXPECT_EQ("try {\n"
1561             "  foo();\n"
1562             "} catch (\n"
1563             "    Exception &bar)\n"
1564             "{\n"
1565             "  baz();\n"
1566             "}",
1567             format("try{foo();}catch(Exception&bar){baz();}", Style));
1568   Style.ColumnLimit =
1569       40; // to concentrate at brace wrapping, not line wrap due to column limit
1570   EXPECT_EQ("try {\n"
1571             "  foo();\n"
1572             "} catch (Exception &bar) {\n"
1573             "  baz();\n"
1574             "}",
1575             format("try{foo();}catch(Exception&bar){baz();}", Style));
1576   Style.ColumnLimit =
1577       20; // to concentrate at brace wrapping, not line wrap due to column limit
1578 
1579   Style.BraceWrapping.BeforeElse = true;
1580   EXPECT_EQ(
1581       "if (foo) {\n"
1582       "  bar();\n"
1583       "}\n"
1584       "else if (baz ||\n"
1585       "         quux)\n"
1586       "{\n"
1587       "  foobar();\n"
1588       "}\n"
1589       "else {\n"
1590       "  barbaz();\n"
1591       "}",
1592       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1593              Style));
1594 
1595   Style.BraceWrapping.BeforeCatch = true;
1596   EXPECT_EQ("try {\n"
1597             "  foo();\n"
1598             "}\n"
1599             "catch (...) {\n"
1600             "  baz();\n"
1601             "}",
1602             format("try{foo();}catch(...){baz();}", Style));
1603 }
1604 
1605 //===----------------------------------------------------------------------===//
1606 // Tests for classes, namespaces, etc.
1607 //===----------------------------------------------------------------------===//
1608 
TEST_F(FormatTest,DoesNotBreakSemiAfterClassDecl)1609 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1610   verifyFormat("class A {};");
1611 }
1612 
TEST_F(FormatTest,UnderstandsAccessSpecifiers)1613 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1614   verifyFormat("class A {\n"
1615                "public:\n"
1616                "public: // comment\n"
1617                "protected:\n"
1618                "private:\n"
1619                "  void f() {}\n"
1620                "};");
1621   verifyFormat("export class A {\n"
1622                "public:\n"
1623                "public: // comment\n"
1624                "protected:\n"
1625                "private:\n"
1626                "  void f() {}\n"
1627                "};");
1628   verifyGoogleFormat("class A {\n"
1629                      " public:\n"
1630                      " protected:\n"
1631                      " private:\n"
1632                      "  void f() {}\n"
1633                      "};");
1634   verifyGoogleFormat("export class A {\n"
1635                      " public:\n"
1636                      " protected:\n"
1637                      " private:\n"
1638                      "  void f() {}\n"
1639                      "};");
1640   verifyFormat("class A {\n"
1641                "public slots:\n"
1642                "  void f1() {}\n"
1643                "public Q_SLOTS:\n"
1644                "  void f2() {}\n"
1645                "protected slots:\n"
1646                "  void f3() {}\n"
1647                "protected Q_SLOTS:\n"
1648                "  void f4() {}\n"
1649                "private slots:\n"
1650                "  void f5() {}\n"
1651                "private Q_SLOTS:\n"
1652                "  void f6() {}\n"
1653                "signals:\n"
1654                "  void g1();\n"
1655                "Q_SIGNALS:\n"
1656                "  void g2();\n"
1657                "};");
1658 
1659   // Don't interpret 'signals' the wrong way.
1660   verifyFormat("signals.set();");
1661   verifyFormat("for (Signals signals : f()) {\n}");
1662   verifyFormat("{\n"
1663                "  signals.set(); // This needs indentation.\n"
1664                "}");
1665   verifyFormat("void f() {\n"
1666                "label:\n"
1667                "  signals.baz();\n"
1668                "}");
1669 }
1670 
TEST_F(FormatTest,SeparatesLogicalBlocks)1671 TEST_F(FormatTest, SeparatesLogicalBlocks) {
1672   EXPECT_EQ("class A {\n"
1673             "public:\n"
1674             "  void f();\n"
1675             "\n"
1676             "private:\n"
1677             "  void g() {}\n"
1678             "  // test\n"
1679             "protected:\n"
1680             "  int h;\n"
1681             "};",
1682             format("class A {\n"
1683                    "public:\n"
1684                    "void f();\n"
1685                    "private:\n"
1686                    "void g() {}\n"
1687                    "// test\n"
1688                    "protected:\n"
1689                    "int h;\n"
1690                    "};"));
1691   EXPECT_EQ("class A {\n"
1692             "protected:\n"
1693             "public:\n"
1694             "  void f();\n"
1695             "};",
1696             format("class A {\n"
1697                    "protected:\n"
1698                    "\n"
1699                    "public:\n"
1700                    "\n"
1701                    "  void f();\n"
1702                    "};"));
1703 
1704   // Even ensure proper spacing inside macros.
1705   EXPECT_EQ("#define B     \\\n"
1706             "  class A {   \\\n"
1707             "   protected: \\\n"
1708             "   public:    \\\n"
1709             "    void f(); \\\n"
1710             "  };",
1711             format("#define B     \\\n"
1712                    "  class A {   \\\n"
1713                    "   protected: \\\n"
1714                    "              \\\n"
1715                    "   public:    \\\n"
1716                    "              \\\n"
1717                    "    void f(); \\\n"
1718                    "  };",
1719                    getGoogleStyle()));
1720   // But don't remove empty lines after macros ending in access specifiers.
1721   EXPECT_EQ("#define A private:\n"
1722             "\n"
1723             "int i;",
1724             format("#define A         private:\n"
1725                    "\n"
1726                    "int              i;"));
1727 }
1728 
TEST_F(FormatTest,FormatsClasses)1729 TEST_F(FormatTest, FormatsClasses) {
1730   verifyFormat("class A : public B {};");
1731   verifyFormat("class A : public ::B {};");
1732 
1733   verifyFormat(
1734       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1735       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1736   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
1737                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1738                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1739   verifyFormat(
1740       "class A : public B, public C, public D, public E, public F {};");
1741   verifyFormat("class AAAAAAAAAAAA : public B,\n"
1742                "                     public C,\n"
1743                "                     public D,\n"
1744                "                     public E,\n"
1745                "                     public F,\n"
1746                "                     public G {};");
1747 
1748   verifyFormat("class\n"
1749                "    ReallyReallyLongClassName {\n"
1750                "  int i;\n"
1751                "};",
1752                getLLVMStyleWithColumns(32));
1753   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
1754                "                           aaaaaaaaaaaaaaaa> {};");
1755   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
1756                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
1757                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
1758   verifyFormat("template <class R, class C>\n"
1759                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
1760                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
1761   verifyFormat("class ::A::B {};");
1762 }
1763 
TEST_F(FormatTest,BreakInheritanceStyle)1764 TEST_F(FormatTest, BreakInheritanceStyle) {
1765   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
1766   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
1767       FormatStyle::BILS_BeforeComma;
1768   verifyFormat("class MyClass : public X {};",
1769                StyleWithInheritanceBreakBeforeComma);
1770   verifyFormat("class MyClass\n"
1771                "    : public X\n"
1772                "    , public Y {};",
1773                StyleWithInheritanceBreakBeforeComma);
1774   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
1775                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
1776                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1777                StyleWithInheritanceBreakBeforeComma);
1778   verifyFormat("struct aaaaaaaaaaaaa\n"
1779                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
1780                "          aaaaaaaaaaaaaaaa> {};",
1781                StyleWithInheritanceBreakBeforeComma);
1782 
1783   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
1784   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
1785       FormatStyle::BILS_AfterColon;
1786   verifyFormat("class MyClass : public X {};",
1787                StyleWithInheritanceBreakAfterColon);
1788   verifyFormat("class MyClass : public X, public Y {};",
1789                StyleWithInheritanceBreakAfterColon);
1790   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
1791                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1792                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1793                StyleWithInheritanceBreakAfterColon);
1794   verifyFormat("struct aaaaaaaaaaaaa :\n"
1795                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
1796                "        aaaaaaaaaaaaaaaa> {};",
1797                StyleWithInheritanceBreakAfterColon);
1798 }
1799 
TEST_F(FormatTest,FormatsVariableDeclarationsAfterStructOrClass)1800 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
1801   verifyFormat("class A {\n} a, b;");
1802   verifyFormat("struct A {\n} a, b;");
1803   verifyFormat("union A {\n} a;");
1804 }
1805 
TEST_F(FormatTest,FormatsEnum)1806 TEST_F(FormatTest, FormatsEnum) {
1807   verifyFormat("enum {\n"
1808                "  Zero,\n"
1809                "  One = 1,\n"
1810                "  Two = One + 1,\n"
1811                "  Three = (One + Two),\n"
1812                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1813                "  Five = (One, Two, Three, Four, 5)\n"
1814                "};");
1815   verifyGoogleFormat("enum {\n"
1816                      "  Zero,\n"
1817                      "  One = 1,\n"
1818                      "  Two = One + 1,\n"
1819                      "  Three = (One + Two),\n"
1820                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1821                      "  Five = (One, Two, Three, Four, 5)\n"
1822                      "};");
1823   verifyFormat("enum Enum {};");
1824   verifyFormat("enum {};");
1825   verifyFormat("enum X E {} d;");
1826   verifyFormat("enum __attribute__((...)) E {} d;");
1827   verifyFormat("enum __declspec__((...)) E {} d;");
1828   verifyFormat("enum {\n"
1829                "  Bar = Foo<int, int>::value\n"
1830                "};",
1831                getLLVMStyleWithColumns(30));
1832 
1833   verifyFormat("enum ShortEnum { A, B, C };");
1834   verifyGoogleFormat("enum ShortEnum { A, B, C };");
1835 
1836   EXPECT_EQ("enum KeepEmptyLines {\n"
1837             "  ONE,\n"
1838             "\n"
1839             "  TWO,\n"
1840             "\n"
1841             "  THREE\n"
1842             "}",
1843             format("enum KeepEmptyLines {\n"
1844                    "  ONE,\n"
1845                    "\n"
1846                    "  TWO,\n"
1847                    "\n"
1848                    "\n"
1849                    "  THREE\n"
1850                    "}"));
1851   verifyFormat("enum E { // comment\n"
1852                "  ONE,\n"
1853                "  TWO\n"
1854                "};\n"
1855                "int i;");
1856   // Not enums.
1857   verifyFormat("enum X f() {\n"
1858                "  a();\n"
1859                "  return 42;\n"
1860                "}");
1861   verifyFormat("enum X Type::f() {\n"
1862                "  a();\n"
1863                "  return 42;\n"
1864                "}");
1865   verifyFormat("enum ::X f() {\n"
1866                "  a();\n"
1867                "  return 42;\n"
1868                "}");
1869   verifyFormat("enum ns::X f() {\n"
1870                "  a();\n"
1871                "  return 42;\n"
1872                "}");
1873 }
1874 
TEST_F(FormatTest,FormatsEnumsWithErrors)1875 TEST_F(FormatTest, FormatsEnumsWithErrors) {
1876   verifyFormat("enum Type {\n"
1877                "  One = 0; // These semicolons should be commas.\n"
1878                "  Two = 1;\n"
1879                "};");
1880   verifyFormat("namespace n {\n"
1881                "enum Type {\n"
1882                "  One,\n"
1883                "  Two, // missing };\n"
1884                "  int i;\n"
1885                "}\n"
1886                "void g() {}");
1887 }
1888 
TEST_F(FormatTest,FormatsEnumStruct)1889 TEST_F(FormatTest, FormatsEnumStruct) {
1890   verifyFormat("enum struct {\n"
1891                "  Zero,\n"
1892                "  One = 1,\n"
1893                "  Two = One + 1,\n"
1894                "  Three = (One + Two),\n"
1895                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1896                "  Five = (One, Two, Three, Four, 5)\n"
1897                "};");
1898   verifyFormat("enum struct Enum {};");
1899   verifyFormat("enum struct {};");
1900   verifyFormat("enum struct X E {} d;");
1901   verifyFormat("enum struct __attribute__((...)) E {} d;");
1902   verifyFormat("enum struct __declspec__((...)) E {} d;");
1903   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
1904 }
1905 
TEST_F(FormatTest,FormatsEnumClass)1906 TEST_F(FormatTest, FormatsEnumClass) {
1907   verifyFormat("enum class {\n"
1908                "  Zero,\n"
1909                "  One = 1,\n"
1910                "  Two = One + 1,\n"
1911                "  Three = (One + Two),\n"
1912                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1913                "  Five = (One, Two, Three, Four, 5)\n"
1914                "};");
1915   verifyFormat("enum class Enum {};");
1916   verifyFormat("enum class {};");
1917   verifyFormat("enum class X E {} d;");
1918   verifyFormat("enum class __attribute__((...)) E {} d;");
1919   verifyFormat("enum class __declspec__((...)) E {} d;");
1920   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
1921 }
1922 
TEST_F(FormatTest,FormatsEnumTypes)1923 TEST_F(FormatTest, FormatsEnumTypes) {
1924   verifyFormat("enum X : int {\n"
1925                "  A, // Force multiple lines.\n"
1926                "  B\n"
1927                "};");
1928   verifyFormat("enum X : int { A, B };");
1929   verifyFormat("enum X : std::uint32_t { A, B };");
1930 }
1931 
TEST_F(FormatTest,FormatsTypedefEnum)1932 TEST_F(FormatTest, FormatsTypedefEnum) {
1933   FormatStyle Style = getLLVMStyle();
1934   Style.ColumnLimit = 40;
1935   verifyFormat("typedef enum {} EmptyEnum;");
1936   verifyFormat("typedef enum { A, B, C } ShortEnum;");
1937   verifyFormat("typedef enum {\n"
1938                "  ZERO = 0,\n"
1939                "  ONE = 1,\n"
1940                "  TWO = 2,\n"
1941                "  THREE = 3\n"
1942                "} LongEnum;",
1943                Style);
1944   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1945   Style.BraceWrapping.AfterEnum = true;
1946   verifyFormat("typedef enum {} EmptyEnum;");
1947   verifyFormat("typedef enum { A, B, C } ShortEnum;");
1948   verifyFormat("typedef enum\n"
1949                "{\n"
1950                "  ZERO = 0,\n"
1951                "  ONE = 1,\n"
1952                "  TWO = 2,\n"
1953                "  THREE = 3\n"
1954                "} LongEnum;",
1955                Style);
1956 }
1957 
TEST_F(FormatTest,FormatsNSEnums)1958 TEST_F(FormatTest, FormatsNSEnums) {
1959   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
1960   verifyGoogleFormat(
1961       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
1962   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
1963                      "  // Information about someDecentlyLongValue.\n"
1964                      "  someDecentlyLongValue,\n"
1965                      "  // Information about anotherDecentlyLongValue.\n"
1966                      "  anotherDecentlyLongValue,\n"
1967                      "  // Information about aThirdDecentlyLongValue.\n"
1968                      "  aThirdDecentlyLongValue\n"
1969                      "};");
1970   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
1971                      "  // Information about someDecentlyLongValue.\n"
1972                      "  someDecentlyLongValue,\n"
1973                      "  // Information about anotherDecentlyLongValue.\n"
1974                      "  anotherDecentlyLongValue,\n"
1975                      "  // Information about aThirdDecentlyLongValue.\n"
1976                      "  aThirdDecentlyLongValue\n"
1977                      "};");
1978   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
1979                      "  a = 1,\n"
1980                      "  b = 2,\n"
1981                      "  c = 3,\n"
1982                      "};");
1983   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
1984                      "  a = 1,\n"
1985                      "  b = 2,\n"
1986                      "  c = 3,\n"
1987                      "};");
1988   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
1989                      "  a = 1,\n"
1990                      "  b = 2,\n"
1991                      "  c = 3,\n"
1992                      "};");
1993   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
1994                      "  a = 1,\n"
1995                      "  b = 2,\n"
1996                      "  c = 3,\n"
1997                      "};");
1998 }
1999 
TEST_F(FormatTest,FormatsBitfields)2000 TEST_F(FormatTest, FormatsBitfields) {
2001   verifyFormat("struct Bitfields {\n"
2002                "  unsigned sClass : 8;\n"
2003                "  unsigned ValueKind : 2;\n"
2004                "};");
2005   verifyFormat("struct A {\n"
2006                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
2007                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
2008                "};");
2009   verifyFormat("struct MyStruct {\n"
2010                "  uchar data;\n"
2011                "  uchar : 8;\n"
2012                "  uchar : 8;\n"
2013                "  uchar other;\n"
2014                "};");
2015 }
2016 
TEST_F(FormatTest,FormatsNamespaces)2017 TEST_F(FormatTest, FormatsNamespaces) {
2018   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
2019   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
2020 
2021   verifyFormat("namespace some_namespace {\n"
2022                "class A {};\n"
2023                "void f() { f(); }\n"
2024                "}",
2025                LLVMWithNoNamespaceFix);
2026   verifyFormat("namespace N::inline D {\n"
2027                "class A {};\n"
2028                "void f() { f(); }\n"
2029                "}",
2030                LLVMWithNoNamespaceFix);
2031   verifyFormat("namespace N::inline D::E {\n"
2032                "class A {};\n"
2033                "void f() { f(); }\n"
2034                "}",
2035                LLVMWithNoNamespaceFix);
2036   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
2037                "class A {};\n"
2038                "void f() { f(); }\n"
2039                "}",
2040                LLVMWithNoNamespaceFix);
2041   verifyFormat("/* something */ namespace some_namespace {\n"
2042                "class A {};\n"
2043                "void f() { f(); }\n"
2044                "}",
2045                LLVMWithNoNamespaceFix);
2046   verifyFormat("namespace {\n"
2047                "class A {};\n"
2048                "void f() { f(); }\n"
2049                "}",
2050                LLVMWithNoNamespaceFix);
2051   verifyFormat("/* something */ namespace {\n"
2052                "class A {};\n"
2053                "void f() { f(); }\n"
2054                "}",
2055                LLVMWithNoNamespaceFix);
2056   verifyFormat("inline namespace X {\n"
2057                "class A {};\n"
2058                "void f() { f(); }\n"
2059                "}",
2060                LLVMWithNoNamespaceFix);
2061   verifyFormat("/* something */ inline namespace X {\n"
2062                "class A {};\n"
2063                "void f() { f(); }\n"
2064                "}",
2065                LLVMWithNoNamespaceFix);
2066   verifyFormat("export namespace X {\n"
2067                "class A {};\n"
2068                "void f() { f(); }\n"
2069                "}",
2070                LLVMWithNoNamespaceFix);
2071   verifyFormat("using namespace some_namespace;\n"
2072                "class A {};\n"
2073                "void f() { f(); }",
2074                LLVMWithNoNamespaceFix);
2075 
2076   // This code is more common than we thought; if we
2077   // layout this correctly the semicolon will go into
2078   // its own line, which is undesirable.
2079   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
2080   verifyFormat("namespace {\n"
2081                "class A {};\n"
2082                "};",
2083                LLVMWithNoNamespaceFix);
2084 
2085   verifyFormat("namespace {\n"
2086                "int SomeVariable = 0; // comment\n"
2087                "} // namespace",
2088                LLVMWithNoNamespaceFix);
2089   EXPECT_EQ("#ifndef HEADER_GUARD\n"
2090             "#define HEADER_GUARD\n"
2091             "namespace my_namespace {\n"
2092             "int i;\n"
2093             "} // my_namespace\n"
2094             "#endif // HEADER_GUARD",
2095             format("#ifndef HEADER_GUARD\n"
2096                    " #define HEADER_GUARD\n"
2097                    "   namespace my_namespace {\n"
2098                    "int i;\n"
2099                    "}    // my_namespace\n"
2100                    "#endif    // HEADER_GUARD",
2101                    LLVMWithNoNamespaceFix));
2102 
2103   EXPECT_EQ("namespace A::B {\n"
2104             "class C {};\n"
2105             "}",
2106             format("namespace A::B {\n"
2107                    "class C {};\n"
2108                    "}",
2109                    LLVMWithNoNamespaceFix));
2110 
2111   FormatStyle Style = getLLVMStyle();
2112   Style.NamespaceIndentation = FormatStyle::NI_All;
2113   EXPECT_EQ("namespace out {\n"
2114             "  int i;\n"
2115             "  namespace in {\n"
2116             "    int i;\n"
2117             "  } // namespace in\n"
2118             "} // namespace out",
2119             format("namespace out {\n"
2120                    "int i;\n"
2121                    "namespace in {\n"
2122                    "int i;\n"
2123                    "} // namespace in\n"
2124                    "} // namespace out",
2125                    Style));
2126 
2127   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2128   EXPECT_EQ("namespace out {\n"
2129             "int i;\n"
2130             "namespace in {\n"
2131             "  int i;\n"
2132             "} // namespace in\n"
2133             "} // namespace out",
2134             format("namespace out {\n"
2135                    "int i;\n"
2136                    "namespace in {\n"
2137                    "int i;\n"
2138                    "} // namespace in\n"
2139                    "} // namespace out",
2140                    Style));
2141 }
2142 
TEST_F(FormatTest,NamespaceMacros)2143 TEST_F(FormatTest, NamespaceMacros) {
2144   FormatStyle Style = getLLVMStyle();
2145   Style.NamespaceMacros.push_back("TESTSUITE");
2146 
2147   verifyFormat("TESTSUITE(A) {\n"
2148                "int foo();\n"
2149                "} // TESTSUITE(A)",
2150                Style);
2151 
2152   verifyFormat("TESTSUITE(A, B) {\n"
2153                "int foo();\n"
2154                "} // TESTSUITE(A)",
2155                Style);
2156 
2157   // Properly indent according to NamespaceIndentation style
2158   Style.NamespaceIndentation = FormatStyle::NI_All;
2159   verifyFormat("TESTSUITE(A) {\n"
2160                "  int foo();\n"
2161                "} // TESTSUITE(A)",
2162                Style);
2163   verifyFormat("TESTSUITE(A) {\n"
2164                "  namespace B {\n"
2165                "    int foo();\n"
2166                "  } // namespace B\n"
2167                "} // TESTSUITE(A)",
2168                Style);
2169   verifyFormat("namespace A {\n"
2170                "  TESTSUITE(B) {\n"
2171                "    int foo();\n"
2172                "  } // TESTSUITE(B)\n"
2173                "} // namespace A",
2174                Style);
2175 
2176   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2177   verifyFormat("TESTSUITE(A) {\n"
2178                "TESTSUITE(B) {\n"
2179                "  int foo();\n"
2180                "} // TESTSUITE(B)\n"
2181                "} // TESTSUITE(A)",
2182                Style);
2183   verifyFormat("TESTSUITE(A) {\n"
2184                "namespace B {\n"
2185                "  int foo();\n"
2186                "} // namespace B\n"
2187                "} // TESTSUITE(A)",
2188                Style);
2189   verifyFormat("namespace A {\n"
2190                "TESTSUITE(B) {\n"
2191                "  int foo();\n"
2192                "} // TESTSUITE(B)\n"
2193                "} // namespace A",
2194                Style);
2195 
2196   // Properly merge namespace-macros blocks in CompactNamespaces mode
2197   Style.NamespaceIndentation = FormatStyle::NI_None;
2198   Style.CompactNamespaces = true;
2199   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
2200                "}} // TESTSUITE(A::B)",
2201                Style);
2202 
2203   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2204             "}} // TESTSUITE(out::in)",
2205             format("TESTSUITE(out) {\n"
2206                    "TESTSUITE(in) {\n"
2207                    "} // TESTSUITE(in)\n"
2208                    "} // TESTSUITE(out)",
2209                    Style));
2210 
2211   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2212             "}} // TESTSUITE(out::in)",
2213             format("TESTSUITE(out) {\n"
2214                    "TESTSUITE(in) {\n"
2215                    "} // TESTSUITE(in)\n"
2216                    "} // TESTSUITE(out)",
2217                    Style));
2218 
2219   // Do not merge different namespaces/macros
2220   EXPECT_EQ("namespace out {\n"
2221             "TESTSUITE(in) {\n"
2222             "} // TESTSUITE(in)\n"
2223             "} // namespace out",
2224             format("namespace out {\n"
2225                    "TESTSUITE(in) {\n"
2226                    "} // TESTSUITE(in)\n"
2227                    "} // namespace out",
2228                    Style));
2229   EXPECT_EQ("TESTSUITE(out) {\n"
2230             "namespace in {\n"
2231             "} // namespace in\n"
2232             "} // TESTSUITE(out)",
2233             format("TESTSUITE(out) {\n"
2234                    "namespace in {\n"
2235                    "} // namespace in\n"
2236                    "} // TESTSUITE(out)",
2237                    Style));
2238   Style.NamespaceMacros.push_back("FOOBAR");
2239   EXPECT_EQ("TESTSUITE(out) {\n"
2240             "FOOBAR(in) {\n"
2241             "} // FOOBAR(in)\n"
2242             "} // TESTSUITE(out)",
2243             format("TESTSUITE(out) {\n"
2244                    "FOOBAR(in) {\n"
2245                    "} // FOOBAR(in)\n"
2246                    "} // TESTSUITE(out)",
2247                    Style));
2248 }
2249 
TEST_F(FormatTest,FormatsCompactNamespaces)2250 TEST_F(FormatTest, FormatsCompactNamespaces) {
2251   FormatStyle Style = getLLVMStyle();
2252   Style.CompactNamespaces = true;
2253   Style.NamespaceMacros.push_back("TESTSUITE");
2254 
2255   verifyFormat("namespace A { namespace B {\n"
2256                "}} // namespace A::B",
2257                Style);
2258 
2259   EXPECT_EQ("namespace out { namespace in {\n"
2260             "}} // namespace out::in",
2261             format("namespace out {\n"
2262                    "namespace in {\n"
2263                    "} // namespace in\n"
2264                    "} // namespace out",
2265                    Style));
2266 
2267   // Only namespaces which have both consecutive opening and end get compacted
2268   EXPECT_EQ("namespace out {\n"
2269             "namespace in1 {\n"
2270             "} // namespace in1\n"
2271             "namespace in2 {\n"
2272             "} // namespace in2\n"
2273             "} // namespace out",
2274             format("namespace out {\n"
2275                    "namespace in1 {\n"
2276                    "} // namespace in1\n"
2277                    "namespace in2 {\n"
2278                    "} // namespace in2\n"
2279                    "} // namespace out",
2280                    Style));
2281 
2282   EXPECT_EQ("namespace out {\n"
2283             "int i;\n"
2284             "namespace in {\n"
2285             "int j;\n"
2286             "} // namespace in\n"
2287             "int k;\n"
2288             "} // namespace out",
2289             format("namespace out { int i;\n"
2290                    "namespace in { int j; } // namespace in\n"
2291                    "int k; } // namespace out",
2292                    Style));
2293 
2294   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
2295             "}}} // namespace A::B::C\n",
2296             format("namespace A { namespace B {\n"
2297                    "namespace C {\n"
2298                    "}} // namespace B::C\n"
2299                    "} // namespace A\n",
2300                    Style));
2301 
2302   Style.ColumnLimit = 40;
2303   EXPECT_EQ("namespace aaaaaaaaaa {\n"
2304             "namespace bbbbbbbbbb {\n"
2305             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
2306             format("namespace aaaaaaaaaa {\n"
2307                    "namespace bbbbbbbbbb {\n"
2308                    "} // namespace bbbbbbbbbb\n"
2309                    "} // namespace aaaaaaaaaa",
2310                    Style));
2311 
2312   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
2313             "namespace cccccc {\n"
2314             "}}} // namespace aaaaaa::bbbbbb::cccccc",
2315             format("namespace aaaaaa {\n"
2316                    "namespace bbbbbb {\n"
2317                    "namespace cccccc {\n"
2318                    "} // namespace cccccc\n"
2319                    "} // namespace bbbbbb\n"
2320                    "} // namespace aaaaaa",
2321                    Style));
2322   Style.ColumnLimit = 80;
2323 
2324   // Extra semicolon after 'inner' closing brace prevents merging
2325   EXPECT_EQ("namespace out { namespace in {\n"
2326             "}; } // namespace out::in",
2327             format("namespace out {\n"
2328                    "namespace in {\n"
2329                    "}; // namespace in\n"
2330                    "} // namespace out",
2331                    Style));
2332 
2333   // Extra semicolon after 'outer' closing brace is conserved
2334   EXPECT_EQ("namespace out { namespace in {\n"
2335             "}}; // namespace out::in",
2336             format("namespace out {\n"
2337                    "namespace in {\n"
2338                    "} // namespace in\n"
2339                    "}; // namespace out",
2340                    Style));
2341 
2342   Style.NamespaceIndentation = FormatStyle::NI_All;
2343   EXPECT_EQ("namespace out { namespace in {\n"
2344             "  int i;\n"
2345             "}} // namespace out::in",
2346             format("namespace out {\n"
2347                    "namespace in {\n"
2348                    "int i;\n"
2349                    "} // namespace in\n"
2350                    "} // namespace out",
2351                    Style));
2352   EXPECT_EQ("namespace out { namespace mid {\n"
2353             "  namespace in {\n"
2354             "    int j;\n"
2355             "  } // namespace in\n"
2356             "  int k;\n"
2357             "}} // namespace out::mid",
2358             format("namespace out { namespace mid {\n"
2359                    "namespace in { int j; } // namespace in\n"
2360                    "int k; }} // namespace out::mid",
2361                    Style));
2362 
2363   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2364   EXPECT_EQ("namespace out { namespace in {\n"
2365             "  int i;\n"
2366             "}} // namespace out::in",
2367             format("namespace out {\n"
2368                    "namespace in {\n"
2369                    "int i;\n"
2370                    "} // namespace in\n"
2371                    "} // namespace out",
2372                    Style));
2373   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
2374             "  int i;\n"
2375             "}}} // namespace out::mid::in",
2376             format("namespace out {\n"
2377                    "namespace mid {\n"
2378                    "namespace in {\n"
2379                    "int i;\n"
2380                    "} // namespace in\n"
2381                    "} // namespace mid\n"
2382                    "} // namespace out",
2383                    Style));
2384 }
2385 
TEST_F(FormatTest,FormatsExternC)2386 TEST_F(FormatTest, FormatsExternC) {
2387   verifyFormat("extern \"C\" {\nint a;");
2388   verifyFormat("extern \"C\" {}");
2389   verifyFormat("extern \"C\" {\n"
2390                "int foo();\n"
2391                "}");
2392   verifyFormat("extern \"C\" int foo() {}");
2393   verifyFormat("extern \"C\" int foo();");
2394   verifyFormat("extern \"C\" int foo() {\n"
2395                "  int i = 42;\n"
2396                "  return i;\n"
2397                "}");
2398 
2399   FormatStyle Style = getLLVMStyle();
2400   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2401   Style.BraceWrapping.AfterFunction = true;
2402   verifyFormat("extern \"C\" int foo() {}", Style);
2403   verifyFormat("extern \"C\" int foo();", Style);
2404   verifyFormat("extern \"C\" int foo()\n"
2405                "{\n"
2406                "  int i = 42;\n"
2407                "  return i;\n"
2408                "}",
2409                Style);
2410 
2411   Style.BraceWrapping.AfterExternBlock = true;
2412   Style.BraceWrapping.SplitEmptyRecord = false;
2413   verifyFormat("extern \"C\"\n"
2414                "{}",
2415                Style);
2416   verifyFormat("extern \"C\"\n"
2417                "{\n"
2418                "  int foo();\n"
2419                "}",
2420                Style);
2421 }
2422 
TEST_F(FormatTest,FormatsInlineASM)2423 TEST_F(FormatTest, FormatsInlineASM) {
2424   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
2425   verifyFormat("asm(\"nop\" ::: \"memory\");");
2426   verifyFormat(
2427       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
2428       "    \"cpuid\\n\\t\"\n"
2429       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
2430       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
2431       "    : \"a\"(value));");
2432   EXPECT_EQ(
2433       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
2434       "  __asm {\n"
2435       "        mov     edx,[that] // vtable in edx\n"
2436       "        mov     eax,methodIndex\n"
2437       "        call    [edx][eax*4] // stdcall\n"
2438       "  }\n"
2439       "}",
2440       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
2441              "    __asm {\n"
2442              "        mov     edx,[that] // vtable in edx\n"
2443              "        mov     eax,methodIndex\n"
2444              "        call    [edx][eax*4] // stdcall\n"
2445              "    }\n"
2446              "}"));
2447   EXPECT_EQ("_asm {\n"
2448             "  xor eax, eax;\n"
2449             "  cpuid;\n"
2450             "}",
2451             format("_asm {\n"
2452                    "  xor eax, eax;\n"
2453                    "  cpuid;\n"
2454                    "}"));
2455   verifyFormat("void function() {\n"
2456                "  // comment\n"
2457                "  asm(\"\");\n"
2458                "}");
2459   EXPECT_EQ("__asm {\n"
2460             "}\n"
2461             "int i;",
2462             format("__asm   {\n"
2463                    "}\n"
2464                    "int   i;"));
2465 }
2466 
TEST_F(FormatTest,FormatTryCatch)2467 TEST_F(FormatTest, FormatTryCatch) {
2468   verifyFormat("try {\n"
2469                "  throw a * b;\n"
2470                "} catch (int a) {\n"
2471                "  // Do nothing.\n"
2472                "} catch (...) {\n"
2473                "  exit(42);\n"
2474                "}");
2475 
2476   // Function-level try statements.
2477   verifyFormat("int f() try { return 4; } catch (...) {\n"
2478                "  return 5;\n"
2479                "}");
2480   verifyFormat("class A {\n"
2481                "  int a;\n"
2482                "  A() try : a(0) {\n"
2483                "  } catch (...) {\n"
2484                "    throw;\n"
2485                "  }\n"
2486                "};\n");
2487 
2488   // Incomplete try-catch blocks.
2489   verifyIncompleteFormat("try {} catch (");
2490 }
2491 
TEST_F(FormatTest,FormatSEHTryCatch)2492 TEST_F(FormatTest, FormatSEHTryCatch) {
2493   verifyFormat("__try {\n"
2494                "  int a = b * c;\n"
2495                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
2496                "  // Do nothing.\n"
2497                "}");
2498 
2499   verifyFormat("__try {\n"
2500                "  int a = b * c;\n"
2501                "} __finally {\n"
2502                "  // Do nothing.\n"
2503                "}");
2504 
2505   verifyFormat("DEBUG({\n"
2506                "  __try {\n"
2507                "  } __finally {\n"
2508                "  }\n"
2509                "});\n");
2510 }
2511 
TEST_F(FormatTest,IncompleteTryCatchBlocks)2512 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
2513   verifyFormat("try {\n"
2514                "  f();\n"
2515                "} catch {\n"
2516                "  g();\n"
2517                "}");
2518   verifyFormat("try {\n"
2519                "  f();\n"
2520                "} catch (A a) MACRO(x) {\n"
2521                "  g();\n"
2522                "} catch (B b) MACRO(x) {\n"
2523                "  g();\n"
2524                "}");
2525 }
2526 
TEST_F(FormatTest,FormatTryCatchBraceStyles)2527 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
2528   FormatStyle Style = getLLVMStyle();
2529   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
2530                           FormatStyle::BS_WebKit}) {
2531     Style.BreakBeforeBraces = BraceStyle;
2532     verifyFormat("try {\n"
2533                  "  // something\n"
2534                  "} catch (...) {\n"
2535                  "  // something\n"
2536                  "}",
2537                  Style);
2538   }
2539   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
2540   verifyFormat("try {\n"
2541                "  // something\n"
2542                "}\n"
2543                "catch (...) {\n"
2544                "  // something\n"
2545                "}",
2546                Style);
2547   verifyFormat("__try {\n"
2548                "  // something\n"
2549                "}\n"
2550                "__finally {\n"
2551                "  // something\n"
2552                "}",
2553                Style);
2554   verifyFormat("@try {\n"
2555                "  // something\n"
2556                "}\n"
2557                "@finally {\n"
2558                "  // something\n"
2559                "}",
2560                Style);
2561   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
2562   verifyFormat("try\n"
2563                "{\n"
2564                "  // something\n"
2565                "}\n"
2566                "catch (...)\n"
2567                "{\n"
2568                "  // something\n"
2569                "}",
2570                Style);
2571   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
2572   verifyFormat("try\n"
2573                "  {\n"
2574                "  // something white\n"
2575                "  }\n"
2576                "catch (...)\n"
2577                "  {\n"
2578                "  // something white\n"
2579                "  }",
2580                Style);
2581   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2582   verifyFormat("try\n"
2583                "  {\n"
2584                "    // something\n"
2585                "  }\n"
2586                "catch (...)\n"
2587                "  {\n"
2588                "    // something\n"
2589                "  }",
2590                Style);
2591   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2592   Style.BraceWrapping.BeforeCatch = true;
2593   verifyFormat("try {\n"
2594                "  // something\n"
2595                "}\n"
2596                "catch (...) {\n"
2597                "  // something\n"
2598                "}",
2599                Style);
2600 }
2601 
TEST_F(FormatTest,StaticInitializers)2602 TEST_F(FormatTest, StaticInitializers) {
2603   verifyFormat("static SomeClass SC = {1, 'a'};");
2604 
2605   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
2606                "    100000000, "
2607                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
2608 
2609   // Here, everything other than the "}" would fit on a line.
2610   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
2611                "    10000000000000000000000000};");
2612   EXPECT_EQ("S s = {a,\n"
2613             "\n"
2614             "       b};",
2615             format("S s = {\n"
2616                    "  a,\n"
2617                    "\n"
2618                    "  b\n"
2619                    "};"));
2620 
2621   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
2622   // line. However, the formatting looks a bit off and this probably doesn't
2623   // happen often in practice.
2624   verifyFormat("static int Variable[1] = {\n"
2625                "    {1000000000000000000000000000000000000}};",
2626                getLLVMStyleWithColumns(40));
2627 }
2628 
TEST_F(FormatTest,DesignatedInitializers)2629 TEST_F(FormatTest, DesignatedInitializers) {
2630   verifyFormat("const struct A a = {.a = 1, .b = 2};");
2631   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
2632                "                    .bbbbbbbbbb = 2,\n"
2633                "                    .cccccccccc = 3,\n"
2634                "                    .dddddddddd = 4,\n"
2635                "                    .eeeeeeeeee = 5};");
2636   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2637                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
2638                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
2639                "    .ccccccccccccccccccccccccccc = 3,\n"
2640                "    .ddddddddddddddddddddddddddd = 4,\n"
2641                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
2642 
2643   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
2644 
2645   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
2646   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
2647                "                    [2] = bbbbbbbbbb,\n"
2648                "                    [3] = cccccccccc,\n"
2649                "                    [4] = dddddddddd,\n"
2650                "                    [5] = eeeeeeeeee};");
2651   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2652                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2653                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
2654                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
2655                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
2656                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
2657 }
2658 
TEST_F(FormatTest,NestedStaticInitializers)2659 TEST_F(FormatTest, NestedStaticInitializers) {
2660   verifyFormat("static A x = {{{}}};\n");
2661   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
2662                "               {init1, init2, init3, init4}}};",
2663                getLLVMStyleWithColumns(50));
2664 
2665   verifyFormat("somes Status::global_reps[3] = {\n"
2666                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2667                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2668                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
2669                getLLVMStyleWithColumns(60));
2670   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
2671                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2672                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2673                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
2674   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
2675                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
2676                "rect.fTop}};");
2677 
2678   verifyFormat(
2679       "SomeArrayOfSomeType a = {\n"
2680       "    {{1, 2, 3},\n"
2681       "     {1, 2, 3},\n"
2682       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
2683       "      333333333333333333333333333333},\n"
2684       "     {1, 2, 3},\n"
2685       "     {1, 2, 3}}};");
2686   verifyFormat(
2687       "SomeArrayOfSomeType a = {\n"
2688       "    {{1, 2, 3}},\n"
2689       "    {{1, 2, 3}},\n"
2690       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
2691       "      333333333333333333333333333333}},\n"
2692       "    {{1, 2, 3}},\n"
2693       "    {{1, 2, 3}}};");
2694 
2695   verifyFormat("struct {\n"
2696                "  unsigned bit;\n"
2697                "  const char *const name;\n"
2698                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
2699                "                 {kOsWin, \"Windows\"},\n"
2700                "                 {kOsLinux, \"Linux\"},\n"
2701                "                 {kOsCrOS, \"Chrome OS\"}};");
2702   verifyFormat("struct {\n"
2703                "  unsigned bit;\n"
2704                "  const char *const name;\n"
2705                "} kBitsToOs[] = {\n"
2706                "    {kOsMac, \"Mac\"},\n"
2707                "    {kOsWin, \"Windows\"},\n"
2708                "    {kOsLinux, \"Linux\"},\n"
2709                "    {kOsCrOS, \"Chrome OS\"},\n"
2710                "};");
2711 }
2712 
TEST_F(FormatTest,FormatsSmallMacroDefinitionsInSingleLine)2713 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
2714   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
2715                "                      \\\n"
2716                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
2717 }
2718 
TEST_F(FormatTest,DoesNotBreakPureVirtualFunctionDefinition)2719 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
2720   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
2721                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
2722 
2723   // Do break defaulted and deleted functions.
2724   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
2725                "    default;",
2726                getLLVMStyleWithColumns(40));
2727   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
2728                "    delete;",
2729                getLLVMStyleWithColumns(40));
2730 }
2731 
TEST_F(FormatTest,BreaksStringLiteralsOnlyInDefine)2732 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
2733   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
2734                getLLVMStyleWithColumns(40));
2735   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
2736                getLLVMStyleWithColumns(40));
2737   EXPECT_EQ("#define Q                              \\\n"
2738             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
2739             "  \"aaaaaaaa.cpp\"",
2740             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
2741                    getLLVMStyleWithColumns(40)));
2742 }
2743 
TEST_F(FormatTest,UnderstandsLinePPDirective)2744 TEST_F(FormatTest, UnderstandsLinePPDirective) {
2745   EXPECT_EQ("# 123 \"A string literal\"",
2746             format("   #     123    \"A string literal\""));
2747 }
2748 
TEST_F(FormatTest,LayoutUnknownPPDirective)2749 TEST_F(FormatTest, LayoutUnknownPPDirective) {
2750   EXPECT_EQ("#;", format("#;"));
2751   verifyFormat("#\n;\n;\n;");
2752 }
2753 
TEST_F(FormatTest,UnescapedEndOfLineEndsPPDirective)2754 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
2755   EXPECT_EQ("#line 42 \"test\"\n",
2756             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
2757   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
2758                                     getLLVMStyleWithColumns(12)));
2759 }
2760 
TEST_F(FormatTest,EndOfFileEndsPPDirective)2761 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
2762   EXPECT_EQ("#line 42 \"test\"",
2763             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
2764   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
2765 }
2766 
TEST_F(FormatTest,DoesntRemoveUnknownTokens)2767 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
2768   verifyFormat("#define A \\x20");
2769   verifyFormat("#define A \\ x20");
2770   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
2771   verifyFormat("#define A ''");
2772   verifyFormat("#define A ''qqq");
2773   verifyFormat("#define A `qqq");
2774   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
2775   EXPECT_EQ("const char *c = STRINGIFY(\n"
2776             "\\na : b);",
2777             format("const char * c = STRINGIFY(\n"
2778                    "\\na : b);"));
2779 
2780   verifyFormat("a\r\\");
2781   verifyFormat("a\v\\");
2782   verifyFormat("a\f\\");
2783 }
2784 
TEST_F(FormatTest,IndentsPPDirectiveInReducedSpace)2785 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
2786   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
2787   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
2788   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
2789   // FIXME: We never break before the macro name.
2790   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
2791 
2792   verifyFormat("#define A A\n#define A A");
2793   verifyFormat("#define A(X) A\n#define A A");
2794 
2795   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
2796   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
2797 }
2798 
TEST_F(FormatTest,HandlePreprocessorDirectiveContext)2799 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
2800   EXPECT_EQ("// somecomment\n"
2801             "#include \"a.h\"\n"
2802             "#define A(  \\\n"
2803             "    A, B)\n"
2804             "#include \"b.h\"\n"
2805             "// somecomment\n",
2806             format("  // somecomment\n"
2807                    "  #include \"a.h\"\n"
2808                    "#define A(A,\\\n"
2809                    "    B)\n"
2810                    "    #include \"b.h\"\n"
2811                    " // somecomment\n",
2812                    getLLVMStyleWithColumns(13)));
2813 }
2814 
TEST_F(FormatTest,LayoutSingleHash)2815 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
2816 
TEST_F(FormatTest,LayoutCodeInMacroDefinitions)2817 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
2818   EXPECT_EQ("#define A    \\\n"
2819             "  c;         \\\n"
2820             "  e;\n"
2821             "f;",
2822             format("#define A c; e;\n"
2823                    "f;",
2824                    getLLVMStyleWithColumns(14)));
2825 }
2826 
TEST_F(FormatTest,LayoutRemainingTokens)2827 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
2828 
TEST_F(FormatTest,MacroDefinitionInsideStatement)2829 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
2830   EXPECT_EQ("int x,\n"
2831             "#define A\n"
2832             "    y;",
2833             format("int x,\n#define A\ny;"));
2834 }
2835 
TEST_F(FormatTest,HashInMacroDefinition)2836 TEST_F(FormatTest, HashInMacroDefinition) {
2837   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
2838   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
2839   verifyFormat("#define A  \\\n"
2840                "  {        \\\n"
2841                "    f(#c); \\\n"
2842                "  }",
2843                getLLVMStyleWithColumns(11));
2844 
2845   verifyFormat("#define A(X)         \\\n"
2846                "  void function##X()",
2847                getLLVMStyleWithColumns(22));
2848 
2849   verifyFormat("#define A(a, b, c)   \\\n"
2850                "  void a##b##c()",
2851                getLLVMStyleWithColumns(22));
2852 
2853   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
2854 }
2855 
TEST_F(FormatTest,RespectWhitespaceInMacroDefinitions)2856 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
2857   EXPECT_EQ("#define A (x)", format("#define A (x)"));
2858   EXPECT_EQ("#define A(x)", format("#define A(x)"));
2859 
2860   FormatStyle Style = getLLVMStyle();
2861   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
2862   verifyFormat("#define true ((foo)1)", Style);
2863   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
2864   verifyFormat("#define false((foo)0)", Style);
2865 }
2866 
TEST_F(FormatTest,EmptyLinesInMacroDefinitions)2867 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
2868   EXPECT_EQ("#define A b;", format("#define A \\\n"
2869                                    "          \\\n"
2870                                    "  b;",
2871                                    getLLVMStyleWithColumns(25)));
2872   EXPECT_EQ("#define A \\\n"
2873             "          \\\n"
2874             "  a;      \\\n"
2875             "  b;",
2876             format("#define A \\\n"
2877                    "          \\\n"
2878                    "  a;      \\\n"
2879                    "  b;",
2880                    getLLVMStyleWithColumns(11)));
2881   EXPECT_EQ("#define A \\\n"
2882             "  a;      \\\n"
2883             "          \\\n"
2884             "  b;",
2885             format("#define A \\\n"
2886                    "  a;      \\\n"
2887                    "          \\\n"
2888                    "  b;",
2889                    getLLVMStyleWithColumns(11)));
2890 }
2891 
TEST_F(FormatTest,MacroDefinitionsWithIncompleteCode)2892 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
2893   verifyIncompleteFormat("#define A :");
2894   verifyFormat("#define SOMECASES  \\\n"
2895                "  case 1:          \\\n"
2896                "  case 2\n",
2897                getLLVMStyleWithColumns(20));
2898   verifyFormat("#define MACRO(a) \\\n"
2899                "  if (a)         \\\n"
2900                "    f();         \\\n"
2901                "  else           \\\n"
2902                "    g()",
2903                getLLVMStyleWithColumns(18));
2904   verifyFormat("#define A template <typename T>");
2905   verifyIncompleteFormat("#define STR(x) #x\n"
2906                          "f(STR(this_is_a_string_literal{));");
2907   verifyFormat("#pragma omp threadprivate( \\\n"
2908                "    y)), // expected-warning",
2909                getLLVMStyleWithColumns(28));
2910   verifyFormat("#d, = };");
2911   verifyFormat("#if \"a");
2912   verifyIncompleteFormat("({\n"
2913                          "#define b     \\\n"
2914                          "  }           \\\n"
2915                          "  a\n"
2916                          "a",
2917                          getLLVMStyleWithColumns(15));
2918   verifyFormat("#define A     \\\n"
2919                "  {           \\\n"
2920                "    {\n"
2921                "#define B     \\\n"
2922                "  }           \\\n"
2923                "  }",
2924                getLLVMStyleWithColumns(15));
2925   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
2926   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
2927   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
2928   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
2929 }
2930 
TEST_F(FormatTest,MacrosWithoutTrailingSemicolon)2931 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
2932   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
2933   EXPECT_EQ("class A : public QObject {\n"
2934             "  Q_OBJECT\n"
2935             "\n"
2936             "  A() {}\n"
2937             "};",
2938             format("class A  :  public QObject {\n"
2939                    "     Q_OBJECT\n"
2940                    "\n"
2941                    "  A() {\n}\n"
2942                    "}  ;"));
2943   EXPECT_EQ("MACRO\n"
2944             "/*static*/ int i;",
2945             format("MACRO\n"
2946                    " /*static*/ int   i;"));
2947   EXPECT_EQ("SOME_MACRO\n"
2948             "namespace {\n"
2949             "void f();\n"
2950             "} // namespace",
2951             format("SOME_MACRO\n"
2952                    "  namespace    {\n"
2953                    "void   f(  );\n"
2954                    "} // namespace"));
2955   // Only if the identifier contains at least 5 characters.
2956   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
2957   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
2958   // Only if everything is upper case.
2959   EXPECT_EQ("class A : public QObject {\n"
2960             "  Q_Object A() {}\n"
2961             "};",
2962             format("class A  :  public QObject {\n"
2963                    "     Q_Object\n"
2964                    "  A() {\n}\n"
2965                    "}  ;"));
2966 
2967   // Only if the next line can actually start an unwrapped line.
2968   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
2969             format("SOME_WEIRD_LOG_MACRO\n"
2970                    "<< SomeThing;"));
2971 
2972   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
2973                "(n, buffers))\n",
2974                getChromiumStyle(FormatStyle::LK_Cpp));
2975 
2976   // See PR41483
2977   EXPECT_EQ("/**/ FOO(a)\n"
2978             "FOO(b)",
2979             format("/**/ FOO(a)\n"
2980                    "FOO(b)"));
2981 }
2982 
TEST_F(FormatTest,MacroCallsWithoutTrailingSemicolon)2983 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
2984   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
2985             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
2986             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
2987             "class X {};\n"
2988             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
2989             "int *createScopDetectionPass() { return 0; }",
2990             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
2991                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
2992                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
2993                    "  class X {};\n"
2994                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
2995                    "  int *createScopDetectionPass() { return 0; }"));
2996   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
2997   // braces, so that inner block is indented one level more.
2998   EXPECT_EQ("int q() {\n"
2999             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3000             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3001             "  IPC_END_MESSAGE_MAP()\n"
3002             "}",
3003             format("int q() {\n"
3004                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3005                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3006                    "  IPC_END_MESSAGE_MAP()\n"
3007                    "}"));
3008 
3009   // Same inside macros.
3010   EXPECT_EQ("#define LIST(L) \\\n"
3011             "  L(A)          \\\n"
3012             "  L(B)          \\\n"
3013             "  L(C)",
3014             format("#define LIST(L) \\\n"
3015                    "  L(A) \\\n"
3016                    "  L(B) \\\n"
3017                    "  L(C)",
3018                    getGoogleStyle()));
3019 
3020   // These must not be recognized as macros.
3021   EXPECT_EQ("int q() {\n"
3022             "  f(x);\n"
3023             "  f(x) {}\n"
3024             "  f(x)->g();\n"
3025             "  f(x)->*g();\n"
3026             "  f(x).g();\n"
3027             "  f(x) = x;\n"
3028             "  f(x) += x;\n"
3029             "  f(x) -= x;\n"
3030             "  f(x) *= x;\n"
3031             "  f(x) /= x;\n"
3032             "  f(x) %= x;\n"
3033             "  f(x) &= x;\n"
3034             "  f(x) |= x;\n"
3035             "  f(x) ^= x;\n"
3036             "  f(x) >>= x;\n"
3037             "  f(x) <<= x;\n"
3038             "  f(x)[y].z();\n"
3039             "  LOG(INFO) << x;\n"
3040             "  ifstream(x) >> x;\n"
3041             "}\n",
3042             format("int q() {\n"
3043                    "  f(x)\n;\n"
3044                    "  f(x)\n {}\n"
3045                    "  f(x)\n->g();\n"
3046                    "  f(x)\n->*g();\n"
3047                    "  f(x)\n.g();\n"
3048                    "  f(x)\n = x;\n"
3049                    "  f(x)\n += x;\n"
3050                    "  f(x)\n -= x;\n"
3051                    "  f(x)\n *= x;\n"
3052                    "  f(x)\n /= x;\n"
3053                    "  f(x)\n %= x;\n"
3054                    "  f(x)\n &= x;\n"
3055                    "  f(x)\n |= x;\n"
3056                    "  f(x)\n ^= x;\n"
3057                    "  f(x)\n >>= x;\n"
3058                    "  f(x)\n <<= x;\n"
3059                    "  f(x)\n[y].z();\n"
3060                    "  LOG(INFO)\n << x;\n"
3061                    "  ifstream(x)\n >> x;\n"
3062                    "}\n"));
3063   EXPECT_EQ("int q() {\n"
3064             "  F(x)\n"
3065             "  if (1) {\n"
3066             "  }\n"
3067             "  F(x)\n"
3068             "  while (1) {\n"
3069             "  }\n"
3070             "  F(x)\n"
3071             "  G(x);\n"
3072             "  F(x)\n"
3073             "  try {\n"
3074             "    Q();\n"
3075             "  } catch (...) {\n"
3076             "  }\n"
3077             "}\n",
3078             format("int q() {\n"
3079                    "F(x)\n"
3080                    "if (1) {}\n"
3081                    "F(x)\n"
3082                    "while (1) {}\n"
3083                    "F(x)\n"
3084                    "G(x);\n"
3085                    "F(x)\n"
3086                    "try { Q(); } catch (...) {}\n"
3087                    "}\n"));
3088   EXPECT_EQ("class A {\n"
3089             "  A() : t(0) {}\n"
3090             "  A(int i) noexcept() : {}\n"
3091             "  A(X x)\n" // FIXME: function-level try blocks are broken.
3092             "  try : t(0) {\n"
3093             "  } catch (...) {\n"
3094             "  }\n"
3095             "};",
3096             format("class A {\n"
3097                    "  A()\n : t(0) {}\n"
3098                    "  A(int i)\n noexcept() : {}\n"
3099                    "  A(X x)\n"
3100                    "  try : t(0) {} catch (...) {}\n"
3101                    "};"));
3102   FormatStyle Style = getLLVMStyle();
3103   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3104   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
3105   Style.BraceWrapping.AfterFunction = true;
3106   EXPECT_EQ("void f()\n"
3107             "try\n"
3108             "{\n"
3109             "}",
3110             format("void f() try {\n"
3111                    "}",
3112                    Style));
3113   EXPECT_EQ("class SomeClass {\n"
3114             "public:\n"
3115             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3116             "};",
3117             format("class SomeClass {\n"
3118                    "public:\n"
3119                    "  SomeClass()\n"
3120                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3121                    "};"));
3122   EXPECT_EQ("class SomeClass {\n"
3123             "public:\n"
3124             "  SomeClass()\n"
3125             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3126             "};",
3127             format("class SomeClass {\n"
3128                    "public:\n"
3129                    "  SomeClass()\n"
3130                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3131                    "};",
3132                    getLLVMStyleWithColumns(40)));
3133 
3134   verifyFormat("MACRO(>)");
3135 
3136   // Some macros contain an implicit semicolon.
3137   Style = getLLVMStyle();
3138   Style.StatementMacros.push_back("FOO");
3139   verifyFormat("FOO(a) int b = 0;");
3140   verifyFormat("FOO(a)\n"
3141                "int b = 0;",
3142                Style);
3143   verifyFormat("FOO(a);\n"
3144                "int b = 0;",
3145                Style);
3146   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
3147                "int b = 0;",
3148                Style);
3149   verifyFormat("FOO()\n"
3150                "int b = 0;",
3151                Style);
3152   verifyFormat("FOO\n"
3153                "int b = 0;",
3154                Style);
3155   verifyFormat("void f() {\n"
3156                "  FOO(a)\n"
3157                "  return a;\n"
3158                "}",
3159                Style);
3160   verifyFormat("FOO(a)\n"
3161                "FOO(b)",
3162                Style);
3163   verifyFormat("int a = 0;\n"
3164                "FOO(b)\n"
3165                "int c = 0;",
3166                Style);
3167   verifyFormat("int a = 0;\n"
3168                "int x = FOO(a)\n"
3169                "int b = 0;",
3170                Style);
3171   verifyFormat("void foo(int a) { FOO(a) }\n"
3172                "uint32_t bar() {}",
3173                Style);
3174 }
3175 
TEST_F(FormatTest,LayoutMacroDefinitionsStatementsSpanningBlocks)3176 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
3177   verifyFormat("#define A \\\n"
3178                "  f({     \\\n"
3179                "    g();  \\\n"
3180                "  });",
3181                getLLVMStyleWithColumns(11));
3182 }
3183 
TEST_F(FormatTest,IndentPreprocessorDirectives)3184 TEST_F(FormatTest, IndentPreprocessorDirectives) {
3185   FormatStyle Style = getLLVMStyle();
3186   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
3187   Style.ColumnLimit = 40;
3188   verifyFormat("#ifdef _WIN32\n"
3189                "#define A 0\n"
3190                "#ifdef VAR2\n"
3191                "#define B 1\n"
3192                "#include <someheader.h>\n"
3193                "#define MACRO                          \\\n"
3194                "  some_very_long_func_aaaaaaaaaa();\n"
3195                "#endif\n"
3196                "#else\n"
3197                "#define A 1\n"
3198                "#endif",
3199                Style);
3200   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
3201   verifyFormat("#ifdef _WIN32\n"
3202                "#  define A 0\n"
3203                "#  ifdef VAR2\n"
3204                "#    define B 1\n"
3205                "#    include <someheader.h>\n"
3206                "#    define MACRO                      \\\n"
3207                "      some_very_long_func_aaaaaaaaaa();\n"
3208                "#  endif\n"
3209                "#else\n"
3210                "#  define A 1\n"
3211                "#endif",
3212                Style);
3213   verifyFormat("#if A\n"
3214                "#  define MACRO                        \\\n"
3215                "    void a(int x) {                    \\\n"
3216                "      b();                             \\\n"
3217                "      c();                             \\\n"
3218                "      d();                             \\\n"
3219                "      e();                             \\\n"
3220                "      f();                             \\\n"
3221                "    }\n"
3222                "#endif",
3223                Style);
3224   // Comments before include guard.
3225   verifyFormat("// file comment\n"
3226                "// file comment\n"
3227                "#ifndef HEADER_H\n"
3228                "#define HEADER_H\n"
3229                "code();\n"
3230                "#endif",
3231                Style);
3232   // Test with include guards.
3233   verifyFormat("#ifndef HEADER_H\n"
3234                "#define HEADER_H\n"
3235                "code();\n"
3236                "#endif",
3237                Style);
3238   // Include guards must have a #define with the same variable immediately
3239   // after #ifndef.
3240   verifyFormat("#ifndef NOT_GUARD\n"
3241                "#  define FOO\n"
3242                "code();\n"
3243                "#endif",
3244                Style);
3245 
3246   // Include guards must cover the entire file.
3247   verifyFormat("code();\n"
3248                "code();\n"
3249                "#ifndef NOT_GUARD\n"
3250                "#  define NOT_GUARD\n"
3251                "code();\n"
3252                "#endif",
3253                Style);
3254   verifyFormat("#ifndef NOT_GUARD\n"
3255                "#  define NOT_GUARD\n"
3256                "code();\n"
3257                "#endif\n"
3258                "code();",
3259                Style);
3260   // Test with trailing blank lines.
3261   verifyFormat("#ifndef HEADER_H\n"
3262                "#define HEADER_H\n"
3263                "code();\n"
3264                "#endif\n",
3265                Style);
3266   // Include guards don't have #else.
3267   verifyFormat("#ifndef NOT_GUARD\n"
3268                "#  define NOT_GUARD\n"
3269                "code();\n"
3270                "#else\n"
3271                "#endif",
3272                Style);
3273   verifyFormat("#ifndef NOT_GUARD\n"
3274                "#  define NOT_GUARD\n"
3275                "code();\n"
3276                "#elif FOO\n"
3277                "#endif",
3278                Style);
3279   // Non-identifier #define after potential include guard.
3280   verifyFormat("#ifndef FOO\n"
3281                "#  define 1\n"
3282                "#endif\n",
3283                Style);
3284   // #if closes past last non-preprocessor line.
3285   verifyFormat("#ifndef FOO\n"
3286                "#define FOO\n"
3287                "#if 1\n"
3288                "int i;\n"
3289                "#  define A 0\n"
3290                "#endif\n"
3291                "#endif\n",
3292                Style);
3293   // Don't crash if there is an #elif directive without a condition.
3294   verifyFormat("#if 1\n"
3295                "int x;\n"
3296                "#elif\n"
3297                "int y;\n"
3298                "#else\n"
3299                "int z;\n"
3300                "#endif",
3301                Style);
3302   // FIXME: This doesn't handle the case where there's code between the
3303   // #ifndef and #define but all other conditions hold. This is because when
3304   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
3305   // previous code line yet, so we can't detect it.
3306   EXPECT_EQ("#ifndef NOT_GUARD\n"
3307             "code();\n"
3308             "#define NOT_GUARD\n"
3309             "code();\n"
3310             "#endif",
3311             format("#ifndef NOT_GUARD\n"
3312                    "code();\n"
3313                    "#  define NOT_GUARD\n"
3314                    "code();\n"
3315                    "#endif",
3316                    Style));
3317   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
3318   // be outside an include guard. Examples are #pragma once and
3319   // #pragma GCC diagnostic, or anything else that does not change the meaning
3320   // of the file if it's included multiple times.
3321   EXPECT_EQ("#ifdef WIN32\n"
3322             "#  pragma once\n"
3323             "#endif\n"
3324             "#ifndef HEADER_H\n"
3325             "#  define HEADER_H\n"
3326             "code();\n"
3327             "#endif",
3328             format("#ifdef WIN32\n"
3329                    "#  pragma once\n"
3330                    "#endif\n"
3331                    "#ifndef HEADER_H\n"
3332                    "#define HEADER_H\n"
3333                    "code();\n"
3334                    "#endif",
3335                    Style));
3336   // FIXME: This does not detect when there is a single non-preprocessor line
3337   // in front of an include-guard-like structure where other conditions hold
3338   // because ScopedLineState hides the line.
3339   EXPECT_EQ("code();\n"
3340             "#ifndef HEADER_H\n"
3341             "#define HEADER_H\n"
3342             "code();\n"
3343             "#endif",
3344             format("code();\n"
3345                    "#ifndef HEADER_H\n"
3346                    "#  define HEADER_H\n"
3347                    "code();\n"
3348                    "#endif",
3349                    Style));
3350   // Keep comments aligned with #, otherwise indent comments normally. These
3351   // tests cannot use verifyFormat because messUp manipulates leading
3352   // whitespace.
3353   {
3354     const char *Expected = ""
3355                            "void f() {\n"
3356                            "#if 1\n"
3357                            "// Preprocessor aligned.\n"
3358                            "#  define A 0\n"
3359                            "  // Code. Separated by blank line.\n"
3360                            "\n"
3361                            "#  define B 0\n"
3362                            "  // Code. Not aligned with #\n"
3363                            "#  define C 0\n"
3364                            "#endif";
3365     const char *ToFormat = ""
3366                            "void f() {\n"
3367                            "#if 1\n"
3368                            "// Preprocessor aligned.\n"
3369                            "#  define A 0\n"
3370                            "// Code. Separated by blank line.\n"
3371                            "\n"
3372                            "#  define B 0\n"
3373                            "   // Code. Not aligned with #\n"
3374                            "#  define C 0\n"
3375                            "#endif";
3376     EXPECT_EQ(Expected, format(ToFormat, Style));
3377     EXPECT_EQ(Expected, format(Expected, Style));
3378   }
3379   // Keep block quotes aligned.
3380   {
3381     const char *Expected = ""
3382                            "void f() {\n"
3383                            "#if 1\n"
3384                            "/* Preprocessor aligned. */\n"
3385                            "#  define A 0\n"
3386                            "  /* Code. Separated by blank line. */\n"
3387                            "\n"
3388                            "#  define B 0\n"
3389                            "  /* Code. Not aligned with # */\n"
3390                            "#  define C 0\n"
3391                            "#endif";
3392     const char *ToFormat = ""
3393                            "void f() {\n"
3394                            "#if 1\n"
3395                            "/* Preprocessor aligned. */\n"
3396                            "#  define A 0\n"
3397                            "/* Code. Separated by blank line. */\n"
3398                            "\n"
3399                            "#  define B 0\n"
3400                            "   /* Code. Not aligned with # */\n"
3401                            "#  define C 0\n"
3402                            "#endif";
3403     EXPECT_EQ(Expected, format(ToFormat, Style));
3404     EXPECT_EQ(Expected, format(Expected, Style));
3405   }
3406   // Keep comments aligned with un-indented directives.
3407   {
3408     const char *Expected = ""
3409                            "void f() {\n"
3410                            "// Preprocessor aligned.\n"
3411                            "#define A 0\n"
3412                            "  // Code. Separated by blank line.\n"
3413                            "\n"
3414                            "#define B 0\n"
3415                            "  // Code. Not aligned with #\n"
3416                            "#define C 0\n";
3417     const char *ToFormat = ""
3418                            "void f() {\n"
3419                            "// Preprocessor aligned.\n"
3420                            "#define A 0\n"
3421                            "// Code. Separated by blank line.\n"
3422                            "\n"
3423                            "#define B 0\n"
3424                            "   // Code. Not aligned with #\n"
3425                            "#define C 0\n";
3426     EXPECT_EQ(Expected, format(ToFormat, Style));
3427     EXPECT_EQ(Expected, format(Expected, Style));
3428   }
3429   // Test AfterHash with tabs.
3430   {
3431     FormatStyle Tabbed = Style;
3432     Tabbed.UseTab = FormatStyle::UT_Always;
3433     Tabbed.IndentWidth = 8;
3434     Tabbed.TabWidth = 8;
3435     verifyFormat("#ifdef _WIN32\n"
3436                  "#\tdefine A 0\n"
3437                  "#\tifdef VAR2\n"
3438                  "#\t\tdefine B 1\n"
3439                  "#\t\tinclude <someheader.h>\n"
3440                  "#\t\tdefine MACRO          \\\n"
3441                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
3442                  "#\tendif\n"
3443                  "#else\n"
3444                  "#\tdefine A 1\n"
3445                  "#endif",
3446                  Tabbed);
3447   }
3448 
3449   // Regression test: Multiline-macro inside include guards.
3450   verifyFormat("#ifndef HEADER_H\n"
3451                "#define HEADER_H\n"
3452                "#define A()        \\\n"
3453                "  int i;           \\\n"
3454                "  int j;\n"
3455                "#endif // HEADER_H",
3456                getLLVMStyleWithColumns(20));
3457 
3458   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
3459   // Basic before hash indent tests
3460   verifyFormat("#ifdef _WIN32\n"
3461                "  #define A 0\n"
3462                "  #ifdef VAR2\n"
3463                "    #define B 1\n"
3464                "    #include <someheader.h>\n"
3465                "    #define MACRO                      \\\n"
3466                "      some_very_long_func_aaaaaaaaaa();\n"
3467                "  #endif\n"
3468                "#else\n"
3469                "  #define A 1\n"
3470                "#endif",
3471                Style);
3472   verifyFormat("#if A\n"
3473                "  #define MACRO                        \\\n"
3474                "    void a(int x) {                    \\\n"
3475                "      b();                             \\\n"
3476                "      c();                             \\\n"
3477                "      d();                             \\\n"
3478                "      e();                             \\\n"
3479                "      f();                             \\\n"
3480                "    }\n"
3481                "#endif",
3482                Style);
3483   // Keep comments aligned with indented directives. These
3484   // tests cannot use verifyFormat because messUp manipulates leading
3485   // whitespace.
3486   {
3487     const char *Expected = "void f() {\n"
3488                            "// Aligned to preprocessor.\n"
3489                            "#if 1\n"
3490                            "  // Aligned to code.\n"
3491                            "  int a;\n"
3492                            "  #if 1\n"
3493                            "    // Aligned to preprocessor.\n"
3494                            "    #define A 0\n"
3495                            "  // Aligned to code.\n"
3496                            "  int b;\n"
3497                            "  #endif\n"
3498                            "#endif\n"
3499                            "}";
3500     const char *ToFormat = "void f() {\n"
3501                            "// Aligned to preprocessor.\n"
3502                            "#if 1\n"
3503                            "// Aligned to code.\n"
3504                            "int a;\n"
3505                            "#if 1\n"
3506                            "// Aligned to preprocessor.\n"
3507                            "#define A 0\n"
3508                            "// Aligned to code.\n"
3509                            "int b;\n"
3510                            "#endif\n"
3511                            "#endif\n"
3512                            "}";
3513     EXPECT_EQ(Expected, format(ToFormat, Style));
3514     EXPECT_EQ(Expected, format(Expected, Style));
3515   }
3516   {
3517     const char *Expected = "void f() {\n"
3518                            "/* Aligned to preprocessor. */\n"
3519                            "#if 1\n"
3520                            "  /* Aligned to code. */\n"
3521                            "  int a;\n"
3522                            "  #if 1\n"
3523                            "    /* Aligned to preprocessor. */\n"
3524                            "    #define A 0\n"
3525                            "  /* Aligned to code. */\n"
3526                            "  int b;\n"
3527                            "  #endif\n"
3528                            "#endif\n"
3529                            "}";
3530     const char *ToFormat = "void f() {\n"
3531                            "/* Aligned to preprocessor. */\n"
3532                            "#if 1\n"
3533                            "/* Aligned to code. */\n"
3534                            "int a;\n"
3535                            "#if 1\n"
3536                            "/* Aligned to preprocessor. */\n"
3537                            "#define A 0\n"
3538                            "/* Aligned to code. */\n"
3539                            "int b;\n"
3540                            "#endif\n"
3541                            "#endif\n"
3542                            "}";
3543     EXPECT_EQ(Expected, format(ToFormat, Style));
3544     EXPECT_EQ(Expected, format(Expected, Style));
3545   }
3546 
3547   // Test single comment before preprocessor
3548   verifyFormat("// Comment\n"
3549                "\n"
3550                "#if 1\n"
3551                "#endif",
3552                Style);
3553 }
3554 
TEST_F(FormatTest,FormatHashIfNotAtStartOfLine)3555 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
3556   verifyFormat("{\n  { a #c; }\n}");
3557 }
3558 
TEST_F(FormatTest,FormatUnbalancedStructuralElements)3559 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
3560   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
3561             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
3562   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
3563             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
3564 }
3565 
TEST_F(FormatTest,EscapedNewlines)3566 TEST_F(FormatTest, EscapedNewlines) {
3567   FormatStyle Narrow = getLLVMStyleWithColumns(11);
3568   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
3569             format("#define A \\\nint i;\\\n  int j;", Narrow));
3570   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
3571   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3572   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
3573   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
3574 
3575   FormatStyle AlignLeft = getLLVMStyle();
3576   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
3577   EXPECT_EQ("#define MACRO(x) \\\n"
3578             "private:         \\\n"
3579             "  int x(int a);\n",
3580             format("#define MACRO(x) \\\n"
3581                    "private:         \\\n"
3582                    "  int x(int a);\n",
3583                    AlignLeft));
3584 
3585   // CRLF line endings
3586   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
3587             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
3588   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
3589   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3590   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
3591   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
3592   EXPECT_EQ("#define MACRO(x) \\\r\n"
3593             "private:         \\\r\n"
3594             "  int x(int a);\r\n",
3595             format("#define MACRO(x) \\\r\n"
3596                    "private:         \\\r\n"
3597                    "  int x(int a);\r\n",
3598                    AlignLeft));
3599 
3600   FormatStyle DontAlign = getLLVMStyle();
3601   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
3602   DontAlign.MaxEmptyLinesToKeep = 3;
3603   // FIXME: can't use verifyFormat here because the newline before
3604   // "public:" is not inserted the first time it's reformatted
3605   EXPECT_EQ("#define A \\\n"
3606             "  class Foo { \\\n"
3607             "    void bar(); \\\n"
3608             "\\\n"
3609             "\\\n"
3610             "\\\n"
3611             "  public: \\\n"
3612             "    void baz(); \\\n"
3613             "  };",
3614             format("#define A \\\n"
3615                    "  class Foo { \\\n"
3616                    "    void bar(); \\\n"
3617                    "\\\n"
3618                    "\\\n"
3619                    "\\\n"
3620                    "  public: \\\n"
3621                    "    void baz(); \\\n"
3622                    "  };",
3623                    DontAlign));
3624 }
3625 
TEST_F(FormatTest,CalculateSpaceOnConsecutiveLinesInMacro)3626 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
3627   verifyFormat("#define A \\\n"
3628                "  int v(  \\\n"
3629                "      a); \\\n"
3630                "  int i;",
3631                getLLVMStyleWithColumns(11));
3632 }
3633 
TEST_F(FormatTest,MixingPreprocessorDirectivesAndNormalCode)3634 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
3635   EXPECT_EQ(
3636       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3637       "                      \\\n"
3638       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3639       "\n"
3640       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3641       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
3642       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
3643              "\\\n"
3644              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3645              "  \n"
3646              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3647              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
3648 }
3649 
TEST_F(FormatTest,LayoutStatementsAroundPreprocessorDirectives)3650 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
3651   EXPECT_EQ("int\n"
3652             "#define A\n"
3653             "    a;",
3654             format("int\n#define A\na;"));
3655   verifyFormat("functionCallTo(\n"
3656                "    someOtherFunction(\n"
3657                "        withSomeParameters, whichInSequence,\n"
3658                "        areLongerThanALine(andAnotherCall,\n"
3659                "#define A B\n"
3660                "                           withMoreParamters,\n"
3661                "                           whichStronglyInfluenceTheLayout),\n"
3662                "        andMoreParameters),\n"
3663                "    trailing);",
3664                getLLVMStyleWithColumns(69));
3665   verifyFormat("Foo::Foo()\n"
3666                "#ifdef BAR\n"
3667                "    : baz(0)\n"
3668                "#endif\n"
3669                "{\n"
3670                "}");
3671   verifyFormat("void f() {\n"
3672                "  if (true)\n"
3673                "#ifdef A\n"
3674                "    f(42);\n"
3675                "  x();\n"
3676                "#else\n"
3677                "    g();\n"
3678                "  x();\n"
3679                "#endif\n"
3680                "}");
3681   verifyFormat("void f(param1, param2,\n"
3682                "       param3,\n"
3683                "#ifdef A\n"
3684                "       param4(param5,\n"
3685                "#ifdef A1\n"
3686                "              param6,\n"
3687                "#ifdef A2\n"
3688                "              param7),\n"
3689                "#else\n"
3690                "              param8),\n"
3691                "       param9,\n"
3692                "#endif\n"
3693                "       param10,\n"
3694                "#endif\n"
3695                "       param11)\n"
3696                "#else\n"
3697                "       param12)\n"
3698                "#endif\n"
3699                "{\n"
3700                "  x();\n"
3701                "}",
3702                getLLVMStyleWithColumns(28));
3703   verifyFormat("#if 1\n"
3704                "int i;");
3705   verifyFormat("#if 1\n"
3706                "#endif\n"
3707                "#if 1\n"
3708                "#else\n"
3709                "#endif\n");
3710   verifyFormat("DEBUG({\n"
3711                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3712                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
3713                "});\n"
3714                "#if a\n"
3715                "#else\n"
3716                "#endif");
3717 
3718   verifyIncompleteFormat("void f(\n"
3719                          "#if A\n"
3720                          ");\n"
3721                          "#else\n"
3722                          "#endif");
3723 }
3724 
TEST_F(FormatTest,GraciouslyHandleIncorrectPreprocessorConditions)3725 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
3726   verifyFormat("#endif\n"
3727                "#if B");
3728 }
3729 
TEST_F(FormatTest,FormatsJoinedLinesOnSubsequentRuns)3730 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
3731   FormatStyle SingleLine = getLLVMStyle();
3732   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
3733   verifyFormat("#if 0\n"
3734                "#elif 1\n"
3735                "#endif\n"
3736                "void foo() {\n"
3737                "  if (test) foo2();\n"
3738                "}",
3739                SingleLine);
3740 }
3741 
TEST_F(FormatTest,LayoutBlockInsideParens)3742 TEST_F(FormatTest, LayoutBlockInsideParens) {
3743   verifyFormat("functionCall({ int i; });");
3744   verifyFormat("functionCall({\n"
3745                "  int i;\n"
3746                "  int j;\n"
3747                "});");
3748   verifyFormat("functionCall(\n"
3749                "    {\n"
3750                "      int i;\n"
3751                "      int j;\n"
3752                "    },\n"
3753                "    aaaa, bbbb, cccc);");
3754   verifyFormat("functionA(functionB({\n"
3755                "            int i;\n"
3756                "            int j;\n"
3757                "          }),\n"
3758                "          aaaa, bbbb, cccc);");
3759   verifyFormat("functionCall(\n"
3760                "    {\n"
3761                "      int i;\n"
3762                "      int j;\n"
3763                "    },\n"
3764                "    aaaa, bbbb, // comment\n"
3765                "    cccc);");
3766   verifyFormat("functionA(functionB({\n"
3767                "            int i;\n"
3768                "            int j;\n"
3769                "          }),\n"
3770                "          aaaa, bbbb, // comment\n"
3771                "          cccc);");
3772   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
3773   verifyFormat("functionCall(aaaa, bbbb, {\n"
3774                "  int i;\n"
3775                "  int j;\n"
3776                "});");
3777   verifyFormat(
3778       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
3779       "    {\n"
3780       "      int i; // break\n"
3781       "    },\n"
3782       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
3783       "                                     ccccccccccccccccc));");
3784   verifyFormat("DEBUG({\n"
3785                "  if (a)\n"
3786                "    f();\n"
3787                "});");
3788 }
3789 
TEST_F(FormatTest,LayoutBlockInsideStatement)3790 TEST_F(FormatTest, LayoutBlockInsideStatement) {
3791   EXPECT_EQ("SOME_MACRO { int i; }\n"
3792             "int i;",
3793             format("  SOME_MACRO  {int i;}  int i;"));
3794 }
3795 
TEST_F(FormatTest,LayoutNestedBlocks)3796 TEST_F(FormatTest, LayoutNestedBlocks) {
3797   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
3798                "  struct s {\n"
3799                "    int i;\n"
3800                "  };\n"
3801                "  s kBitsToOs[] = {{10}};\n"
3802                "  for (int i = 0; i < 10; ++i)\n"
3803                "    return;\n"
3804                "}");
3805   verifyFormat("call(parameter, {\n"
3806                "  something();\n"
3807                "  // Comment using all columns.\n"
3808                "  somethingelse();\n"
3809                "});",
3810                getLLVMStyleWithColumns(40));
3811   verifyFormat("DEBUG( //\n"
3812                "    { f(); }, a);");
3813   verifyFormat("DEBUG( //\n"
3814                "    {\n"
3815                "      f(); //\n"
3816                "    },\n"
3817                "    a);");
3818 
3819   EXPECT_EQ("call(parameter, {\n"
3820             "  something();\n"
3821             "  // Comment too\n"
3822             "  // looooooooooong.\n"
3823             "  somethingElse();\n"
3824             "});",
3825             format("call(parameter, {\n"
3826                    "  something();\n"
3827                    "  // Comment too looooooooooong.\n"
3828                    "  somethingElse();\n"
3829                    "});",
3830                    getLLVMStyleWithColumns(29)));
3831   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
3832   EXPECT_EQ("DEBUG({ // comment\n"
3833             "  int i;\n"
3834             "});",
3835             format("DEBUG({ // comment\n"
3836                    "int  i;\n"
3837                    "});"));
3838   EXPECT_EQ("DEBUG({\n"
3839             "  int i;\n"
3840             "\n"
3841             "  // comment\n"
3842             "  int j;\n"
3843             "});",
3844             format("DEBUG({\n"
3845                    "  int  i;\n"
3846                    "\n"
3847                    "  // comment\n"
3848                    "  int  j;\n"
3849                    "});"));
3850 
3851   verifyFormat("DEBUG({\n"
3852                "  if (a)\n"
3853                "    return;\n"
3854                "});");
3855   verifyGoogleFormat("DEBUG({\n"
3856                      "  if (a) return;\n"
3857                      "});");
3858   FormatStyle Style = getGoogleStyle();
3859   Style.ColumnLimit = 45;
3860   verifyFormat("Debug(\n"
3861                "    aaaaa,\n"
3862                "    {\n"
3863                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
3864                "    },\n"
3865                "    a);",
3866                Style);
3867 
3868   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
3869 
3870   verifyNoCrash("^{v^{a}}");
3871 }
3872 
TEST_F(FormatTest,FormatNestedBlocksInMacros)3873 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
3874   EXPECT_EQ("#define MACRO()                     \\\n"
3875             "  Debug(aaa, /* force line break */ \\\n"
3876             "        {                           \\\n"
3877             "          int i;                    \\\n"
3878             "          int j;                    \\\n"
3879             "        })",
3880             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
3881                    "          {  int   i;  int  j;   })",
3882                    getGoogleStyle()));
3883 
3884   EXPECT_EQ("#define A                                       \\\n"
3885             "  [] {                                          \\\n"
3886             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
3887             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
3888             "  }",
3889             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
3890                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
3891                    getGoogleStyle()));
3892 }
3893 
TEST_F(FormatTest,PutEmptyBlocksIntoOneLine)3894 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
3895   EXPECT_EQ("{}", format("{}"));
3896   verifyFormat("enum E {};");
3897   verifyFormat("enum E {}");
3898   FormatStyle Style = getLLVMStyle();
3899   Style.SpaceInEmptyBlock = true;
3900   EXPECT_EQ("void f() { }", format("void f() {}", Style));
3901   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
3902   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
3903 }
3904 
TEST_F(FormatTest,FormatBeginBlockEndMacros)3905 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
3906   FormatStyle Style = getLLVMStyle();
3907   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
3908   Style.MacroBlockEnd = "^[A-Z_]+_END$";
3909   verifyFormat("FOO_BEGIN\n"
3910                "  FOO_ENTRY\n"
3911                "FOO_END",
3912                Style);
3913   verifyFormat("FOO_BEGIN\n"
3914                "  NESTED_FOO_BEGIN\n"
3915                "    NESTED_FOO_ENTRY\n"
3916                "  NESTED_FOO_END\n"
3917                "FOO_END",
3918                Style);
3919   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
3920                "  int x;\n"
3921                "  x = 1;\n"
3922                "FOO_END(Baz)",
3923                Style);
3924 }
3925 
3926 //===----------------------------------------------------------------------===//
3927 // Line break tests.
3928 //===----------------------------------------------------------------------===//
3929 
TEST_F(FormatTest,PreventConfusingIndents)3930 TEST_F(FormatTest, PreventConfusingIndents) {
3931   verifyFormat(
3932       "void f() {\n"
3933       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
3934       "                         parameter, parameter, parameter)),\n"
3935       "                     SecondLongCall(parameter));\n"
3936       "}");
3937   verifyFormat(
3938       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3939       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
3940       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3941       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
3942   verifyFormat(
3943       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3944       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
3945       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3946       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
3947   verifyFormat(
3948       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
3949       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
3950       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
3951       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
3952   verifyFormat("int a = bbbb && ccc &&\n"
3953                "        fffff(\n"
3954                "#define A Just forcing a new line\n"
3955                "            ddd);");
3956 }
3957 
TEST_F(FormatTest,LineBreakingInBinaryExpressions)3958 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
3959   verifyFormat(
3960       "bool aaaaaaa =\n"
3961       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
3962       "    bbbbbbbb();");
3963   verifyFormat(
3964       "bool aaaaaaa =\n"
3965       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
3966       "    bbbbbbbb();");
3967 
3968   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
3969                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
3970                "    ccccccccc == ddddddddddd;");
3971   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
3972                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
3973                "    ccccccccc == ddddddddddd;");
3974   verifyFormat(
3975       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
3976       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
3977       "    ccccccccc == ddddddddddd;");
3978 
3979   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
3980                "                 aaaaaa) &&\n"
3981                "         bbbbbb && cccccc;");
3982   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
3983                "                 aaaaaa) >>\n"
3984                "         bbbbbb;");
3985   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
3986                "    SourceMgr.getSpellingColumnNumber(\n"
3987                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
3988                "    1);");
3989 
3990   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3991                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
3992                "    cccccc) {\n}");
3993   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3994                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
3995                "              cccccc) {\n}");
3996   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3997                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
3998                "              cccccc) {\n}");
3999   verifyFormat("b = a &&\n"
4000                "    // Comment\n"
4001                "    b.c && d;");
4002 
4003   // If the LHS of a comparison is not a binary expression itself, the
4004   // additional linebreak confuses many people.
4005   verifyFormat(
4006       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4007       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
4008       "}");
4009   verifyFormat(
4010       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4011       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4012       "}");
4013   verifyFormat(
4014       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
4015       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4016       "}");
4017   verifyFormat(
4018       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4019       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
4020       "}");
4021   // Even explicit parentheses stress the precedence enough to make the
4022   // additional break unnecessary.
4023   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4024                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4025                "}");
4026   // This cases is borderline, but with the indentation it is still readable.
4027   verifyFormat(
4028       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4029       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4030       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
4031       "}",
4032       getLLVMStyleWithColumns(75));
4033 
4034   // If the LHS is a binary expression, we should still use the additional break
4035   // as otherwise the formatting hides the operator precedence.
4036   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4037                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4038                "    5) {\n"
4039                "}");
4040   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4041                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
4042                "    5) {\n"
4043                "}");
4044 
4045   FormatStyle OnePerLine = getLLVMStyle();
4046   OnePerLine.BinPackParameters = false;
4047   verifyFormat(
4048       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4049       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4050       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
4051       OnePerLine);
4052 
4053   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
4054                "                .aaa(aaaaaaaaaaaaa) *\n"
4055                "            aaaaaaa +\n"
4056                "        aaaaaaa;",
4057                getLLVMStyleWithColumns(40));
4058 }
4059 
TEST_F(FormatTest,ExpressionIndentation)4060 TEST_F(FormatTest, ExpressionIndentation) {
4061   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4062                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4063                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4064                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4065                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
4066                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
4067                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4068                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
4069                "                 ccccccccccccccccccccccccccccccccccccccccc;");
4070   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4071                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4072                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4073                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4074   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4075                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4076                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4077                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4078   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4079                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4080                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4081                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4082   verifyFormat("if () {\n"
4083                "} else if (aaaaa && bbbbb > // break\n"
4084                "                        ccccc) {\n"
4085                "}");
4086   verifyFormat("if () {\n"
4087                "} else if constexpr (aaaaa && bbbbb > // break\n"
4088                "                                  ccccc) {\n"
4089                "}");
4090   verifyFormat("if () {\n"
4091                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
4092                "                                  ccccc) {\n"
4093                "}");
4094   verifyFormat("if () {\n"
4095                "} else if (aaaaa &&\n"
4096                "           bbbbb > // break\n"
4097                "               ccccc &&\n"
4098                "           ddddd) {\n"
4099                "}");
4100 
4101   // Presence of a trailing comment used to change indentation of b.
4102   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
4103                "       b;\n"
4104                "return aaaaaaaaaaaaaaaaaaa +\n"
4105                "       b; //",
4106                getLLVMStyleWithColumns(30));
4107 }
4108 
TEST_F(FormatTest,ExpressionIndentationBreakingBeforeOperators)4109 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
4110   // Not sure what the best system is here. Like this, the LHS can be found
4111   // immediately above an operator (everything with the same or a higher
4112   // indent). The RHS is aligned right of the operator and so compasses
4113   // everything until something with the same indent as the operator is found.
4114   // FIXME: Is this a good system?
4115   FormatStyle Style = getLLVMStyle();
4116   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4117   verifyFormat(
4118       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4119       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4120       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4121       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4122       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4123       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4124       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4125       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4126       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
4127       Style);
4128   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4129                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4130                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4131                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4132                Style);
4133   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4134                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4135                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4136                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4137                Style);
4138   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4139                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4140                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4141                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4142                Style);
4143   verifyFormat("if () {\n"
4144                "} else if (aaaaa\n"
4145                "           && bbbbb // break\n"
4146                "                  > ccccc) {\n"
4147                "}",
4148                Style);
4149   verifyFormat("return (a)\n"
4150                "       // comment\n"
4151                "       + b;",
4152                Style);
4153   verifyFormat(
4154       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4155       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4156       "             + cc;",
4157       Style);
4158 
4159   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4160                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4161                Style);
4162 
4163   // Forced by comments.
4164   verifyFormat(
4165       "unsigned ContentSize =\n"
4166       "    sizeof(int16_t)   // DWARF ARange version number\n"
4167       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4168       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4169       "    + sizeof(int8_t); // Segment Size (in bytes)");
4170 
4171   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4172                "       == boost::fusion::at_c<1>(iiii).second;",
4173                Style);
4174 
4175   Style.ColumnLimit = 60;
4176   verifyFormat("zzzzzzzzzz\n"
4177                "    = bbbbbbbbbbbbbbbbb\n"
4178                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4179                Style);
4180 
4181   Style.ColumnLimit = 80;
4182   Style.IndentWidth = 4;
4183   Style.TabWidth = 4;
4184   Style.UseTab = FormatStyle::UT_Always;
4185   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4186   Style.AlignOperands = false;
4187   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
4188             "\t&& (someOtherLongishConditionPart1\n"
4189             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
4190             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
4191                    "(someOtherLongishConditionPart1 || "
4192                    "someOtherEvenLongerNestedConditionPart2);",
4193                    Style));
4194 }
4195 
TEST_F(FormatTest,EnforcedOperatorWraps)4196 TEST_F(FormatTest, EnforcedOperatorWraps) {
4197   // Here we'd like to wrap after the || operators, but a comment is forcing an
4198   // earlier wrap.
4199   verifyFormat("bool x = aaaaa //\n"
4200                "         || bbbbb\n"
4201                "         //\n"
4202                "         || cccc;");
4203 }
4204 
TEST_F(FormatTest,NoOperandAlignment)4205 TEST_F(FormatTest, NoOperandAlignment) {
4206   FormatStyle Style = getLLVMStyle();
4207   Style.AlignOperands = false;
4208   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
4209                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4210                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4211                Style);
4212   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4213   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4214                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4215                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4216                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4217                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4218                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4219                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4220                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4221                "        > ccccccccccccccccccccccccccccccccccccccccc;",
4222                Style);
4223 
4224   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4225                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4226                "    + cc;",
4227                Style);
4228   verifyFormat("int a = aa\n"
4229                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4230                "        * cccccccccccccccccccccccccccccccccccc;\n",
4231                Style);
4232 
4233   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4234   verifyFormat("return (a > b\n"
4235                "    // comment1\n"
4236                "    // comment2\n"
4237                "    || c);",
4238                Style);
4239 }
4240 
TEST_F(FormatTest,BreakingBeforeNonAssigmentOperators)4241 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
4242   FormatStyle Style = getLLVMStyle();
4243   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4244   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4245                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4246                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4247                Style);
4248 }
4249 
TEST_F(FormatTest,AllowBinPackingInsideArguments)4250 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
4251   FormatStyle Style = getLLVMStyle();
4252   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4253   Style.BinPackArguments = false;
4254   Style.ColumnLimit = 40;
4255   verifyFormat("void test() {\n"
4256                "  someFunction(\n"
4257                "      this + argument + is + quite\n"
4258                "      + long + so + it + gets + wrapped\n"
4259                "      + but + remains + bin - packed);\n"
4260                "}",
4261                Style);
4262   verifyFormat("void test() {\n"
4263                "  someFunction(arg1,\n"
4264                "               this + argument + is\n"
4265                "                   + quite + long + so\n"
4266                "                   + it + gets + wrapped\n"
4267                "                   + but + remains + bin\n"
4268                "                   - packed,\n"
4269                "               arg3);\n"
4270                "}",
4271                Style);
4272   verifyFormat("void test() {\n"
4273                "  someFunction(\n"
4274                "      arg1,\n"
4275                "      this + argument + has\n"
4276                "          + anotherFunc(nested,\n"
4277                "                        calls + whose\n"
4278                "                            + arguments\n"
4279                "                            + are + also\n"
4280                "                            + wrapped,\n"
4281                "                        in + addition)\n"
4282                "          + to + being + bin - packed,\n"
4283                "      arg3);\n"
4284                "}",
4285                Style);
4286 
4287   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
4288   verifyFormat("void test() {\n"
4289                "  someFunction(\n"
4290                "      arg1,\n"
4291                "      this + argument + has +\n"
4292                "          anotherFunc(nested,\n"
4293                "                      calls + whose +\n"
4294                "                          arguments +\n"
4295                "                          are + also +\n"
4296                "                          wrapped,\n"
4297                "                      in + addition) +\n"
4298                "          to + being + bin - packed,\n"
4299                "      arg3);\n"
4300                "}",
4301                Style);
4302 }
4303 
TEST_F(FormatTest,ConstructorInitializers)4304 TEST_F(FormatTest, ConstructorInitializers) {
4305   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
4306   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
4307                getLLVMStyleWithColumns(45));
4308   verifyFormat("Constructor()\n"
4309                "    : Inttializer(FitsOnTheLine) {}",
4310                getLLVMStyleWithColumns(44));
4311   verifyFormat("Constructor()\n"
4312                "    : Inttializer(FitsOnTheLine) {}",
4313                getLLVMStyleWithColumns(43));
4314 
4315   verifyFormat("template <typename T>\n"
4316                "Constructor() : Initializer(FitsOnTheLine) {}",
4317                getLLVMStyleWithColumns(45));
4318 
4319   verifyFormat(
4320       "SomeClass::Constructor()\n"
4321       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4322 
4323   verifyFormat(
4324       "SomeClass::Constructor()\n"
4325       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4326       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
4327   verifyFormat(
4328       "SomeClass::Constructor()\n"
4329       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4330       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4331   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4332                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4333                "    : aaaaaaaaaa(aaaaaa) {}");
4334 
4335   verifyFormat("Constructor()\n"
4336                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4337                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4338                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4339                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
4340 
4341   verifyFormat("Constructor()\n"
4342                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4343                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4344 
4345   verifyFormat("Constructor(int Parameter = 0)\n"
4346                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
4347                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
4348   verifyFormat("Constructor()\n"
4349                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
4350                "}",
4351                getLLVMStyleWithColumns(60));
4352   verifyFormat("Constructor()\n"
4353                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4354                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
4355 
4356   // Here a line could be saved by splitting the second initializer onto two
4357   // lines, but that is not desirable.
4358   verifyFormat("Constructor()\n"
4359                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
4360                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
4361                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4362 
4363   FormatStyle OnePerLine = getLLVMStyle();
4364   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4365   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
4366   verifyFormat("SomeClass::Constructor()\n"
4367                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4368                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4369                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4370                OnePerLine);
4371   verifyFormat("SomeClass::Constructor()\n"
4372                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
4373                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4374                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4375                OnePerLine);
4376   verifyFormat("MyClass::MyClass(int var)\n"
4377                "    : some_var_(var),            // 4 space indent\n"
4378                "      some_other_var_(var + 1) { // lined up\n"
4379                "}",
4380                OnePerLine);
4381   verifyFormat("Constructor()\n"
4382                "    : aaaaa(aaaaaa),\n"
4383                "      aaaaa(aaaaaa),\n"
4384                "      aaaaa(aaaaaa),\n"
4385                "      aaaaa(aaaaaa),\n"
4386                "      aaaaa(aaaaaa) {}",
4387                OnePerLine);
4388   verifyFormat("Constructor()\n"
4389                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
4390                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
4391                OnePerLine);
4392   OnePerLine.BinPackParameters = false;
4393   verifyFormat(
4394       "Constructor()\n"
4395       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4396       "          aaaaaaaaaaa().aaa(),\n"
4397       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4398       OnePerLine);
4399   OnePerLine.ColumnLimit = 60;
4400   verifyFormat("Constructor()\n"
4401                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4402                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
4403                OnePerLine);
4404 
4405   EXPECT_EQ("Constructor()\n"
4406             "    : // Comment forcing unwanted break.\n"
4407             "      aaaa(aaaa) {}",
4408             format("Constructor() :\n"
4409                    "    // Comment forcing unwanted break.\n"
4410                    "    aaaa(aaaa) {}"));
4411 }
4412 
TEST_F(FormatTest,AllowAllConstructorInitializersOnNextLine)4413 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
4414   FormatStyle Style = getLLVMStyle();
4415   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4416   Style.ColumnLimit = 60;
4417   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4418   Style.AllowAllConstructorInitializersOnNextLine = true;
4419   Style.BinPackParameters = false;
4420 
4421   for (int i = 0; i < 4; ++i) {
4422     // Test all combinations of parameters that should not have an effect.
4423     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4424     Style.AllowAllArgumentsOnNextLine = i & 2;
4425 
4426     Style.AllowAllConstructorInitializersOnNextLine = true;
4427     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4428     verifyFormat("Constructor()\n"
4429                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4430                  Style);
4431     verifyFormat("Constructor() : a(a), b(b) {}", Style);
4432 
4433     Style.AllowAllConstructorInitializersOnNextLine = false;
4434     verifyFormat("Constructor()\n"
4435                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4436                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4437                  Style);
4438     verifyFormat("Constructor() : a(a), b(b) {}", Style);
4439 
4440     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4441     Style.AllowAllConstructorInitializersOnNextLine = true;
4442     verifyFormat("Constructor()\n"
4443                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4444                  Style);
4445 
4446     Style.AllowAllConstructorInitializersOnNextLine = false;
4447     verifyFormat("Constructor()\n"
4448                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4449                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4450                  Style);
4451 
4452     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4453     Style.AllowAllConstructorInitializersOnNextLine = true;
4454     verifyFormat("Constructor() :\n"
4455                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4456                  Style);
4457 
4458     Style.AllowAllConstructorInitializersOnNextLine = false;
4459     verifyFormat("Constructor() :\n"
4460                  "    aaaaaaaaaaaaaaaaaa(a),\n"
4461                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4462                  Style);
4463   }
4464 
4465   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
4466   // AllowAllConstructorInitializersOnNextLine in all
4467   // BreakConstructorInitializers modes
4468   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4469   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4470   Style.AllowAllConstructorInitializersOnNextLine = false;
4471   verifyFormat("SomeClassWithALongName::Constructor(\n"
4472                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4473                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4474                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4475                Style);
4476 
4477   Style.AllowAllConstructorInitializersOnNextLine = true;
4478   verifyFormat("SomeClassWithALongName::Constructor(\n"
4479                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4480                "    int bbbbbbbbbbbbb,\n"
4481                "    int cccccccccccccccc)\n"
4482                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4483                Style);
4484 
4485   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4486   Style.AllowAllConstructorInitializersOnNextLine = false;
4487   verifyFormat("SomeClassWithALongName::Constructor(\n"
4488                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4489                "    int bbbbbbbbbbbbb)\n"
4490                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4491                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4492                Style);
4493 
4494   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4495 
4496   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4497   verifyFormat("SomeClassWithALongName::Constructor(\n"
4498                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4499                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4500                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4501                Style);
4502 
4503   Style.AllowAllConstructorInitializersOnNextLine = true;
4504   verifyFormat("SomeClassWithALongName::Constructor(\n"
4505                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4506                "    int bbbbbbbbbbbbb,\n"
4507                "    int cccccccccccccccc)\n"
4508                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4509                Style);
4510 
4511   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4512   Style.AllowAllConstructorInitializersOnNextLine = false;
4513   verifyFormat("SomeClassWithALongName::Constructor(\n"
4514                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4515                "    int bbbbbbbbbbbbb)\n"
4516                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4517                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4518                Style);
4519 
4520   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4521   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4522   verifyFormat("SomeClassWithALongName::Constructor(\n"
4523                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
4524                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4525                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4526                Style);
4527 
4528   Style.AllowAllConstructorInitializersOnNextLine = true;
4529   verifyFormat("SomeClassWithALongName::Constructor(\n"
4530                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4531                "    int bbbbbbbbbbbbb,\n"
4532                "    int cccccccccccccccc) :\n"
4533                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4534                Style);
4535 
4536   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4537   Style.AllowAllConstructorInitializersOnNextLine = false;
4538   verifyFormat("SomeClassWithALongName::Constructor(\n"
4539                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4540                "    int bbbbbbbbbbbbb) :\n"
4541                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4542                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4543                Style);
4544 }
4545 
TEST_F(FormatTest,AllowAllArgumentsOnNextLine)4546 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
4547   FormatStyle Style = getLLVMStyle();
4548   Style.ColumnLimit = 60;
4549   Style.BinPackArguments = false;
4550   for (int i = 0; i < 4; ++i) {
4551     // Test all combinations of parameters that should not have an effect.
4552     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4553     Style.AllowAllConstructorInitializersOnNextLine = i & 2;
4554 
4555     Style.AllowAllArgumentsOnNextLine = true;
4556     verifyFormat("void foo() {\n"
4557                  "  FunctionCallWithReallyLongName(\n"
4558                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
4559                  "}",
4560                  Style);
4561     Style.AllowAllArgumentsOnNextLine = false;
4562     verifyFormat("void foo() {\n"
4563                  "  FunctionCallWithReallyLongName(\n"
4564                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4565                  "      bbbbbbbbbbbb);\n"
4566                  "}",
4567                  Style);
4568 
4569     Style.AllowAllArgumentsOnNextLine = true;
4570     verifyFormat("void foo() {\n"
4571                  "  auto VariableWithReallyLongName = {\n"
4572                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
4573                  "}",
4574                  Style);
4575     Style.AllowAllArgumentsOnNextLine = false;
4576     verifyFormat("void foo() {\n"
4577                  "  auto VariableWithReallyLongName = {\n"
4578                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4579                  "      bbbbbbbbbbbb};\n"
4580                  "}",
4581                  Style);
4582   }
4583 
4584   // This parameter should not affect declarations.
4585   Style.BinPackParameters = false;
4586   Style.AllowAllArgumentsOnNextLine = false;
4587   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4588   verifyFormat("void FunctionCallWithReallyLongName(\n"
4589                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
4590                Style);
4591   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4592   verifyFormat("void FunctionCallWithReallyLongName(\n"
4593                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
4594                "    int bbbbbbbbbbbb);",
4595                Style);
4596 }
4597 
TEST_F(FormatTest,BreakConstructorInitializersAfterColon)4598 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
4599   FormatStyle Style = getLLVMStyle();
4600   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4601 
4602   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
4603   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
4604                getStyleWithColumns(Style, 45));
4605   verifyFormat("Constructor() :\n"
4606                "    Initializer(FitsOnTheLine) {}",
4607                getStyleWithColumns(Style, 44));
4608   verifyFormat("Constructor() :\n"
4609                "    Initializer(FitsOnTheLine) {}",
4610                getStyleWithColumns(Style, 43));
4611 
4612   verifyFormat("template <typename T>\n"
4613                "Constructor() : Initializer(FitsOnTheLine) {}",
4614                getStyleWithColumns(Style, 50));
4615   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4616   verifyFormat(
4617       "SomeClass::Constructor() :\n"
4618       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
4619       Style);
4620 
4621   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
4622   verifyFormat(
4623       "SomeClass::Constructor() :\n"
4624       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
4625       Style);
4626 
4627   verifyFormat(
4628       "SomeClass::Constructor() :\n"
4629       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4630       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4631       Style);
4632   verifyFormat(
4633       "SomeClass::Constructor() :\n"
4634       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4635       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
4636       Style);
4637   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4638                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
4639                "    aaaaaaaaaa(aaaaaa) {}",
4640                Style);
4641 
4642   verifyFormat("Constructor() :\n"
4643                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4644                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4645                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4646                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
4647                Style);
4648 
4649   verifyFormat("Constructor() :\n"
4650                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4651                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4652                Style);
4653 
4654   verifyFormat("Constructor(int Parameter = 0) :\n"
4655                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
4656                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
4657                Style);
4658   verifyFormat("Constructor() :\n"
4659                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
4660                "}",
4661                getStyleWithColumns(Style, 60));
4662   verifyFormat("Constructor() :\n"
4663                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4664                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
4665                Style);
4666 
4667   // Here a line could be saved by splitting the second initializer onto two
4668   // lines, but that is not desirable.
4669   verifyFormat("Constructor() :\n"
4670                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
4671                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
4672                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4673                Style);
4674 
4675   FormatStyle OnePerLine = Style;
4676   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4677   OnePerLine.AllowAllConstructorInitializersOnNextLine = false;
4678   verifyFormat("SomeClass::Constructor() :\n"
4679                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4680                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4681                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4682                OnePerLine);
4683   verifyFormat("SomeClass::Constructor() :\n"
4684                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
4685                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4686                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4687                OnePerLine);
4688   verifyFormat("MyClass::MyClass(int var) :\n"
4689                "    some_var_(var),            // 4 space indent\n"
4690                "    some_other_var_(var + 1) { // lined up\n"
4691                "}",
4692                OnePerLine);
4693   verifyFormat("Constructor() :\n"
4694                "    aaaaa(aaaaaa),\n"
4695                "    aaaaa(aaaaaa),\n"
4696                "    aaaaa(aaaaaa),\n"
4697                "    aaaaa(aaaaaa),\n"
4698                "    aaaaa(aaaaaa) {}",
4699                OnePerLine);
4700   verifyFormat("Constructor() :\n"
4701                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
4702                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
4703                OnePerLine);
4704   OnePerLine.BinPackParameters = false;
4705   verifyFormat("Constructor() :\n"
4706                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4707                "        aaaaaaaaaaa().aaa(),\n"
4708                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4709                OnePerLine);
4710   OnePerLine.ColumnLimit = 60;
4711   verifyFormat("Constructor() :\n"
4712                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4713                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
4714                OnePerLine);
4715 
4716   EXPECT_EQ("Constructor() :\n"
4717             "    // Comment forcing unwanted break.\n"
4718             "    aaaa(aaaa) {}",
4719             format("Constructor() :\n"
4720                    "    // Comment forcing unwanted break.\n"
4721                    "    aaaa(aaaa) {}",
4722                    Style));
4723 
4724   Style.ColumnLimit = 0;
4725   verifyFormat("SomeClass::Constructor() :\n"
4726                "    a(a) {}",
4727                Style);
4728   verifyFormat("SomeClass::Constructor() noexcept :\n"
4729                "    a(a) {}",
4730                Style);
4731   verifyFormat("SomeClass::Constructor() :\n"
4732                "    a(a), b(b), c(c) {}",
4733                Style);
4734   verifyFormat("SomeClass::Constructor() :\n"
4735                "    a(a) {\n"
4736                "  foo();\n"
4737                "  bar();\n"
4738                "}",
4739                Style);
4740 
4741   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
4742   verifyFormat("SomeClass::Constructor() :\n"
4743                "    a(a), b(b), c(c) {\n"
4744                "}",
4745                Style);
4746   verifyFormat("SomeClass::Constructor() :\n"
4747                "    a(a) {\n"
4748                "}",
4749                Style);
4750 
4751   Style.ColumnLimit = 80;
4752   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
4753   Style.ConstructorInitializerIndentWidth = 2;
4754   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
4755   verifyFormat("SomeClass::Constructor() :\n"
4756                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4757                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
4758                Style);
4759 
4760   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
4761   // well
4762   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
4763   verifyFormat(
4764       "class SomeClass\n"
4765       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4766       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
4767       Style);
4768   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
4769   verifyFormat(
4770       "class SomeClass\n"
4771       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4772       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
4773       Style);
4774   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
4775   verifyFormat(
4776       "class SomeClass :\n"
4777       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4778       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
4779       Style);
4780 }
4781 
4782 #ifndef EXPENSIVE_CHECKS
4783 // Expensive checks enables libstdc++ checking which includes validating the
4784 // state of ranges used in std::priority_queue - this blows out the
4785 // runtime/scalability of the function and makes this test unacceptably slow.
TEST_F(FormatTest,MemoizationTests)4786 TEST_F(FormatTest, MemoizationTests) {
4787   // This breaks if the memoization lookup does not take \c Indent and
4788   // \c LastSpace into account.
4789   verifyFormat(
4790       "extern CFRunLoopTimerRef\n"
4791       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
4792       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
4793       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
4794       "                     CFRunLoopTimerContext *context) {}");
4795 
4796   // Deep nesting somewhat works around our memoization.
4797   verifyFormat(
4798       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
4799       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
4800       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
4801       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
4802       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
4803       getLLVMStyleWithColumns(65));
4804   verifyFormat(
4805       "aaaaa(\n"
4806       "    aaaaa,\n"
4807       "    aaaaa(\n"
4808       "        aaaaa,\n"
4809       "        aaaaa(\n"
4810       "            aaaaa,\n"
4811       "            aaaaa(\n"
4812       "                aaaaa,\n"
4813       "                aaaaa(\n"
4814       "                    aaaaa,\n"
4815       "                    aaaaa(\n"
4816       "                        aaaaa,\n"
4817       "                        aaaaa(\n"
4818       "                            aaaaa,\n"
4819       "                            aaaaa(\n"
4820       "                                aaaaa,\n"
4821       "                                aaaaa(\n"
4822       "                                    aaaaa,\n"
4823       "                                    aaaaa(\n"
4824       "                                        aaaaa,\n"
4825       "                                        aaaaa(\n"
4826       "                                            aaaaa,\n"
4827       "                                            aaaaa(\n"
4828       "                                                aaaaa,\n"
4829       "                                                aaaaa))))))))))));",
4830       getLLVMStyleWithColumns(65));
4831   verifyFormat(
4832       "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"
4833       "                                  a),\n"
4834       "                                a),\n"
4835       "                              a),\n"
4836       "                            a),\n"
4837       "                          a),\n"
4838       "                        a),\n"
4839       "                      a),\n"
4840       "                    a),\n"
4841       "                  a),\n"
4842       "                a),\n"
4843       "              a),\n"
4844       "            a),\n"
4845       "          a),\n"
4846       "        a),\n"
4847       "      a),\n"
4848       "    a),\n"
4849       "  a)",
4850       getLLVMStyleWithColumns(65));
4851 
4852   // This test takes VERY long when memoization is broken.
4853   FormatStyle OnePerLine = getLLVMStyle();
4854   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4855   OnePerLine.BinPackParameters = false;
4856   std::string input = "Constructor()\n"
4857                       "    : aaaa(a,\n";
4858   for (unsigned i = 0, e = 80; i != e; ++i) {
4859     input += "           a,\n";
4860   }
4861   input += "           a) {}";
4862   verifyFormat(input, OnePerLine);
4863 }
4864 #endif
4865 
TEST_F(FormatTest,BreaksAsHighAsPossible)4866 TEST_F(FormatTest, BreaksAsHighAsPossible) {
4867   verifyFormat(
4868       "void f() {\n"
4869       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
4870       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
4871       "    f();\n"
4872       "}");
4873   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
4874                "    Intervals[i - 1].getRange().getLast()) {\n}");
4875 }
4876 
TEST_F(FormatTest,BreaksFunctionDeclarations)4877 TEST_F(FormatTest, BreaksFunctionDeclarations) {
4878   // Principially, we break function declarations in a certain order:
4879   // 1) break amongst arguments.
4880   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
4881                "                              Cccccccccccccc cccccccccccccc);");
4882   verifyFormat("template <class TemplateIt>\n"
4883                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
4884                "                            TemplateIt *stop) {}");
4885 
4886   // 2) break after return type.
4887   verifyFormat(
4888       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4889       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
4890       getGoogleStyle());
4891 
4892   // 3) break after (.
4893   verifyFormat(
4894       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
4895       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
4896       getGoogleStyle());
4897 
4898   // 4) break before after nested name specifiers.
4899   verifyFormat(
4900       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4901       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
4902       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
4903       getGoogleStyle());
4904 
4905   // However, there are exceptions, if a sufficient amount of lines can be
4906   // saved.
4907   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
4908   // more adjusting.
4909   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
4910                "                                  Cccccccccccccc cccccccccc,\n"
4911                "                                  Cccccccccccccc cccccccccc,\n"
4912                "                                  Cccccccccccccc cccccccccc,\n"
4913                "                                  Cccccccccccccc cccccccccc);");
4914   verifyFormat(
4915       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4916       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
4917       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
4918       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
4919       getGoogleStyle());
4920   verifyFormat(
4921       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
4922       "                                          Cccccccccccccc cccccccccc,\n"
4923       "                                          Cccccccccccccc cccccccccc,\n"
4924       "                                          Cccccccccccccc cccccccccc,\n"
4925       "                                          Cccccccccccccc cccccccccc,\n"
4926       "                                          Cccccccccccccc cccccccccc,\n"
4927       "                                          Cccccccccccccc cccccccccc);");
4928   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
4929                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
4930                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
4931                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
4932                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
4933 
4934   // Break after multi-line parameters.
4935   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4936                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4937                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4938                "    bbbb bbbb);");
4939   verifyFormat("void SomeLoooooooooooongFunction(\n"
4940                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
4941                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4942                "    int bbbbbbbbbbbbb);");
4943 
4944   // Treat overloaded operators like other functions.
4945   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
4946                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
4947   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
4948                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
4949   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
4950                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
4951   verifyGoogleFormat(
4952       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
4953       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
4954   verifyGoogleFormat(
4955       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
4956       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
4957   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4958                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
4959   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
4960                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
4961   verifyGoogleFormat(
4962       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
4963       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4964       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
4965   verifyGoogleFormat("template <typename T>\n"
4966                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4967                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
4968                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
4969 
4970   FormatStyle Style = getLLVMStyle();
4971   Style.PointerAlignment = FormatStyle::PAS_Left;
4972   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4973                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
4974                Style);
4975   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
4976                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4977                Style);
4978 }
4979 
TEST_F(FormatTest,DontBreakBeforeQualifiedOperator)4980 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
4981   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
4982   // Prefer keeping `::` followed by `operator` together.
4983   EXPECT_EQ("const aaaa::bbbbbbb &\n"
4984             "ccccccccc::operator++() {\n"
4985             "  stuff();\n"
4986             "}",
4987             format("const aaaa::bbbbbbb\n"
4988                    "&ccccccccc::operator++() { stuff(); }",
4989                    getLLVMStyleWithColumns(40)));
4990 }
4991 
TEST_F(FormatTest,TrailingReturnType)4992 TEST_F(FormatTest, TrailingReturnType) {
4993   verifyFormat("auto foo() -> int;\n");
4994   // correct trailing return type spacing
4995   verifyFormat("auto operator->() -> int;\n");
4996   verifyFormat("auto operator++(int) -> int;\n");
4997 
4998   verifyFormat("struct S {\n"
4999                "  auto bar() const -> int;\n"
5000                "};");
5001   verifyFormat("template <size_t Order, typename T>\n"
5002                "auto load_img(const std::string &filename)\n"
5003                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
5004   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
5005                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
5006   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
5007   verifyFormat("template <typename T>\n"
5008                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
5009                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
5010 
5011   // Not trailing return types.
5012   verifyFormat("void f() { auto a = b->c(); }");
5013 }
5014 
TEST_F(FormatTest,DeductionGuides)5015 TEST_F(FormatTest, DeductionGuides) {
5016   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
5017   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
5018   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
5019   verifyFormat(
5020       "template <class... T>\n"
5021       "array(T &&... t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
5022   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
5023   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
5024   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
5025   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
5026   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
5027   verifyFormat("template <class T> x() -> x<1>;");
5028   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
5029 
5030   // Ensure not deduction guides.
5031   verifyFormat("c()->f<int>();");
5032   verifyFormat("x()->foo<1>;");
5033   verifyFormat("x = p->foo<3>();");
5034   verifyFormat("x()->x<1>();");
5035   verifyFormat("x()->x<1>;");
5036 }
5037 
TEST_F(FormatTest,BreaksFunctionDeclarationsWithTrailingTokens)5038 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
5039   // Avoid breaking before trailing 'const' or other trailing annotations, if
5040   // they are not function-like.
5041   FormatStyle Style = getGoogleStyle();
5042   Style.ColumnLimit = 47;
5043   verifyFormat("void someLongFunction(\n"
5044                "    int someLoooooooooooooongParameter) const {\n}",
5045                getLLVMStyleWithColumns(47));
5046   verifyFormat("LoooooongReturnType\n"
5047                "someLoooooooongFunction() const {}",
5048                getLLVMStyleWithColumns(47));
5049   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
5050                "    const {}",
5051                Style);
5052   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5053                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
5054   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5055                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
5056   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5057                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
5058   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
5059                "                   aaaaaaaaaaa aaaaa) const override;");
5060   verifyGoogleFormat(
5061       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5062       "    const override;");
5063 
5064   // Even if the first parameter has to be wrapped.
5065   verifyFormat("void someLongFunction(\n"
5066                "    int someLongParameter) const {}",
5067                getLLVMStyleWithColumns(46));
5068   verifyFormat("void someLongFunction(\n"
5069                "    int someLongParameter) const {}",
5070                Style);
5071   verifyFormat("void someLongFunction(\n"
5072                "    int someLongParameter) override {}",
5073                Style);
5074   verifyFormat("void someLongFunction(\n"
5075                "    int someLongParameter) OVERRIDE {}",
5076                Style);
5077   verifyFormat("void someLongFunction(\n"
5078                "    int someLongParameter) final {}",
5079                Style);
5080   verifyFormat("void someLongFunction(\n"
5081                "    int someLongParameter) FINAL {}",
5082                Style);
5083   verifyFormat("void someLongFunction(\n"
5084                "    int parameter) const override {}",
5085                Style);
5086 
5087   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
5088   verifyFormat("void someLongFunction(\n"
5089                "    int someLongParameter) const\n"
5090                "{\n"
5091                "}",
5092                Style);
5093 
5094   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
5095   verifyFormat("void someLongFunction(\n"
5096                "    int someLongParameter) const\n"
5097                "  {\n"
5098                "  }",
5099                Style);
5100 
5101   // Unless these are unknown annotations.
5102   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
5103                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5104                "    LONG_AND_UGLY_ANNOTATION;");
5105 
5106   // Breaking before function-like trailing annotations is fine to keep them
5107   // close to their arguments.
5108   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5109                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5110   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5111                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5112   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5113                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
5114   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
5115                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
5116   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
5117 
5118   verifyFormat(
5119       "void aaaaaaaaaaaaaaaaaa()\n"
5120       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
5121       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
5122   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5123                "    __attribute__((unused));");
5124   verifyGoogleFormat(
5125       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5126       "    GUARDED_BY(aaaaaaaaaaaa);");
5127   verifyGoogleFormat(
5128       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5129       "    GUARDED_BY(aaaaaaaaaaaa);");
5130   verifyGoogleFormat(
5131       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5132       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5133   verifyGoogleFormat(
5134       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5135       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
5136 }
5137 
TEST_F(FormatTest,FunctionAnnotations)5138 TEST_F(FormatTest, FunctionAnnotations) {
5139   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5140                "int OldFunction(const string &parameter) {}");
5141   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5142                "string OldFunction(const string &parameter) {}");
5143   verifyFormat("template <typename T>\n"
5144                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5145                "string OldFunction(const string &parameter) {}");
5146 
5147   // Not function annotations.
5148   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5149                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
5150   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
5151                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
5152   verifyFormat("MACRO(abc).function() // wrap\n"
5153                "    << abc;");
5154   verifyFormat("MACRO(abc)->function() // wrap\n"
5155                "    << abc;");
5156   verifyFormat("MACRO(abc)::function() // wrap\n"
5157                "    << abc;");
5158 }
5159 
TEST_F(FormatTest,BreaksDesireably)5160 TEST_F(FormatTest, BreaksDesireably) {
5161   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5162                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5163                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
5164   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5165                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
5166                "}");
5167 
5168   verifyFormat(
5169       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5170       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5171 
5172   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5173                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5174                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5175 
5176   verifyFormat(
5177       "aaaaaaaa(aaaaaaaaaaaaa,\n"
5178       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5179       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5180       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5181       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
5182 
5183   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5184                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5185 
5186   verifyFormat(
5187       "void f() {\n"
5188       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
5189       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5190       "}");
5191   verifyFormat(
5192       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5193       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5194   verifyFormat(
5195       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5196       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5197   verifyFormat(
5198       "aaaaaa(aaa,\n"
5199       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5200       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5201       "       aaaa);");
5202   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5203                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5204                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5205 
5206   // Indent consistently independent of call expression and unary operator.
5207   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5208                "    dddddddddddddddddddddddddddddd));");
5209   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5210                "    dddddddddddddddddddddddddddddd));");
5211   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
5212                "    dddddddddddddddddddddddddddddd));");
5213 
5214   // This test case breaks on an incorrect memoization, i.e. an optimization not
5215   // taking into account the StopAt value.
5216   verifyFormat(
5217       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5218       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5219       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5220       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5221 
5222   verifyFormat("{\n  {\n    {\n"
5223                "      Annotation.SpaceRequiredBefore =\n"
5224                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
5225                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
5226                "    }\n  }\n}");
5227 
5228   // Break on an outer level if there was a break on an inner level.
5229   EXPECT_EQ("f(g(h(a, // comment\n"
5230             "      b, c),\n"
5231             "    d, e),\n"
5232             "  x, y);",
5233             format("f(g(h(a, // comment\n"
5234                    "    b, c), d, e), x, y);"));
5235 
5236   // Prefer breaking similar line breaks.
5237   verifyFormat(
5238       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
5239       "                             NSTrackingMouseEnteredAndExited |\n"
5240       "                             NSTrackingActiveAlways;");
5241 }
5242 
TEST_F(FormatTest,FormatsDeclarationsOnePerLine)5243 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
5244   FormatStyle NoBinPacking = getGoogleStyle();
5245   NoBinPacking.BinPackParameters = false;
5246   NoBinPacking.BinPackArguments = true;
5247   verifyFormat("void f() {\n"
5248                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
5249                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5250                "}",
5251                NoBinPacking);
5252   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
5253                "       int aaaaaaaaaaaaaaaaaaaa,\n"
5254                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5255                NoBinPacking);
5256 
5257   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5258   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5259                "                        vector<int> bbbbbbbbbbbbbbb);",
5260                NoBinPacking);
5261   // FIXME: This behavior difference is probably not wanted. However, currently
5262   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
5263   // template arguments from BreakBeforeParameter being set because of the
5264   // one-per-line formatting.
5265   verifyFormat(
5266       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5267       "                                             aaaaaaaaaa> aaaaaaaaaa);",
5268       NoBinPacking);
5269   verifyFormat(
5270       "void fffffffffff(\n"
5271       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
5272       "        aaaaaaaaaa);");
5273 }
5274 
TEST_F(FormatTest,FormatsOneParameterPerLineIfNecessary)5275 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
5276   FormatStyle NoBinPacking = getGoogleStyle();
5277   NoBinPacking.BinPackParameters = false;
5278   NoBinPacking.BinPackArguments = false;
5279   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
5280                "  aaaaaaaaaaaaaaaaaaaa,\n"
5281                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
5282                NoBinPacking);
5283   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
5284                "        aaaaaaaaaaaaa,\n"
5285                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
5286                NoBinPacking);
5287   verifyFormat(
5288       "aaaaaaaa(aaaaaaaaaaaaa,\n"
5289       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5290       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5291       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5292       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
5293       NoBinPacking);
5294   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5295                "    .aaaaaaaaaaaaaaaaaa();",
5296                NoBinPacking);
5297   verifyFormat("void f() {\n"
5298                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5299                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
5300                "}",
5301                NoBinPacking);
5302 
5303   verifyFormat(
5304       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5305       "             aaaaaaaaaaaa,\n"
5306       "             aaaaaaaaaaaa);",
5307       NoBinPacking);
5308   verifyFormat(
5309       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
5310       "                               ddddddddddddddddddddddddddddd),\n"
5311       "             test);",
5312       NoBinPacking);
5313 
5314   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5315                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
5316                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
5317                "    aaaaaaaaaaaaaaaaaa;",
5318                NoBinPacking);
5319   verifyFormat("a(\"a\"\n"
5320                "  \"a\",\n"
5321                "  a);");
5322 
5323   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5324   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
5325                "                aaaaaaaaa,\n"
5326                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5327                NoBinPacking);
5328   verifyFormat(
5329       "void f() {\n"
5330       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5331       "      .aaaaaaa();\n"
5332       "}",
5333       NoBinPacking);
5334   verifyFormat(
5335       "template <class SomeType, class SomeOtherType>\n"
5336       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
5337       NoBinPacking);
5338 }
5339 
TEST_F(FormatTest,AdaptiveOnePerLineFormatting)5340 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
5341   FormatStyle Style = getLLVMStyleWithColumns(15);
5342   Style.ExperimentalAutoDetectBinPacking = true;
5343   EXPECT_EQ("aaa(aaaa,\n"
5344             "    aaaa,\n"
5345             "    aaaa);\n"
5346             "aaa(aaaa,\n"
5347             "    aaaa,\n"
5348             "    aaaa);",
5349             format("aaa(aaaa,\n" // one-per-line
5350                    "  aaaa,\n"
5351                    "    aaaa  );\n"
5352                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
5353                    Style));
5354   EXPECT_EQ("aaa(aaaa, aaaa,\n"
5355             "    aaaa);\n"
5356             "aaa(aaaa, aaaa,\n"
5357             "    aaaa);",
5358             format("aaa(aaaa,  aaaa,\n" // bin-packed
5359                    "    aaaa  );\n"
5360                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
5361                    Style));
5362 }
5363 
TEST_F(FormatTest,FormatsBuilderPattern)5364 TEST_F(FormatTest, FormatsBuilderPattern) {
5365   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
5366                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
5367                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
5368                "    .StartsWith(\".init\", ORDER_INIT)\n"
5369                "    .StartsWith(\".fini\", ORDER_FINI)\n"
5370                "    .StartsWith(\".hash\", ORDER_HASH)\n"
5371                "    .Default(ORDER_TEXT);\n");
5372 
5373   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
5374                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
5375   verifyFormat("aaaaaaa->aaaaaaa\n"
5376                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5377                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5378                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5379   verifyFormat(
5380       "aaaaaaa->aaaaaaa\n"
5381       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5382       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5383   verifyFormat(
5384       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
5385       "    aaaaaaaaaaaaaa);");
5386   verifyFormat(
5387       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
5388       "    aaaaaa->aaaaaaaaaaaa()\n"
5389       "        ->aaaaaaaaaaaaaaaa(\n"
5390       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5391       "        ->aaaaaaaaaaaaaaaaa();");
5392   verifyGoogleFormat(
5393       "void f() {\n"
5394       "  someo->Add((new util::filetools::Handler(dir))\n"
5395       "                 ->OnEvent1(NewPermanentCallback(\n"
5396       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
5397       "                 ->OnEvent2(NewPermanentCallback(\n"
5398       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
5399       "                 ->OnEvent3(NewPermanentCallback(\n"
5400       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
5401       "                 ->OnEvent5(NewPermanentCallback(\n"
5402       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
5403       "                 ->OnEvent6(NewPermanentCallback(\n"
5404       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
5405       "}");
5406 
5407   verifyFormat(
5408       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
5409   verifyFormat("aaaaaaaaaaaaaaa()\n"
5410                "    .aaaaaaaaaaaaaaa()\n"
5411                "    .aaaaaaaaaaaaaaa()\n"
5412                "    .aaaaaaaaaaaaaaa()\n"
5413                "    .aaaaaaaaaaaaaaa();");
5414   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5415                "    .aaaaaaaaaaaaaaa()\n"
5416                "    .aaaaaaaaaaaaaaa()\n"
5417                "    .aaaaaaaaaaaaaaa();");
5418   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5419                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5420                "    .aaaaaaaaaaaaaaa();");
5421   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
5422                "    ->aaaaaaaaaaaaaae(0)\n"
5423                "    ->aaaaaaaaaaaaaaa();");
5424 
5425   // Don't linewrap after very short segments.
5426   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5427                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5428                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5429   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5430                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5431                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5432   verifyFormat("aaa()\n"
5433                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5434                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5435                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5436 
5437   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5438                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5439                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
5440   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5441                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5442                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
5443 
5444   // Prefer not to break after empty parentheses.
5445   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
5446                "    First->LastNewlineOffset);");
5447 
5448   // Prefer not to create "hanging" indents.
5449   verifyFormat(
5450       "return !soooooooooooooome_map\n"
5451       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5452       "            .second;");
5453   verifyFormat(
5454       "return aaaaaaaaaaaaaaaa\n"
5455       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
5456       "    .aaaa(aaaaaaaaaaaaaa);");
5457   // No hanging indent here.
5458   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
5459                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5460   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
5461                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5462   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5463                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5464                getLLVMStyleWithColumns(60));
5465   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
5466                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5467                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5468                getLLVMStyleWithColumns(59));
5469   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5470                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5471                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5472 
5473   // Dont break if only closing statements before member call
5474   verifyFormat("test() {\n"
5475                "  ([]() -> {\n"
5476                "    int b = 32;\n"
5477                "    return 3;\n"
5478                "  }).foo();\n"
5479                "}");
5480   verifyFormat("test() {\n"
5481                "  (\n"
5482                "      []() -> {\n"
5483                "        int b = 32;\n"
5484                "        return 3;\n"
5485                "      },\n"
5486                "      foo, bar)\n"
5487                "      .foo();\n"
5488                "}");
5489   verifyFormat("test() {\n"
5490                "  ([]() -> {\n"
5491                "    int b = 32;\n"
5492                "    return 3;\n"
5493                "  })\n"
5494                "      .foo()\n"
5495                "      .bar();\n"
5496                "}");
5497   verifyFormat("test() {\n"
5498                "  ([]() -> {\n"
5499                "    int b = 32;\n"
5500                "    return 3;\n"
5501                "  })\n"
5502                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
5503                "           \"bbbb\");\n"
5504                "}",
5505                getLLVMStyleWithColumns(30));
5506 }
5507 
TEST_F(FormatTest,BreaksAccordingToOperatorPrecedence)5508 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
5509   verifyFormat(
5510       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5511       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
5512   verifyFormat(
5513       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
5514       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
5515 
5516   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5517                "    ccccccccccccccccccccccccc) {\n}");
5518   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
5519                "    ccccccccccccccccccccccccc) {\n}");
5520 
5521   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5522                "    ccccccccccccccccccccccccc) {\n}");
5523   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
5524                "    ccccccccccccccccccccccccc) {\n}");
5525 
5526   verifyFormat(
5527       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
5528       "    ccccccccccccccccccccccccc) {\n}");
5529   verifyFormat(
5530       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
5531       "    ccccccccccccccccccccccccc) {\n}");
5532 
5533   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
5534                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
5535                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
5536                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
5537   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
5538                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
5539                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
5540                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
5541 
5542   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
5543                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
5544                "    aaaaaaaaaaaaaaa != aa) {\n}");
5545   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
5546                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
5547                "    aaaaaaaaaaaaaaa != aa) {\n}");
5548 }
5549 
TEST_F(FormatTest,BreaksAfterAssignments)5550 TEST_F(FormatTest, BreaksAfterAssignments) {
5551   verifyFormat(
5552       "unsigned Cost =\n"
5553       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
5554       "                        SI->getPointerAddressSpaceee());\n");
5555   verifyFormat(
5556       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
5557       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
5558 
5559   verifyFormat(
5560       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
5561       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
5562   verifyFormat("unsigned OriginalStartColumn =\n"
5563                "    SourceMgr.getSpellingColumnNumber(\n"
5564                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
5565                "    1;");
5566 }
5567 
TEST_F(FormatTest,ConfigurableBreakAssignmentPenalty)5568 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
5569   FormatStyle Style = getLLVMStyle();
5570   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5571                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
5572                Style);
5573 
5574   Style.PenaltyBreakAssignment = 20;
5575   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
5576                "                                 cccccccccccccccccccccccccc;",
5577                Style);
5578 }
5579 
TEST_F(FormatTest,AlignsAfterAssignments)5580 TEST_F(FormatTest, AlignsAfterAssignments) {
5581   verifyFormat(
5582       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5583       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
5584   verifyFormat(
5585       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5586       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
5587   verifyFormat(
5588       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5589       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
5590   verifyFormat(
5591       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5592       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
5593   verifyFormat(
5594       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
5595       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
5596       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
5597 }
5598 
TEST_F(FormatTest,AlignsAfterReturn)5599 TEST_F(FormatTest, AlignsAfterReturn) {
5600   verifyFormat(
5601       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5602       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
5603   verifyFormat(
5604       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5605       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
5606   verifyFormat(
5607       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
5608       "       aaaaaaaaaaaaaaaaaaaaaa();");
5609   verifyFormat(
5610       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
5611       "        aaaaaaaaaaaaaaaaaaaaaa());");
5612   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5613                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5614   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5615                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
5616                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5617   verifyFormat("return\n"
5618                "    // true if code is one of a or b.\n"
5619                "    code == a || code == b;");
5620 }
5621 
TEST_F(FormatTest,AlignsAfterOpenBracket)5622 TEST_F(FormatTest, AlignsAfterOpenBracket) {
5623   verifyFormat(
5624       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
5625       "                                                aaaaaaaaa aaaaaaa) {}");
5626   verifyFormat(
5627       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
5628       "                                               aaaaaaaaaaa aaaaaaaaa);");
5629   verifyFormat(
5630       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
5631       "                                             aaaaaaaaaaaaaaaaaaaaa));");
5632   FormatStyle Style = getLLVMStyle();
5633   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5634   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5635                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
5636                Style);
5637   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
5638                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
5639                Style);
5640   verifyFormat("SomeLongVariableName->someFunction(\n"
5641                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
5642                Style);
5643   verifyFormat(
5644       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
5645       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5646       Style);
5647   verifyFormat(
5648       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
5649       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5650       Style);
5651   verifyFormat(
5652       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
5653       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
5654       Style);
5655 
5656   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
5657                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
5658                "        b));",
5659                Style);
5660 
5661   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5662   Style.BinPackArguments = false;
5663   Style.BinPackParameters = false;
5664   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5665                "    aaaaaaaaaaa aaaaaaaa,\n"
5666                "    aaaaaaaaa aaaaaaa,\n"
5667                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5668                Style);
5669   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
5670                "    aaaaaaaaaaa aaaaaaaaa,\n"
5671                "    aaaaaaaaaaa aaaaaaaaa,\n"
5672                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5673                Style);
5674   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
5675                "    aaaaaaaaaaaaaaa,\n"
5676                "    aaaaaaaaaaaaaaaaaaaaa,\n"
5677                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
5678                Style);
5679   verifyFormat(
5680       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
5681       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
5682       Style);
5683   verifyFormat(
5684       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
5685       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
5686       Style);
5687   verifyFormat(
5688       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5689       "    aaaaaaaaaaaaaaaaaaaaa(\n"
5690       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
5691       "    aaaaaaaaaaaaaaaa);",
5692       Style);
5693   verifyFormat(
5694       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5695       "    aaaaaaaaaaaaaaaaaaaaa(\n"
5696       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
5697       "    aaaaaaaaaaaaaaaa);",
5698       Style);
5699 }
5700 
TEST_F(FormatTest,ParenthesesAndOperandAlignment)5701 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
5702   FormatStyle Style = getLLVMStyleWithColumns(40);
5703   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
5704                "          bbbbbbbbbbbbbbbbbbbbbb);",
5705                Style);
5706   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5707   Style.AlignOperands = false;
5708   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
5709                "          bbbbbbbbbbbbbbbbbbbbbb);",
5710                Style);
5711   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5712   Style.AlignOperands = true;
5713   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
5714                "          bbbbbbbbbbbbbbbbbbbbbb);",
5715                Style);
5716   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5717   Style.AlignOperands = false;
5718   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
5719                "    bbbbbbbbbbbbbbbbbbbbbb);",
5720                Style);
5721 }
5722 
TEST_F(FormatTest,BreaksConditionalExpressions)5723 TEST_F(FormatTest, BreaksConditionalExpressions) {
5724   verifyFormat(
5725       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5726       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5727       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5728   verifyFormat(
5729       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
5730       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5731       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5732   verifyFormat(
5733       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5734       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5735   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
5736                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5737                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5738   verifyFormat(
5739       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
5740       "                                                    : aaaaaaaaaaaaa);");
5741   verifyFormat(
5742       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5743       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5744       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5745       "                   aaaaaaaaaaaaa);");
5746   verifyFormat(
5747       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5748       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5749       "                   aaaaaaaaaaaaa);");
5750   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5751                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5752                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5753                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5754                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5755   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5756                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5757                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5758                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5759                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5760                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5761                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5762   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5763                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5764                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5765                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5766                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5767   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5768                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5769                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5770   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
5771                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5772                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5773                "        : aaaaaaaaaaaaaaaa;");
5774   verifyFormat(
5775       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5776       "    ? aaaaaaaaaaaaaaa\n"
5777       "    : aaaaaaaaaaaaaaa;");
5778   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
5779                "          aaaaaaaaa\n"
5780                "      ? b\n"
5781                "      : c);");
5782   verifyFormat("return aaaa == bbbb\n"
5783                "           // comment\n"
5784                "           ? aaaa\n"
5785                "           : bbbb;");
5786   verifyFormat("unsigned Indent =\n"
5787                "    format(TheLine.First,\n"
5788                "           IndentForLevel[TheLine.Level] >= 0\n"
5789                "               ? IndentForLevel[TheLine.Level]\n"
5790                "               : TheLine * 2,\n"
5791                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
5792                getLLVMStyleWithColumns(60));
5793   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
5794                "                  ? aaaaaaaaaaaaaaa\n"
5795                "                  : bbbbbbbbbbbbbbb //\n"
5796                "                        ? ccccccccccccccc\n"
5797                "                        : ddddddddddddddd;");
5798   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
5799                "                  ? aaaaaaaaaaaaaaa\n"
5800                "                  : (bbbbbbbbbbbbbbb //\n"
5801                "                         ? ccccccccccccccc\n"
5802                "                         : ddddddddddddddd);");
5803   verifyFormat(
5804       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5805       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5806       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
5807       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
5808       "                                      : aaaaaaaaaa;");
5809   verifyFormat(
5810       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5811       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
5812       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5813 
5814   FormatStyle NoBinPacking = getLLVMStyle();
5815   NoBinPacking.BinPackArguments = false;
5816   verifyFormat(
5817       "void f() {\n"
5818       "  g(aaa,\n"
5819       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
5820       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5821       "        ? aaaaaaaaaaaaaaa\n"
5822       "        : aaaaaaaaaaaaaaa);\n"
5823       "}",
5824       NoBinPacking);
5825   verifyFormat(
5826       "void f() {\n"
5827       "  g(aaa,\n"
5828       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
5829       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5830       "        ?: aaaaaaaaaaaaaaa);\n"
5831       "}",
5832       NoBinPacking);
5833 
5834   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
5835                "             // comment.\n"
5836                "             ccccccccccccccccccccccccccccccccccccccc\n"
5837                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5838                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
5839 
5840   // Assignments in conditional expressions. Apparently not uncommon :-(.
5841   verifyFormat("return a != b\n"
5842                "           // comment\n"
5843                "           ? a = b\n"
5844                "           : a = b;");
5845   verifyFormat("return a != b\n"
5846                "           // comment\n"
5847                "           ? a = a != b\n"
5848                "                     // comment\n"
5849                "                     ? a = b\n"
5850                "                     : a\n"
5851                "           : a;\n");
5852   verifyFormat("return a != b\n"
5853                "           // comment\n"
5854                "           ? a\n"
5855                "           : a = a != b\n"
5856                "                     // comment\n"
5857                "                     ? a = b\n"
5858                "                     : a;");
5859 }
5860 
TEST_F(FormatTest,BreaksConditionalExpressionsAfterOperator)5861 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
5862   FormatStyle Style = getLLVMStyle();
5863   Style.BreakBeforeTernaryOperators = false;
5864   Style.ColumnLimit = 70;
5865   verifyFormat(
5866       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
5867       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
5868       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5869       Style);
5870   verifyFormat(
5871       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
5872       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
5873       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5874       Style);
5875   verifyFormat(
5876       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
5877       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5878       Style);
5879   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
5880                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
5881                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5882                Style);
5883   verifyFormat(
5884       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
5885       "                                                      aaaaaaaaaaaaa);",
5886       Style);
5887   verifyFormat(
5888       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5889       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
5890       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5891       "                   aaaaaaaaaaaaa);",
5892       Style);
5893   verifyFormat(
5894       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5895       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5896       "                   aaaaaaaaaaaaa);",
5897       Style);
5898   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
5899                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5900                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
5901                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5902                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5903                Style);
5904   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5905                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
5906                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5907                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
5908                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5909                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5910                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5911                Style);
5912   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5913                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
5914                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5915                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5916                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5917                Style);
5918   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
5919                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
5920                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5921                Style);
5922   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
5923                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
5924                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
5925                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5926                Style);
5927   verifyFormat(
5928       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
5929       "    aaaaaaaaaaaaaaa :\n"
5930       "    aaaaaaaaaaaaaaa;",
5931       Style);
5932   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
5933                "          aaaaaaaaa ?\n"
5934                "      b :\n"
5935                "      c);",
5936                Style);
5937   verifyFormat("unsigned Indent =\n"
5938                "    format(TheLine.First,\n"
5939                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
5940                "               IndentForLevel[TheLine.Level] :\n"
5941                "               TheLine * 2,\n"
5942                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
5943                Style);
5944   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
5945                "                  aaaaaaaaaaaaaaa :\n"
5946                "                  bbbbbbbbbbbbbbb ? //\n"
5947                "                      ccccccccccccccc :\n"
5948                "                      ddddddddddddddd;",
5949                Style);
5950   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
5951                "                  aaaaaaaaaaaaaaa :\n"
5952                "                  (bbbbbbbbbbbbbbb ? //\n"
5953                "                       ccccccccccccccc :\n"
5954                "                       ddddddddddddddd);",
5955                Style);
5956   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
5957                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
5958                "            ccccccccccccccccccccccccccc;",
5959                Style);
5960   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
5961                "           aaaaa :\n"
5962                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
5963                Style);
5964 }
5965 
TEST_F(FormatTest,DeclarationsOfMultipleVariables)5966 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
5967   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
5968                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
5969   verifyFormat("bool a = true, b = false;");
5970 
5971   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5972                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
5973                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
5974                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
5975   verifyFormat(
5976       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
5977       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
5978       "     d = e && f;");
5979   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
5980                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
5981   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
5982                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
5983   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
5984                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
5985 
5986   FormatStyle Style = getGoogleStyle();
5987   Style.PointerAlignment = FormatStyle::PAS_Left;
5988   Style.DerivePointerAlignment = false;
5989   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5990                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
5991                "    *b = bbbbbbbbbbbbbbbbbbb;",
5992                Style);
5993   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
5994                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
5995                Style);
5996   verifyFormat("vector<int*> a, b;", Style);
5997   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
5998 }
5999 
TEST_F(FormatTest,ConditionalExpressionsInBrackets)6000 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
6001   verifyFormat("arr[foo ? bar : baz];");
6002   verifyFormat("f()[foo ? bar : baz];");
6003   verifyFormat("(a + b)[foo ? bar : baz];");
6004   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
6005 }
6006 
TEST_F(FormatTest,AlignsStringLiterals)6007 TEST_F(FormatTest, AlignsStringLiterals) {
6008   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
6009                "                                      \"short literal\");");
6010   verifyFormat(
6011       "looooooooooooooooooooooooongFunction(\n"
6012       "    \"short literal\"\n"
6013       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
6014   verifyFormat("someFunction(\"Always break between multi-line\"\n"
6015                "             \" string literals\",\n"
6016                "             and, other, parameters);");
6017   EXPECT_EQ("fun + \"1243\" /* comment */\n"
6018             "      \"5678\";",
6019             format("fun + \"1243\" /* comment */\n"
6020                    "    \"5678\";",
6021                    getLLVMStyleWithColumns(28)));
6022   EXPECT_EQ(
6023       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
6024       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
6025       "         \"aaaaaaaaaaaaaaaa\";",
6026       format("aaaaaa ="
6027              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
6028              "aaaaaaaaaaaaaaaaaaaaa\" "
6029              "\"aaaaaaaaaaaaaaaa\";"));
6030   verifyFormat("a = a + \"a\"\n"
6031                "        \"a\"\n"
6032                "        \"a\";");
6033   verifyFormat("f(\"a\", \"b\"\n"
6034                "       \"c\");");
6035 
6036   verifyFormat(
6037       "#define LL_FORMAT \"ll\"\n"
6038       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
6039       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
6040 
6041   verifyFormat("#define A(X)          \\\n"
6042                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
6043                "  \"ccccc\"",
6044                getLLVMStyleWithColumns(23));
6045   verifyFormat("#define A \"def\"\n"
6046                "f(\"abc\" A \"ghi\"\n"
6047                "  \"jkl\");");
6048 
6049   verifyFormat("f(L\"a\"\n"
6050                "  L\"b\");");
6051   verifyFormat("#define A(X)            \\\n"
6052                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
6053                "  L\"ccccc\"",
6054                getLLVMStyleWithColumns(25));
6055 
6056   verifyFormat("f(@\"a\"\n"
6057                "  @\"b\");");
6058   verifyFormat("NSString s = @\"a\"\n"
6059                "             @\"b\"\n"
6060                "             @\"c\";");
6061   verifyFormat("NSString s = @\"a\"\n"
6062                "              \"b\"\n"
6063                "              \"c\";");
6064 }
6065 
TEST_F(FormatTest,ReturnTypeBreakingStyle)6066 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
6067   FormatStyle Style = getLLVMStyle();
6068   // No declarations or definitions should be moved to own line.
6069   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
6070   verifyFormat("class A {\n"
6071                "  int f() { return 1; }\n"
6072                "  int g();\n"
6073                "};\n"
6074                "int f() { return 1; }\n"
6075                "int g();\n",
6076                Style);
6077 
6078   // All declarations and definitions should have the return type moved to its
6079   // own
6080   // line.
6081   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
6082   verifyFormat("class E {\n"
6083                "  int\n"
6084                "  f() {\n"
6085                "    return 1;\n"
6086                "  }\n"
6087                "  int\n"
6088                "  g();\n"
6089                "};\n"
6090                "int\n"
6091                "f() {\n"
6092                "  return 1;\n"
6093                "}\n"
6094                "int\n"
6095                "g();\n",
6096                Style);
6097 
6098   // Top-level definitions, and no kinds of declarations should have the
6099   // return type moved to its own line.
6100   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
6101   verifyFormat("class B {\n"
6102                "  int f() { return 1; }\n"
6103                "  int g();\n"
6104                "};\n"
6105                "int\n"
6106                "f() {\n"
6107                "  return 1;\n"
6108                "}\n"
6109                "int g();\n",
6110                Style);
6111 
6112   // Top-level definitions and declarations should have the return type moved
6113   // to its own line.
6114   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
6115   verifyFormat("class C {\n"
6116                "  int f() { return 1; }\n"
6117                "  int g();\n"
6118                "};\n"
6119                "int\n"
6120                "f() {\n"
6121                "  return 1;\n"
6122                "}\n"
6123                "int\n"
6124                "g();\n",
6125                Style);
6126 
6127   // All definitions should have the return type moved to its own line, but no
6128   // kinds of declarations.
6129   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
6130   verifyFormat("class D {\n"
6131                "  int\n"
6132                "  f() {\n"
6133                "    return 1;\n"
6134                "  }\n"
6135                "  int g();\n"
6136                "};\n"
6137                "int\n"
6138                "f() {\n"
6139                "  return 1;\n"
6140                "}\n"
6141                "int g();\n",
6142                Style);
6143   verifyFormat("const char *\n"
6144                "f(void) {\n" // Break here.
6145                "  return \"\";\n"
6146                "}\n"
6147                "const char *bar(void);\n", // No break here.
6148                Style);
6149   verifyFormat("template <class T>\n"
6150                "T *\n"
6151                "f(T &c) {\n" // Break here.
6152                "  return NULL;\n"
6153                "}\n"
6154                "template <class T> T *f(T &c);\n", // No break here.
6155                Style);
6156   verifyFormat("class C {\n"
6157                "  int\n"
6158                "  operator+() {\n"
6159                "    return 1;\n"
6160                "  }\n"
6161                "  int\n"
6162                "  operator()() {\n"
6163                "    return 1;\n"
6164                "  }\n"
6165                "};\n",
6166                Style);
6167   verifyFormat("void\n"
6168                "A::operator()() {}\n"
6169                "void\n"
6170                "A::operator>>() {}\n"
6171                "void\n"
6172                "A::operator+() {}\n"
6173                "void\n"
6174                "A::operator*() {}\n"
6175                "void\n"
6176                "A::operator->() {}\n"
6177                "void\n"
6178                "A::operator void *() {}\n"
6179                "void\n"
6180                "A::operator void &() {}\n"
6181                "void\n"
6182                "A::operator void &&() {}\n"
6183                "void\n"
6184                "A::operator char *() {}\n"
6185                "void\n"
6186                "A::operator[]() {}\n"
6187                "void\n"
6188                "A::operator!() {}\n"
6189                "void\n"
6190                "A::operator**() {}\n"
6191                "void\n"
6192                "A::operator<Foo> *() {}\n"
6193                "void\n"
6194                "A::operator<Foo> **() {}\n"
6195                "void\n"
6196                "A::operator<Foo> &() {}\n"
6197                "void\n"
6198                "A::operator void **() {}\n",
6199                Style);
6200   verifyFormat("constexpr auto\n"
6201                "operator()() const -> reference {}\n"
6202                "constexpr auto\n"
6203                "operator>>() const -> reference {}\n"
6204                "constexpr auto\n"
6205                "operator+() const -> reference {}\n"
6206                "constexpr auto\n"
6207                "operator*() const -> reference {}\n"
6208                "constexpr auto\n"
6209                "operator->() const -> reference {}\n"
6210                "constexpr auto\n"
6211                "operator++() const -> reference {}\n"
6212                "constexpr auto\n"
6213                "operator void *() const -> reference {}\n"
6214                "constexpr auto\n"
6215                "operator void **() const -> reference {}\n"
6216                "constexpr auto\n"
6217                "operator void *() const -> reference {}\n"
6218                "constexpr auto\n"
6219                "operator void &() const -> reference {}\n"
6220                "constexpr auto\n"
6221                "operator void &&() const -> reference {}\n"
6222                "constexpr auto\n"
6223                "operator char *() const -> reference {}\n"
6224                "constexpr auto\n"
6225                "operator!() const -> reference {}\n"
6226                "constexpr auto\n"
6227                "operator[]() const -> reference {}\n",
6228                Style);
6229   verifyFormat("void *operator new(std::size_t s);", // No break here.
6230                Style);
6231   verifyFormat("void *\n"
6232                "operator new(std::size_t s) {}",
6233                Style);
6234   verifyFormat("void *\n"
6235                "operator delete[](void *ptr) {}",
6236                Style);
6237   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
6238   verifyFormat("const char *\n"
6239                "f(void)\n" // Break here.
6240                "{\n"
6241                "  return \"\";\n"
6242                "}\n"
6243                "const char *bar(void);\n", // No break here.
6244                Style);
6245   verifyFormat("template <class T>\n"
6246                "T *\n"     // Problem here: no line break
6247                "f(T &c)\n" // Break here.
6248                "{\n"
6249                "  return NULL;\n"
6250                "}\n"
6251                "template <class T> T *f(T &c);\n", // No break here.
6252                Style);
6253   verifyFormat("int\n"
6254                "foo(A<bool> a)\n"
6255                "{\n"
6256                "  return a;\n"
6257                "}\n",
6258                Style);
6259   verifyFormat("int\n"
6260                "foo(A<8> a)\n"
6261                "{\n"
6262                "  return a;\n"
6263                "}\n",
6264                Style);
6265   verifyFormat("int\n"
6266                "foo(A<B<bool>, 8> a)\n"
6267                "{\n"
6268                "  return a;\n"
6269                "}\n",
6270                Style);
6271   verifyFormat("int\n"
6272                "foo(A<B<8>, bool> a)\n"
6273                "{\n"
6274                "  return a;\n"
6275                "}\n",
6276                Style);
6277   verifyFormat("int\n"
6278                "foo(A<B<bool>, bool> a)\n"
6279                "{\n"
6280                "  return a;\n"
6281                "}\n",
6282                Style);
6283   verifyFormat("int\n"
6284                "foo(A<B<8>, 8> a)\n"
6285                "{\n"
6286                "  return a;\n"
6287                "}\n",
6288                Style);
6289 
6290   Style = getGNUStyle();
6291 
6292   // Test for comments at the end of function declarations.
6293   verifyFormat("void\n"
6294                "foo (int a, /*abc*/ int b) // def\n"
6295                "{\n"
6296                "}\n",
6297                Style);
6298 
6299   verifyFormat("void\n"
6300                "foo (int a, /* abc */ int b) /* def */\n"
6301                "{\n"
6302                "}\n",
6303                Style);
6304 
6305   // Definitions that should not break after return type
6306   verifyFormat("void foo (int a, int b); // def\n", Style);
6307   verifyFormat("void foo (int a, int b); /* def */\n", Style);
6308   verifyFormat("void foo (int a, int b);\n", Style);
6309 }
6310 
TEST_F(FormatTest,AlwaysBreakBeforeMultilineStrings)6311 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
6312   FormatStyle NoBreak = getLLVMStyle();
6313   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
6314   FormatStyle Break = getLLVMStyle();
6315   Break.AlwaysBreakBeforeMultilineStrings = true;
6316   verifyFormat("aaaa = \"bbbb\"\n"
6317                "       \"cccc\";",
6318                NoBreak);
6319   verifyFormat("aaaa =\n"
6320                "    \"bbbb\"\n"
6321                "    \"cccc\";",
6322                Break);
6323   verifyFormat("aaaa(\"bbbb\"\n"
6324                "     \"cccc\");",
6325                NoBreak);
6326   verifyFormat("aaaa(\n"
6327                "    \"bbbb\"\n"
6328                "    \"cccc\");",
6329                Break);
6330   verifyFormat("aaaa(qqq, \"bbbb\"\n"
6331                "          \"cccc\");",
6332                NoBreak);
6333   verifyFormat("aaaa(qqq,\n"
6334                "     \"bbbb\"\n"
6335                "     \"cccc\");",
6336                Break);
6337   verifyFormat("aaaa(qqq,\n"
6338                "     L\"bbbb\"\n"
6339                "     L\"cccc\");",
6340                Break);
6341   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
6342                "                      \"bbbb\"));",
6343                Break);
6344   verifyFormat("string s = someFunction(\n"
6345                "    \"abc\"\n"
6346                "    \"abc\");",
6347                Break);
6348 
6349   // As we break before unary operators, breaking right after them is bad.
6350   verifyFormat("string foo = abc ? \"x\"\n"
6351                "                   \"blah blah blah blah blah blah\"\n"
6352                "                 : \"y\";",
6353                Break);
6354 
6355   // Don't break if there is no column gain.
6356   verifyFormat("f(\"aaaa\"\n"
6357                "  \"bbbb\");",
6358                Break);
6359 
6360   // Treat literals with escaped newlines like multi-line string literals.
6361   EXPECT_EQ("x = \"a\\\n"
6362             "b\\\n"
6363             "c\";",
6364             format("x = \"a\\\n"
6365                    "b\\\n"
6366                    "c\";",
6367                    NoBreak));
6368   EXPECT_EQ("xxxx =\n"
6369             "    \"a\\\n"
6370             "b\\\n"
6371             "c\";",
6372             format("xxxx = \"a\\\n"
6373                    "b\\\n"
6374                    "c\";",
6375                    Break));
6376 
6377   EXPECT_EQ("NSString *const kString =\n"
6378             "    @\"aaaa\"\n"
6379             "    @\"bbbb\";",
6380             format("NSString *const kString = @\"aaaa\"\n"
6381                    "@\"bbbb\";",
6382                    Break));
6383 
6384   Break.ColumnLimit = 0;
6385   verifyFormat("const char *hello = \"hello llvm\";", Break);
6386 }
6387 
TEST_F(FormatTest,AlignsPipes)6388 TEST_F(FormatTest, AlignsPipes) {
6389   verifyFormat(
6390       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6391       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6392       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6393   verifyFormat(
6394       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
6395       "                     << aaaaaaaaaaaaaaaaaaaa;");
6396   verifyFormat(
6397       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6398       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6399   verifyFormat(
6400       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6401       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6402   verifyFormat(
6403       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
6404       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
6405       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
6406   verifyFormat(
6407       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6408       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6409       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6410   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6411                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6412                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6413                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
6414   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
6415                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
6416   verifyFormat(
6417       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6418       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6419   verifyFormat(
6420       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
6421       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
6422 
6423   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
6424                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
6425   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6426                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6427                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
6428                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
6429   verifyFormat("LOG_IF(aaa == //\n"
6430                "       bbb)\n"
6431                "    << a << b;");
6432 
6433   // But sometimes, breaking before the first "<<" is desirable.
6434   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
6435                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
6436   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
6437                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6438                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6439   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
6440                "    << BEF << IsTemplate << Description << E->getType();");
6441   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
6442                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6443                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6444   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
6445                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6446                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6447                "    << aaa;");
6448 
6449   verifyFormat(
6450       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6451       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6452 
6453   // Incomplete string literal.
6454   EXPECT_EQ("llvm::errs() << \"\n"
6455             "             << a;",
6456             format("llvm::errs() << \"\n<<a;"));
6457 
6458   verifyFormat("void f() {\n"
6459                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
6460                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
6461                "}");
6462 
6463   // Handle 'endl'.
6464   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
6465                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
6466   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
6467 
6468   // Handle '\n'.
6469   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
6470                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
6471   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
6472                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
6473   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
6474                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
6475   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
6476 }
6477 
TEST_F(FormatTest,KeepStringLabelValuePairsOnALine)6478 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
6479   verifyFormat("return out << \"somepacket = {\\n\"\n"
6480                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
6481                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
6482                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
6483                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
6484                "           << \"}\";");
6485 
6486   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
6487                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
6488                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
6489   verifyFormat(
6490       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
6491       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
6492       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
6493       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
6494       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
6495   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
6496                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
6497   verifyFormat(
6498       "void f() {\n"
6499       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
6500       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
6501       "}");
6502 
6503   // Breaking before the first "<<" is generally not desirable.
6504   verifyFormat(
6505       "llvm::errs()\n"
6506       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6507       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6508       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6509       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6510       getLLVMStyleWithColumns(70));
6511   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
6512                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6513                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
6514                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6515                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
6516                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6517                getLLVMStyleWithColumns(70));
6518 
6519   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
6520                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
6521                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
6522   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
6523                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
6524                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
6525   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
6526                "           (aaaa + aaaa);",
6527                getLLVMStyleWithColumns(40));
6528   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
6529                "                  (aaaaaaa + aaaaa));",
6530                getLLVMStyleWithColumns(40));
6531   verifyFormat(
6532       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
6533       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
6534       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
6535 }
6536 
TEST_F(FormatTest,UnderstandsEquals)6537 TEST_F(FormatTest, UnderstandsEquals) {
6538   verifyFormat(
6539       "aaaaaaaaaaaaaaaaa =\n"
6540       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6541   verifyFormat(
6542       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6543       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
6544   verifyFormat(
6545       "if (a) {\n"
6546       "  f();\n"
6547       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6548       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
6549       "}");
6550 
6551   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6552                "        100000000 + 10000000) {\n}");
6553 }
6554 
TEST_F(FormatTest,WrapsAtFunctionCallsIfNecessary)6555 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
6556   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
6557                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
6558 
6559   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
6560                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
6561 
6562   verifyFormat(
6563       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
6564       "                                                          Parameter2);");
6565 
6566   verifyFormat(
6567       "ShortObject->shortFunction(\n"
6568       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
6569       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
6570 
6571   verifyFormat("loooooooooooooongFunction(\n"
6572                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
6573 
6574   verifyFormat(
6575       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
6576       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
6577 
6578   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
6579                "    .WillRepeatedly(Return(SomeValue));");
6580   verifyFormat("void f() {\n"
6581                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
6582                "      .Times(2)\n"
6583                "      .WillRepeatedly(Return(SomeValue));\n"
6584                "}");
6585   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
6586                "    ccccccccccccccccccccccc);");
6587   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6588                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6589                "          .aaaaa(aaaaa),\n"
6590                "      aaaaaaaaaaaaaaaaaaaaa);");
6591   verifyFormat("void f() {\n"
6592                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6593                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
6594                "}");
6595   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6596                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6597                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6598                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6599                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6600   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6601                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6602                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6603                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
6604                "}");
6605 
6606   // Here, it is not necessary to wrap at "." or "->".
6607   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
6608                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
6609   verifyFormat(
6610       "aaaaaaaaaaa->aaaaaaaaa(\n"
6611       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6612       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
6613 
6614   verifyFormat(
6615       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6616       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
6617   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
6618                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
6619   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
6620                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
6621 
6622   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6623                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6624                "    .a();");
6625 
6626   FormatStyle NoBinPacking = getLLVMStyle();
6627   NoBinPacking.BinPackParameters = false;
6628   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
6629                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
6630                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
6631                "                         aaaaaaaaaaaaaaaaaaa,\n"
6632                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6633                NoBinPacking);
6634 
6635   // If there is a subsequent call, change to hanging indentation.
6636   verifyFormat(
6637       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6638       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
6639       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6640   verifyFormat(
6641       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6642       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
6643   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6644                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6645                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6646   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6647                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6648                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
6649 }
6650 
TEST_F(FormatTest,WrapsTemplateDeclarations)6651 TEST_F(FormatTest, WrapsTemplateDeclarations) {
6652   verifyFormat("template <typename T>\n"
6653                "virtual void loooooooooooongFunction(int Param1, int Param2);");
6654   verifyFormat("template <typename T>\n"
6655                "// T should be one of {A, B}.\n"
6656                "virtual void loooooooooooongFunction(int Param1, int Param2);");
6657   verifyFormat(
6658       "template <typename T>\n"
6659       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
6660   verifyFormat("template <typename T>\n"
6661                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
6662                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
6663   verifyFormat(
6664       "template <typename T>\n"
6665       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
6666       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
6667   verifyFormat(
6668       "template <typename T>\n"
6669       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
6670       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
6671       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6672   verifyFormat("template <typename T>\n"
6673                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6674                "    int aaaaaaaaaaaaaaaaaaaaaa);");
6675   verifyFormat(
6676       "template <typename T1, typename T2 = char, typename T3 = char,\n"
6677       "          typename T4 = char>\n"
6678       "void f();");
6679   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
6680                "          template <typename> class cccccccccccccccccccccc,\n"
6681                "          typename ddddddddddddd>\n"
6682                "class C {};");
6683   verifyFormat(
6684       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
6685       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6686 
6687   verifyFormat("void f() {\n"
6688                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
6689                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
6690                "}");
6691 
6692   verifyFormat("template <typename T> class C {};");
6693   verifyFormat("template <typename T> void f();");
6694   verifyFormat("template <typename T> void f() {}");
6695   verifyFormat(
6696       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
6697       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6698       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
6699       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
6700       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6701       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
6702       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
6703       getLLVMStyleWithColumns(72));
6704   EXPECT_EQ("static_cast<A< //\n"
6705             "    B> *>(\n"
6706             "\n"
6707             ");",
6708             format("static_cast<A<//\n"
6709                    "    B>*>(\n"
6710                    "\n"
6711                    "    );"));
6712   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6713                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
6714 
6715   FormatStyle AlwaysBreak = getLLVMStyle();
6716   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
6717   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
6718   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
6719   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
6720   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6721                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
6722                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
6723   verifyFormat("template <template <typename> class Fooooooo,\n"
6724                "          template <typename> class Baaaaaaar>\n"
6725                "struct C {};",
6726                AlwaysBreak);
6727   verifyFormat("template <typename T> // T can be A, B or C.\n"
6728                "struct C {};",
6729                AlwaysBreak);
6730   verifyFormat("template <enum E> class A {\n"
6731                "public:\n"
6732                "  E *f();\n"
6733                "};");
6734 
6735   FormatStyle NeverBreak = getLLVMStyle();
6736   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
6737   verifyFormat("template <typename T> class C {};", NeverBreak);
6738   verifyFormat("template <typename T> void f();", NeverBreak);
6739   verifyFormat("template <typename T> void f() {}", NeverBreak);
6740   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
6741                "bbbbbbbbbbbbbbbbbbbb) {}",
6742                NeverBreak);
6743   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6744                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
6745                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
6746                NeverBreak);
6747   verifyFormat("template <template <typename> class Fooooooo,\n"
6748                "          template <typename> class Baaaaaaar>\n"
6749                "struct C {};",
6750                NeverBreak);
6751   verifyFormat("template <typename T> // T can be A, B or C.\n"
6752                "struct C {};",
6753                NeverBreak);
6754   verifyFormat("template <enum E> class A {\n"
6755                "public:\n"
6756                "  E *f();\n"
6757                "};",
6758                NeverBreak);
6759   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
6760   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
6761                "bbbbbbbbbbbbbbbbbbbb) {}",
6762                NeverBreak);
6763 }
6764 
TEST_F(FormatTest,WrapsTemplateDeclarationsWithComments)6765 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
6766   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
6767   Style.ColumnLimit = 60;
6768   EXPECT_EQ("// Baseline - no comments.\n"
6769             "template <\n"
6770             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
6771             "void f() {}",
6772             format("// Baseline - no comments.\n"
6773                    "template <\n"
6774                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
6775                    "void f() {}",
6776                    Style));
6777 
6778   EXPECT_EQ("template <\n"
6779             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
6780             "void f() {}",
6781             format("template <\n"
6782                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
6783                    "void f() {}",
6784                    Style));
6785 
6786   EXPECT_EQ(
6787       "template <\n"
6788       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
6789       "void f() {}",
6790       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
6791              "void f() {}",
6792              Style));
6793 
6794   EXPECT_EQ(
6795       "template <\n"
6796       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
6797       "                                               // multiline\n"
6798       "void f() {}",
6799       format("template <\n"
6800              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
6801              "                                              // multiline\n"
6802              "void f() {}",
6803              Style));
6804 
6805   EXPECT_EQ(
6806       "template <typename aaaaaaaaaa<\n"
6807       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
6808       "void f() {}",
6809       format(
6810           "template <\n"
6811           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
6812           "void f() {}",
6813           Style));
6814 }
6815 
TEST_F(FormatTest,WrapsTemplateParameters)6816 TEST_F(FormatTest, WrapsTemplateParameters) {
6817   FormatStyle Style = getLLVMStyle();
6818   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6819   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6820   verifyFormat(
6821       "template <typename... a> struct q {};\n"
6822       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
6823       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
6824       "    y;",
6825       Style);
6826   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6827   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6828   verifyFormat(
6829       "template <typename... a> struct r {};\n"
6830       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
6831       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
6832       "    y;",
6833       Style);
6834   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6835   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6836   verifyFormat("template <typename... a> struct s {};\n"
6837                "extern s<\n"
6838                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
6839                "aaaaaaaaaaaaaaaaaaaaaa,\n"
6840                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
6841                "aaaaaaaaaaaaaaaaaaaaaa>\n"
6842                "    y;",
6843                Style);
6844   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6845   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6846   verifyFormat("template <typename... a> struct t {};\n"
6847                "extern t<\n"
6848                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
6849                "aaaaaaaaaaaaaaaaaaaaaa,\n"
6850                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
6851                "aaaaaaaaaaaaaaaaaaaaaa>\n"
6852                "    y;",
6853                Style);
6854 }
6855 
TEST_F(FormatTest,WrapsAtNestedNameSpecifiers)6856 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
6857   verifyFormat(
6858       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
6859       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6860   verifyFormat(
6861       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
6862       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6863       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
6864 
6865   // FIXME: Should we have the extra indent after the second break?
6866   verifyFormat(
6867       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
6868       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
6869       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6870 
6871   verifyFormat(
6872       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
6873       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
6874 
6875   // Breaking at nested name specifiers is generally not desirable.
6876   verifyFormat(
6877       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6878       "    aaaaaaaaaaaaaaaaaaaaaaa);");
6879 
6880   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
6881                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
6882                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6883                "                   aaaaaaaaaaaaaaaaaaaaa);",
6884                getLLVMStyleWithColumns(74));
6885 
6886   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
6887                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6888                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6889 }
6890 
TEST_F(FormatTest,UnderstandsTemplateParameters)6891 TEST_F(FormatTest, UnderstandsTemplateParameters) {
6892   verifyFormat("A<int> a;");
6893   verifyFormat("A<A<A<int>>> a;");
6894   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
6895   verifyFormat("bool x = a < 1 || 2 > a;");
6896   verifyFormat("bool x = 5 < f<int>();");
6897   verifyFormat("bool x = f<int>() > 5;");
6898   verifyFormat("bool x = 5 < a<int>::x;");
6899   verifyFormat("bool x = a < 4 ? a > 2 : false;");
6900   verifyFormat("bool x = f() ? a < 2 : a > 2;");
6901 
6902   verifyGoogleFormat("A<A<int>> a;");
6903   verifyGoogleFormat("A<A<A<int>>> a;");
6904   verifyGoogleFormat("A<A<A<A<int>>>> a;");
6905   verifyGoogleFormat("A<A<int> > a;");
6906   verifyGoogleFormat("A<A<A<int> > > a;");
6907   verifyGoogleFormat("A<A<A<A<int> > > > a;");
6908   verifyGoogleFormat("A<::A<int>> a;");
6909   verifyGoogleFormat("A<::A> a;");
6910   verifyGoogleFormat("A< ::A> a;");
6911   verifyGoogleFormat("A< ::A<int> > a;");
6912   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
6913   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
6914   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
6915   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
6916   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
6917             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
6918 
6919   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
6920 
6921   // template closer followed by a token that starts with > or =
6922   verifyFormat("bool b = a<1> > 1;");
6923   verifyFormat("bool b = a<1> >= 1;");
6924   verifyFormat("int i = a<1> >> 1;");
6925   FormatStyle Style = getLLVMStyle();
6926   Style.SpaceBeforeAssignmentOperators = false;
6927   verifyFormat("bool b= a<1> == 1;", Style);
6928   verifyFormat("a<int> = 1;", Style);
6929   verifyFormat("a<int> >>= 1;", Style);
6930 
6931   verifyFormat("test >> a >> b;");
6932   verifyFormat("test << a >> b;");
6933 
6934   verifyFormat("f<int>();");
6935   verifyFormat("template <typename T> void f() {}");
6936   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
6937   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
6938                "sizeof(char)>::type>;");
6939   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
6940   verifyFormat("f(a.operator()<A>());");
6941   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6942                "      .template operator()<A>());",
6943                getLLVMStyleWithColumns(35));
6944 
6945   // Not template parameters.
6946   verifyFormat("return a < b && c > d;");
6947   verifyFormat("void f() {\n"
6948                "  while (a < b && c > d) {\n"
6949                "  }\n"
6950                "}");
6951   verifyFormat("template <typename... Types>\n"
6952                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
6953 
6954   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6955                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
6956                getLLVMStyleWithColumns(60));
6957   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
6958   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
6959   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
6960 }
6961 
TEST_F(FormatTest,BitshiftOperatorWidth)6962 TEST_F(FormatTest, BitshiftOperatorWidth) {
6963   EXPECT_EQ("int a = 1 << 2; /* foo\n"
6964             "                   bar */",
6965             format("int    a=1<<2;  /* foo\n"
6966                    "                   bar */"));
6967 
6968   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
6969             "                     bar */",
6970             format("int  b  =256>>1 ;  /* foo\n"
6971                    "                      bar */"));
6972 }
6973 
TEST_F(FormatTest,UnderstandsBinaryOperators)6974 TEST_F(FormatTest, UnderstandsBinaryOperators) {
6975   verifyFormat("COMPARE(a, ==, b);");
6976   verifyFormat("auto s = sizeof...(Ts) - 1;");
6977 }
6978 
TEST_F(FormatTest,UnderstandsPointersToMembers)6979 TEST_F(FormatTest, UnderstandsPointersToMembers) {
6980   verifyFormat("int A::*x;");
6981   verifyFormat("int (S::*func)(void *);");
6982   verifyFormat("void f() { int (S::*func)(void *); }");
6983   verifyFormat("typedef bool *(Class::*Member)() const;");
6984   verifyFormat("void f() {\n"
6985                "  (a->*f)();\n"
6986                "  a->*x;\n"
6987                "  (a.*f)();\n"
6988                "  ((*a).*f)();\n"
6989                "  a.*x;\n"
6990                "}");
6991   verifyFormat("void f() {\n"
6992                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
6993                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
6994                "}");
6995   verifyFormat(
6996       "(aaaaaaaaaa->*bbbbbbb)(\n"
6997       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6998   FormatStyle Style = getLLVMStyle();
6999   Style.PointerAlignment = FormatStyle::PAS_Left;
7000   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
7001 }
7002 
TEST_F(FormatTest,UnderstandsUnaryOperators)7003 TEST_F(FormatTest, UnderstandsUnaryOperators) {
7004   verifyFormat("int a = -2;");
7005   verifyFormat("f(-1, -2, -3);");
7006   verifyFormat("a[-1] = 5;");
7007   verifyFormat("int a = 5 + -2;");
7008   verifyFormat("if (i == -1) {\n}");
7009   verifyFormat("if (i != -1) {\n}");
7010   verifyFormat("if (i > -1) {\n}");
7011   verifyFormat("if (i < -1) {\n}");
7012   verifyFormat("++(a->f());");
7013   verifyFormat("--(a->f());");
7014   verifyFormat("(a->f())++;");
7015   verifyFormat("a[42]++;");
7016   verifyFormat("if (!(a->f())) {\n}");
7017   verifyFormat("if (!+i) {\n}");
7018   verifyFormat("~&a;");
7019 
7020   verifyFormat("a-- > b;");
7021   verifyFormat("b ? -a : c;");
7022   verifyFormat("n * sizeof char16;");
7023   verifyFormat("n * alignof char16;", getGoogleStyle());
7024   verifyFormat("sizeof(char);");
7025   verifyFormat("alignof(char);", getGoogleStyle());
7026 
7027   verifyFormat("return -1;");
7028   verifyFormat("throw -1;");
7029   verifyFormat("switch (a) {\n"
7030                "case -1:\n"
7031                "  break;\n"
7032                "}");
7033   verifyFormat("#define X -1");
7034   verifyFormat("#define X -kConstant");
7035 
7036   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
7037   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
7038 
7039   verifyFormat("int a = /* confusing comment */ -1;");
7040   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
7041   verifyFormat("int a = i /* confusing comment */++;");
7042 
7043   verifyFormat("co_yield -1;");
7044   verifyFormat("co_return -1;");
7045 }
7046 
TEST_F(FormatTest,DoesNotIndentRelativeToUnaryOperators)7047 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
7048   verifyFormat("if (!aaaaaaaaaa( // break\n"
7049                "        aaaaa)) {\n"
7050                "}");
7051   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
7052                "    aaaaa));");
7053   verifyFormat("*aaa = aaaaaaa( // break\n"
7054                "    bbbbbb);");
7055 }
7056 
TEST_F(FormatTest,UnderstandsOverloadedOperators)7057 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
7058   verifyFormat("bool operator<();");
7059   verifyFormat("bool operator>();");
7060   verifyFormat("bool operator=();");
7061   verifyFormat("bool operator==();");
7062   verifyFormat("bool operator!=();");
7063   verifyFormat("int operator+();");
7064   verifyFormat("int operator++();");
7065   verifyFormat("int operator++(int) volatile noexcept;");
7066   verifyFormat("bool operator,();");
7067   verifyFormat("bool operator();");
7068   verifyFormat("bool operator()();");
7069   verifyFormat("bool operator[]();");
7070   verifyFormat("operator bool();");
7071   verifyFormat("operator int();");
7072   verifyFormat("operator void *();");
7073   verifyFormat("operator SomeType<int>();");
7074   verifyFormat("operator SomeType<int, int>();");
7075   verifyFormat("operator SomeType<SomeType<int>>();");
7076   verifyFormat("void *operator new(std::size_t size);");
7077   verifyFormat("void *operator new[](std::size_t size);");
7078   verifyFormat("void operator delete(void *ptr);");
7079   verifyFormat("void operator delete[](void *ptr);");
7080   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
7081                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
7082   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
7083                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
7084 
7085   verifyFormat(
7086       "ostream &operator<<(ostream &OutputStream,\n"
7087       "                    SomeReallyLongType WithSomeReallyLongValue);");
7088   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
7089                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
7090                "  return left.group < right.group;\n"
7091                "}");
7092   verifyFormat("SomeType &operator=(const SomeType &S);");
7093   verifyFormat("f.template operator()<int>();");
7094 
7095   verifyGoogleFormat("operator void*();");
7096   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
7097   verifyGoogleFormat("operator ::A();");
7098 
7099   verifyFormat("using A::operator+;");
7100   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
7101                "int i;");
7102 }
7103 
TEST_F(FormatTest,UnderstandsFunctionRefQualification)7104 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
7105   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
7106   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
7107   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
7108   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
7109   verifyFormat("Deleted &operator=(const Deleted &) &;");
7110   verifyFormat("Deleted &operator=(const Deleted &) &&;");
7111   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
7112   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
7113   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
7114   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
7115   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
7116   verifyFormat("void Fn(T const &) const &;");
7117   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
7118   verifyFormat("template <typename T>\n"
7119                "void F(T) && = delete;",
7120                getGoogleStyle());
7121 
7122   FormatStyle AlignLeft = getLLVMStyle();
7123   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
7124   verifyFormat("void A::b() && {}", AlignLeft);
7125   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
7126   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
7127                AlignLeft);
7128   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
7129   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
7130   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
7131   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
7132   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
7133   verifyFormat("auto Function(T) & -> void;", AlignLeft);
7134   verifyFormat("void Fn(T const&) const&;", AlignLeft);
7135   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
7136 
7137   FormatStyle Spaces = getLLVMStyle();
7138   Spaces.SpacesInCStyleCastParentheses = true;
7139   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
7140   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
7141   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
7142   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
7143 
7144   Spaces.SpacesInCStyleCastParentheses = false;
7145   Spaces.SpacesInParentheses = true;
7146   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
7147   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
7148                Spaces);
7149   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
7150   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
7151 
7152   FormatStyle BreakTemplate = getLLVMStyle();
7153   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7154 
7155   verifyFormat("struct f {\n"
7156                "  template <class T>\n"
7157                "  int &foo(const std::string &str) &noexcept {}\n"
7158                "};",
7159                BreakTemplate);
7160 
7161   verifyFormat("struct f {\n"
7162                "  template <class T>\n"
7163                "  int &foo(const std::string &str) &&noexcept {}\n"
7164                "};",
7165                BreakTemplate);
7166 
7167   verifyFormat("struct f {\n"
7168                "  template <class T>\n"
7169                "  int &foo(const std::string &str) const &noexcept {}\n"
7170                "};",
7171                BreakTemplate);
7172 
7173   verifyFormat("struct f {\n"
7174                "  template <class T>\n"
7175                "  int &foo(const std::string &str) const &noexcept {}\n"
7176                "};",
7177                BreakTemplate);
7178 
7179   verifyFormat("struct f {\n"
7180                "  template <class T>\n"
7181                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
7182                "};",
7183                BreakTemplate);
7184 
7185   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
7186   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
7187       FormatStyle::BTDS_Yes;
7188   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
7189 
7190   verifyFormat("struct f {\n"
7191                "  template <class T>\n"
7192                "  int& foo(const std::string& str) & noexcept {}\n"
7193                "};",
7194                AlignLeftBreakTemplate);
7195 
7196   verifyFormat("struct f {\n"
7197                "  template <class T>\n"
7198                "  int& foo(const std::string& str) && noexcept {}\n"
7199                "};",
7200                AlignLeftBreakTemplate);
7201 
7202   verifyFormat("struct f {\n"
7203                "  template <class T>\n"
7204                "  int& foo(const std::string& str) const& noexcept {}\n"
7205                "};",
7206                AlignLeftBreakTemplate);
7207 
7208   verifyFormat("struct f {\n"
7209                "  template <class T>\n"
7210                "  int& foo(const std::string& str) const&& noexcept {}\n"
7211                "};",
7212                AlignLeftBreakTemplate);
7213 
7214   verifyFormat("struct f {\n"
7215                "  template <class T>\n"
7216                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
7217                "};",
7218                AlignLeftBreakTemplate);
7219 
7220   // The `&` in `Type&` should not be confused with a trailing `&` of
7221   // DEPRECATED(reason) member function.
7222   verifyFormat("struct f {\n"
7223                "  template <class T>\n"
7224                "  DEPRECATED(reason)\n"
7225                "  Type &foo(arguments) {}\n"
7226                "};",
7227                BreakTemplate);
7228 
7229   verifyFormat("struct f {\n"
7230                "  template <class T>\n"
7231                "  DEPRECATED(reason)\n"
7232                "  Type& foo(arguments) {}\n"
7233                "};",
7234                AlignLeftBreakTemplate);
7235 
7236   verifyFormat("void (*foopt)(int) = &func;");
7237 }
7238 
TEST_F(FormatTest,UnderstandsNewAndDelete)7239 TEST_F(FormatTest, UnderstandsNewAndDelete) {
7240   verifyFormat("void f() {\n"
7241                "  A *a = new A;\n"
7242                "  A *a = new (placement) A;\n"
7243                "  delete a;\n"
7244                "  delete (A *)a;\n"
7245                "}");
7246   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7247                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7248   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7249                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7250                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7251   verifyFormat("delete[] h->p;");
7252 }
7253 
TEST_F(FormatTest,UnderstandsUsesOfStarAndAmp)7254 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
7255   verifyFormat("int *f(int *a) {}");
7256   verifyFormat("int main(int argc, char **argv) {}");
7257   verifyFormat("Test::Test(int b) : a(b * b) {}");
7258   verifyIndependentOfContext("f(a, *a);");
7259   verifyFormat("void g() { f(*a); }");
7260   verifyIndependentOfContext("int a = b * 10;");
7261   verifyIndependentOfContext("int a = 10 * b;");
7262   verifyIndependentOfContext("int a = b * c;");
7263   verifyIndependentOfContext("int a += b * c;");
7264   verifyIndependentOfContext("int a -= b * c;");
7265   verifyIndependentOfContext("int a *= b * c;");
7266   verifyIndependentOfContext("int a /= b * c;");
7267   verifyIndependentOfContext("int a = *b;");
7268   verifyIndependentOfContext("int a = *b * c;");
7269   verifyIndependentOfContext("int a = b * *c;");
7270   verifyIndependentOfContext("int a = b * (10);");
7271   verifyIndependentOfContext("S << b * (10);");
7272   verifyIndependentOfContext("return 10 * b;");
7273   verifyIndependentOfContext("return *b * *c;");
7274   verifyIndependentOfContext("return a & ~b;");
7275   verifyIndependentOfContext("f(b ? *c : *d);");
7276   verifyIndependentOfContext("int a = b ? *c : *d;");
7277   verifyIndependentOfContext("*b = a;");
7278   verifyIndependentOfContext("a * ~b;");
7279   verifyIndependentOfContext("a * !b;");
7280   verifyIndependentOfContext("a * +b;");
7281   verifyIndependentOfContext("a * -b;");
7282   verifyIndependentOfContext("a * ++b;");
7283   verifyIndependentOfContext("a * --b;");
7284   verifyIndependentOfContext("a[4] * b;");
7285   verifyIndependentOfContext("a[a * a] = 1;");
7286   verifyIndependentOfContext("f() * b;");
7287   verifyIndependentOfContext("a * [self dostuff];");
7288   verifyIndependentOfContext("int x = a * (a + b);");
7289   verifyIndependentOfContext("(a *)(a + b);");
7290   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
7291   verifyIndependentOfContext("int *pa = (int *)&a;");
7292   verifyIndependentOfContext("return sizeof(int **);");
7293   verifyIndependentOfContext("return sizeof(int ******);");
7294   verifyIndependentOfContext("return (int **&)a;");
7295   verifyIndependentOfContext("f((*PointerToArray)[10]);");
7296   verifyFormat("void f(Type (*parameter)[10]) {}");
7297   verifyFormat("void f(Type (&parameter)[10]) {}");
7298   verifyGoogleFormat("return sizeof(int**);");
7299   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
7300   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
7301   verifyFormat("auto a = [](int **&, int ***) {};");
7302   verifyFormat("auto PointerBinding = [](const char *S) {};");
7303   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
7304   verifyFormat("[](const decltype(*a) &value) {}");
7305   verifyFormat("decltype(a * b) F();");
7306   verifyFormat("#define MACRO() [](A *a) { return 1; }");
7307   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
7308   verifyIndependentOfContext("typedef void (*f)(int *a);");
7309   verifyIndependentOfContext("int i{a * b};");
7310   verifyIndependentOfContext("aaa && aaa->f();");
7311   verifyIndependentOfContext("int x = ~*p;");
7312   verifyFormat("Constructor() : a(a), area(width * height) {}");
7313   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
7314   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
7315   verifyFormat("void f() { f(a, c * d); }");
7316   verifyFormat("void f() { f(new a(), c * d); }");
7317   verifyFormat("void f(const MyOverride &override);");
7318   verifyFormat("void f(const MyFinal &final);");
7319   verifyIndependentOfContext("bool a = f() && override.f();");
7320   verifyIndependentOfContext("bool a = f() && final.f();");
7321 
7322   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
7323 
7324   verifyIndependentOfContext("A<int *> a;");
7325   verifyIndependentOfContext("A<int **> a;");
7326   verifyIndependentOfContext("A<int *, int *> a;");
7327   verifyIndependentOfContext("A<int *[]> a;");
7328   verifyIndependentOfContext(
7329       "const char *const p = reinterpret_cast<const char *const>(q);");
7330   verifyIndependentOfContext("A<int **, int **> a;");
7331   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
7332   verifyFormat("for (char **a = b; *a; ++a) {\n}");
7333   verifyFormat("for (; a && b;) {\n}");
7334   verifyFormat("bool foo = true && [] { return false; }();");
7335 
7336   verifyFormat(
7337       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7338       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7339 
7340   verifyGoogleFormat("int const* a = &b;");
7341   verifyGoogleFormat("**outparam = 1;");
7342   verifyGoogleFormat("*outparam = a * b;");
7343   verifyGoogleFormat("int main(int argc, char** argv) {}");
7344   verifyGoogleFormat("A<int*> a;");
7345   verifyGoogleFormat("A<int**> a;");
7346   verifyGoogleFormat("A<int*, int*> a;");
7347   verifyGoogleFormat("A<int**, int**> a;");
7348   verifyGoogleFormat("f(b ? *c : *d);");
7349   verifyGoogleFormat("int a = b ? *c : *d;");
7350   verifyGoogleFormat("Type* t = **x;");
7351   verifyGoogleFormat("Type* t = *++*x;");
7352   verifyGoogleFormat("*++*x;");
7353   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
7354   verifyGoogleFormat("Type* t = x++ * y;");
7355   verifyGoogleFormat(
7356       "const char* const p = reinterpret_cast<const char* const>(q);");
7357   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
7358   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
7359   verifyGoogleFormat("template <typename T>\n"
7360                      "void f(int i = 0, SomeType** temps = NULL);");
7361 
7362   FormatStyle Left = getLLVMStyle();
7363   Left.PointerAlignment = FormatStyle::PAS_Left;
7364   verifyFormat("x = *a(x) = *a(y);", Left);
7365   verifyFormat("for (;; *a = b) {\n}", Left);
7366   verifyFormat("return *this += 1;", Left);
7367   verifyFormat("throw *x;", Left);
7368   verifyFormat("delete *x;", Left);
7369   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
7370   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
7371   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
7372 
7373   verifyIndependentOfContext("a = *(x + y);");
7374   verifyIndependentOfContext("a = &(x + y);");
7375   verifyIndependentOfContext("*(x + y).call();");
7376   verifyIndependentOfContext("&(x + y)->call();");
7377   verifyFormat("void f() { &(*I).first; }");
7378 
7379   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
7380   verifyFormat(
7381       "int *MyValues = {\n"
7382       "    *A, // Operator detection might be confused by the '{'\n"
7383       "    *BB // Operator detection might be confused by previous comment\n"
7384       "};");
7385 
7386   verifyIndependentOfContext("if (int *a = &b)");
7387   verifyIndependentOfContext("if (int &a = *b)");
7388   verifyIndependentOfContext("if (a & b[i])");
7389   verifyIndependentOfContext("if constexpr (a & b[i])");
7390   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
7391   verifyIndependentOfContext("if (a * (b * c))");
7392   verifyIndependentOfContext("if constexpr (a * (b * c))");
7393   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
7394   verifyIndependentOfContext("if (a::b::c::d & b[i])");
7395   verifyIndependentOfContext("if (*b[i])");
7396   verifyIndependentOfContext("if (int *a = (&b))");
7397   verifyIndependentOfContext("while (int *a = &b)");
7398   verifyIndependentOfContext("while (a * (b * c))");
7399   verifyIndependentOfContext("size = sizeof *a;");
7400   verifyIndependentOfContext("if (a && (b = c))");
7401   verifyFormat("void f() {\n"
7402                "  for (const int &v : Values) {\n"
7403                "  }\n"
7404                "}");
7405   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
7406   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
7407   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
7408 
7409   verifyFormat("#define A (!a * b)");
7410   verifyFormat("#define MACRO     \\\n"
7411                "  int *i = a * b; \\\n"
7412                "  void f(a *b);",
7413                getLLVMStyleWithColumns(19));
7414 
7415   verifyIndependentOfContext("A = new SomeType *[Length];");
7416   verifyIndependentOfContext("A = new SomeType *[Length]();");
7417   verifyIndependentOfContext("T **t = new T *;");
7418   verifyIndependentOfContext("T **t = new T *();");
7419   verifyGoogleFormat("A = new SomeType*[Length]();");
7420   verifyGoogleFormat("A = new SomeType*[Length];");
7421   verifyGoogleFormat("T** t = new T*;");
7422   verifyGoogleFormat("T** t = new T*();");
7423 
7424   verifyFormat("STATIC_ASSERT((a & b) == 0);");
7425   verifyFormat("STATIC_ASSERT(0 == (a & b));");
7426   verifyFormat("template <bool a, bool b> "
7427                "typename t::if<x && y>::type f() {}");
7428   verifyFormat("template <int *y> f() {}");
7429   verifyFormat("vector<int *> v;");
7430   verifyFormat("vector<int *const> v;");
7431   verifyFormat("vector<int *const **const *> v;");
7432   verifyFormat("vector<int *volatile> v;");
7433   verifyFormat("vector<a * b> v;");
7434   verifyFormat("foo<b && false>();");
7435   verifyFormat("foo<b & 1>();");
7436   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
7437   verifyFormat(
7438       "template <class T, class = typename std::enable_if<\n"
7439       "                       std::is_integral<T>::value &&\n"
7440       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
7441       "void F();",
7442       getLLVMStyleWithColumns(70));
7443   verifyFormat("template <class T,\n"
7444                "          class = typename std::enable_if<\n"
7445                "              std::is_integral<T>::value &&\n"
7446                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
7447                "          class U>\n"
7448                "void F();",
7449                getLLVMStyleWithColumns(70));
7450   verifyFormat(
7451       "template <class T,\n"
7452       "          class = typename ::std::enable_if<\n"
7453       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
7454       "void F();",
7455       getGoogleStyleWithColumns(68));
7456 
7457   verifyIndependentOfContext("MACRO(int *i);");
7458   verifyIndependentOfContext("MACRO(auto *a);");
7459   verifyIndependentOfContext("MACRO(const A *a);");
7460   verifyIndependentOfContext("MACRO(A *const a);");
7461   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
7462   verifyFormat("void f() { f(float{1}, a * a); }");
7463   // FIXME: Is there a way to make this work?
7464   // verifyIndependentOfContext("MACRO(A *a);");
7465 
7466   verifyFormat("DatumHandle const *operator->() const { return input_; }");
7467   verifyFormat("return options != nullptr && operator==(*options);");
7468 
7469   EXPECT_EQ("#define OP(x)                                    \\\n"
7470             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
7471             "    return s << a.DebugString();                 \\\n"
7472             "  }",
7473             format("#define OP(x) \\\n"
7474                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
7475                    "    return s << a.DebugString(); \\\n"
7476                    "  }",
7477                    getLLVMStyleWithColumns(50)));
7478 
7479   // FIXME: We cannot handle this case yet; we might be able to figure out that
7480   // foo<x> d > v; doesn't make sense.
7481   verifyFormat("foo<a<b && c> d> v;");
7482 
7483   FormatStyle PointerMiddle = getLLVMStyle();
7484   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
7485   verifyFormat("delete *x;", PointerMiddle);
7486   verifyFormat("int * x;", PointerMiddle);
7487   verifyFormat("int *[] x;", PointerMiddle);
7488   verifyFormat("template <int * y> f() {}", PointerMiddle);
7489   verifyFormat("int * f(int * a) {}", PointerMiddle);
7490   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
7491   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
7492   verifyFormat("A<int *> a;", PointerMiddle);
7493   verifyFormat("A<int **> a;", PointerMiddle);
7494   verifyFormat("A<int *, int *> a;", PointerMiddle);
7495   verifyFormat("A<int *[]> a;", PointerMiddle);
7496   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
7497   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
7498   verifyFormat("T ** t = new T *;", PointerMiddle);
7499 
7500   // Member function reference qualifiers aren't binary operators.
7501   verifyFormat("string // break\n"
7502                "operator()() & {}");
7503   verifyFormat("string // break\n"
7504                "operator()() && {}");
7505   verifyGoogleFormat("template <typename T>\n"
7506                      "auto x() & -> int {}");
7507 }
7508 
TEST_F(FormatTest,UnderstandsAttributes)7509 TEST_F(FormatTest, UnderstandsAttributes) {
7510   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
7511   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
7512                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
7513   FormatStyle AfterType = getLLVMStyle();
7514   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
7515   verifyFormat("__attribute__((nodebug)) void\n"
7516                "foo() {}\n",
7517                AfterType);
7518 }
7519 
TEST_F(FormatTest,UnderstandsSquareAttributes)7520 TEST_F(FormatTest, UnderstandsSquareAttributes) {
7521   verifyFormat("SomeType s [[unused]] (InitValue);");
7522   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
7523   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
7524   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
7525   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
7526   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7527                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
7528 
7529   // Make sure we do not mistake attributes for array subscripts.
7530   verifyFormat("int a() {}\n"
7531                "[[unused]] int b() {}\n");
7532   verifyFormat("NSArray *arr;\n"
7533                "arr[[Foo() bar]];");
7534 
7535   // On the other hand, we still need to correctly find array subscripts.
7536   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
7537 
7538   // Make sure that we do not mistake Objective-C method inside array literals
7539   // as attributes, even if those method names are also keywords.
7540   verifyFormat("@[ [foo bar] ];");
7541   verifyFormat("@[ [NSArray class] ];");
7542   verifyFormat("@[ [foo enum] ];");
7543 
7544   // Make sure we do not parse attributes as lambda introducers.
7545   FormatStyle MultiLineFunctions = getLLVMStyle();
7546   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
7547   verifyFormat("[[unused]] int b() {\n"
7548                "  return 42;\n"
7549                "}\n",
7550                MultiLineFunctions);
7551 }
7552 
TEST_F(FormatTest,UnderstandsEllipsis)7553 TEST_F(FormatTest, UnderstandsEllipsis) {
7554   verifyFormat("int printf(const char *fmt, ...);");
7555   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
7556   verifyFormat("template <class... Ts> void Foo(Ts *... ts) {}");
7557 
7558   FormatStyle PointersLeft = getLLVMStyle();
7559   PointersLeft.PointerAlignment = FormatStyle::PAS_Left;
7560   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", PointersLeft);
7561 }
7562 
TEST_F(FormatTest,AdaptivelyFormatsPointersAndReferences)7563 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
7564   EXPECT_EQ("int *a;\n"
7565             "int *a;\n"
7566             "int *a;",
7567             format("int *a;\n"
7568                    "int* a;\n"
7569                    "int *a;",
7570                    getGoogleStyle()));
7571   EXPECT_EQ("int* a;\n"
7572             "int* a;\n"
7573             "int* a;",
7574             format("int* a;\n"
7575                    "int* a;\n"
7576                    "int *a;",
7577                    getGoogleStyle()));
7578   EXPECT_EQ("int *a;\n"
7579             "int *a;\n"
7580             "int *a;",
7581             format("int *a;\n"
7582                    "int * a;\n"
7583                    "int *  a;",
7584                    getGoogleStyle()));
7585   EXPECT_EQ("auto x = [] {\n"
7586             "  int *a;\n"
7587             "  int *a;\n"
7588             "  int *a;\n"
7589             "};",
7590             format("auto x=[]{int *a;\n"
7591                    "int * a;\n"
7592                    "int *  a;};",
7593                    getGoogleStyle()));
7594 }
7595 
TEST_F(FormatTest,UnderstandsRvalueReferences)7596 TEST_F(FormatTest, UnderstandsRvalueReferences) {
7597   verifyFormat("int f(int &&a) {}");
7598   verifyFormat("int f(int a, char &&b) {}");
7599   verifyFormat("void f() { int &&a = b; }");
7600   verifyGoogleFormat("int f(int a, char&& b) {}");
7601   verifyGoogleFormat("void f() { int&& a = b; }");
7602 
7603   verifyIndependentOfContext("A<int &&> a;");
7604   verifyIndependentOfContext("A<int &&, int &&> a;");
7605   verifyGoogleFormat("A<int&&> a;");
7606   verifyGoogleFormat("A<int&&, int&&> a;");
7607 
7608   // Not rvalue references:
7609   verifyFormat("template <bool B, bool C> class A {\n"
7610                "  static_assert(B && C, \"Something is wrong\");\n"
7611                "};");
7612   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
7613   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
7614   verifyFormat("#define A(a, b) (a && b)");
7615 }
7616 
TEST_F(FormatTest,FormatsBinaryOperatorsPrecedingEquals)7617 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
7618   verifyFormat("void f() {\n"
7619                "  x[aaaaaaaaa -\n"
7620                "    b] = 23;\n"
7621                "}",
7622                getLLVMStyleWithColumns(15));
7623 }
7624 
TEST_F(FormatTest,FormatsCasts)7625 TEST_F(FormatTest, FormatsCasts) {
7626   verifyFormat("Type *A = static_cast<Type *>(P);");
7627   verifyFormat("Type *A = (Type *)P;");
7628   verifyFormat("Type *A = (vector<Type *, int *>)P;");
7629   verifyFormat("int a = (int)(2.0f);");
7630   verifyFormat("int a = (int)2.0f;");
7631   verifyFormat("x[(int32)y];");
7632   verifyFormat("x = (int32)y;");
7633   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
7634   verifyFormat("int a = (int)*b;");
7635   verifyFormat("int a = (int)2.0f;");
7636   verifyFormat("int a = (int)~0;");
7637   verifyFormat("int a = (int)++a;");
7638   verifyFormat("int a = (int)sizeof(int);");
7639   verifyFormat("int a = (int)+2;");
7640   verifyFormat("my_int a = (my_int)2.0f;");
7641   verifyFormat("my_int a = (my_int)sizeof(int);");
7642   verifyFormat("return (my_int)aaa;");
7643   verifyFormat("#define x ((int)-1)");
7644   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
7645   verifyFormat("#define p(q) ((int *)&q)");
7646   verifyFormat("fn(a)(b) + 1;");
7647 
7648   verifyFormat("void f() { my_int a = (my_int)*b; }");
7649   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
7650   verifyFormat("my_int a = (my_int)~0;");
7651   verifyFormat("my_int a = (my_int)++a;");
7652   verifyFormat("my_int a = (my_int)-2;");
7653   verifyFormat("my_int a = (my_int)1;");
7654   verifyFormat("my_int a = (my_int *)1;");
7655   verifyFormat("my_int a = (const my_int)-1;");
7656   verifyFormat("my_int a = (const my_int *)-1;");
7657   verifyFormat("my_int a = (my_int)(my_int)-1;");
7658   verifyFormat("my_int a = (ns::my_int)-2;");
7659   verifyFormat("case (my_int)ONE:");
7660   verifyFormat("auto x = (X)this;");
7661   // Casts in Obj-C style calls used to not be recognized as such.
7662   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
7663 
7664   // FIXME: single value wrapped with paren will be treated as cast.
7665   verifyFormat("void f(int i = (kValue)*kMask) {}");
7666 
7667   verifyFormat("{ (void)F; }");
7668 
7669   // Don't break after a cast's
7670   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7671                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
7672                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
7673 
7674   // These are not casts.
7675   verifyFormat("void f(int *) {}");
7676   verifyFormat("f(foo)->b;");
7677   verifyFormat("f(foo).b;");
7678   verifyFormat("f(foo)(b);");
7679   verifyFormat("f(foo)[b];");
7680   verifyFormat("[](foo) { return 4; }(bar);");
7681   verifyFormat("(*funptr)(foo)[4];");
7682   verifyFormat("funptrs[4](foo)[4];");
7683   verifyFormat("void f(int *);");
7684   verifyFormat("void f(int *) = 0;");
7685   verifyFormat("void f(SmallVector<int>) {}");
7686   verifyFormat("void f(SmallVector<int>);");
7687   verifyFormat("void f(SmallVector<int>) = 0;");
7688   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
7689   verifyFormat("int a = sizeof(int) * b;");
7690   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
7691   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
7692   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
7693   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
7694 
7695   // These are not casts, but at some point were confused with casts.
7696   verifyFormat("virtual void foo(int *) override;");
7697   verifyFormat("virtual void foo(char &) const;");
7698   verifyFormat("virtual void foo(int *a, char *) const;");
7699   verifyFormat("int a = sizeof(int *) + b;");
7700   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
7701   verifyFormat("bool b = f(g<int>) && c;");
7702   verifyFormat("typedef void (*f)(int i) func;");
7703   verifyFormat("void operator++(int) noexcept;");
7704   verifyFormat("void operator++(int &) noexcept;");
7705   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
7706                "&) noexcept;");
7707   verifyFormat(
7708       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
7709   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
7710   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
7711   verifyFormat("void operator delete(nothrow_t &) noexcept;");
7712   verifyFormat("void operator delete(foo &) noexcept;");
7713   verifyFormat("void operator delete(foo) noexcept;");
7714   verifyFormat("void operator delete(int) noexcept;");
7715   verifyFormat("void operator delete(int &) noexcept;");
7716   verifyFormat("void operator delete(int &) volatile noexcept;");
7717   verifyFormat("void operator delete(int &) const");
7718   verifyFormat("void operator delete(int &) = default");
7719   verifyFormat("void operator delete(int &) = delete");
7720   verifyFormat("void operator delete(int &) [[noreturn]]");
7721   verifyFormat("void operator delete(int &) throw();");
7722   verifyFormat("void operator delete(int &) throw(int);");
7723   verifyFormat("auto operator delete(int &) -> int;");
7724   verifyFormat("auto operator delete(int &) override");
7725   verifyFormat("auto operator delete(int &) final");
7726 
7727   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
7728                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7729   // FIXME: The indentation here is not ideal.
7730   verifyFormat(
7731       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7732       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
7733       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
7734 }
7735 
TEST_F(FormatTest,FormatsFunctionTypes)7736 TEST_F(FormatTest, FormatsFunctionTypes) {
7737   verifyFormat("A<bool()> a;");
7738   verifyFormat("A<SomeType()> a;");
7739   verifyFormat("A<void (*)(int, std::string)> a;");
7740   verifyFormat("A<void *(int)>;");
7741   verifyFormat("void *(*a)(int *, SomeType *);");
7742   verifyFormat("int (*func)(void *);");
7743   verifyFormat("void f() { int (*func)(void *); }");
7744   verifyFormat("template <class CallbackClass>\n"
7745                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
7746 
7747   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
7748   verifyGoogleFormat("void* (*a)(int);");
7749   verifyGoogleFormat(
7750       "template <class CallbackClass>\n"
7751       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
7752 
7753   // Other constructs can look somewhat like function types:
7754   verifyFormat("A<sizeof(*x)> a;");
7755   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
7756   verifyFormat("some_var = function(*some_pointer_var)[0];");
7757   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
7758   verifyFormat("int x = f(&h)();");
7759   verifyFormat("returnsFunction(&param1, &param2)(param);");
7760   verifyFormat("std::function<\n"
7761                "    LooooooooooongTemplatedType<\n"
7762                "        SomeType>*(\n"
7763                "        LooooooooooooooooongType type)>\n"
7764                "    function;",
7765                getGoogleStyleWithColumns(40));
7766 }
7767 
TEST_F(FormatTest,FormatsPointersToArrayTypes)7768 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
7769   verifyFormat("A (*foo_)[6];");
7770   verifyFormat("vector<int> (*foo_)[6];");
7771 }
7772 
TEST_F(FormatTest,BreaksLongVariableDeclarations)7773 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
7774   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7775                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
7776   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
7777                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
7778   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7779                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
7780 
7781   // Different ways of ()-initializiation.
7782   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7783                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
7784   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7785                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
7786   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7787                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
7788   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7789                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
7790 
7791   // Lambdas should not confuse the variable declaration heuristic.
7792   verifyFormat("LooooooooooooooooongType\n"
7793                "    variable(nullptr, [](A *a) {});",
7794                getLLVMStyleWithColumns(40));
7795 }
7796 
TEST_F(FormatTest,BreaksLongDeclarations)7797 TEST_F(FormatTest, BreaksLongDeclarations) {
7798   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
7799                "    AnotherNameForTheLongType;");
7800   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
7801                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7802   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7803                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
7804   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
7805                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
7806   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7807                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
7808   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
7809                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
7810   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
7811                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
7812   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
7813                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
7814   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7815                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
7816   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7817                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
7818   FormatStyle Indented = getLLVMStyle();
7819   Indented.IndentWrappedFunctionNames = true;
7820   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7821                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
7822                Indented);
7823   verifyFormat(
7824       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7825       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
7826       Indented);
7827   verifyFormat(
7828       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
7829       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
7830       Indented);
7831   verifyFormat(
7832       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
7833       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
7834       Indented);
7835 
7836   // FIXME: Without the comment, this breaks after "(".
7837   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
7838                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
7839                getGoogleStyle());
7840 
7841   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
7842                "                  int LoooooooooooooooooooongParam2) {}");
7843   verifyFormat(
7844       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
7845       "                                   SourceLocation L, IdentifierIn *II,\n"
7846       "                                   Type *T) {}");
7847   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
7848                "ReallyReaaallyLongFunctionName(\n"
7849                "    const std::string &SomeParameter,\n"
7850                "    const SomeType<string, SomeOtherTemplateParameter>\n"
7851                "        &ReallyReallyLongParameterName,\n"
7852                "    const SomeType<string, SomeOtherTemplateParameter>\n"
7853                "        &AnotherLongParameterName) {}");
7854   verifyFormat("template <typename A>\n"
7855                "SomeLoooooooooooooooooooooongType<\n"
7856                "    typename some_namespace::SomeOtherType<A>::Type>\n"
7857                "Function() {}");
7858 
7859   verifyGoogleFormat(
7860       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
7861       "    aaaaaaaaaaaaaaaaaaaaaaa;");
7862   verifyGoogleFormat(
7863       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
7864       "                                   SourceLocation L) {}");
7865   verifyGoogleFormat(
7866       "some_namespace::LongReturnType\n"
7867       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
7868       "    int first_long_parameter, int second_parameter) {}");
7869 
7870   verifyGoogleFormat("template <typename T>\n"
7871                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
7872                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
7873   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7874                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
7875 
7876   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
7877                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7878                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7879   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7880                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
7881                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
7882   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7883                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7884                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
7885                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7886 
7887   verifyFormat("template <typename T> // Templates on own line.\n"
7888                "static int            // Some comment.\n"
7889                "MyFunction(int a);",
7890                getLLVMStyle());
7891 }
7892 
TEST_F(FormatTest,FormatsArrays)7893 TEST_F(FormatTest, FormatsArrays) {
7894   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
7895                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
7896   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
7897                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
7898   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
7899                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
7900   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7901                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
7902   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7903                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
7904   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7905                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
7906                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
7907   verifyFormat(
7908       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
7909       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
7910       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
7911   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
7912                "    .aaaaaaaaaaaaaaaaaaaaaa();");
7913 
7914   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
7915                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
7916   verifyFormat(
7917       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
7918       "                                  .aaaaaaa[0]\n"
7919       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
7920   verifyFormat("a[::b::c];");
7921 
7922   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
7923 
7924   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
7925   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
7926 }
7927 
TEST_F(FormatTest,LineStartsWithSpecialCharacter)7928 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
7929   verifyFormat("(a)->b();");
7930   verifyFormat("--a;");
7931 }
7932 
TEST_F(FormatTest,HandlesIncludeDirectives)7933 TEST_F(FormatTest, HandlesIncludeDirectives) {
7934   verifyFormat("#include <string>\n"
7935                "#include <a/b/c.h>\n"
7936                "#include \"a/b/string\"\n"
7937                "#include \"string.h\"\n"
7938                "#include \"string.h\"\n"
7939                "#include <a-a>\n"
7940                "#include < path with space >\n"
7941                "#include_next <test.h>"
7942                "#include \"abc.h\" // this is included for ABC\n"
7943                "#include \"some long include\" // with a comment\n"
7944                "#include \"some very long include path\"\n"
7945                "#include <some/very/long/include/path>\n",
7946                getLLVMStyleWithColumns(35));
7947   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
7948   EXPECT_EQ("#include <a>", format("#include<a>"));
7949 
7950   verifyFormat("#import <string>");
7951   verifyFormat("#import <a/b/c.h>");
7952   verifyFormat("#import \"a/b/string\"");
7953   verifyFormat("#import \"string.h\"");
7954   verifyFormat("#import \"string.h\"");
7955   verifyFormat("#if __has_include(<strstream>)\n"
7956                "#include <strstream>\n"
7957                "#endif");
7958 
7959   verifyFormat("#define MY_IMPORT <a/b>");
7960 
7961   verifyFormat("#if __has_include(<a/b>)");
7962   verifyFormat("#if __has_include_next(<a/b>)");
7963   verifyFormat("#define F __has_include(<a/b>)");
7964   verifyFormat("#define F __has_include_next(<a/b>)");
7965 
7966   // Protocol buffer definition or missing "#".
7967   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
7968                getLLVMStyleWithColumns(30));
7969 
7970   FormatStyle Style = getLLVMStyle();
7971   Style.AlwaysBreakBeforeMultilineStrings = true;
7972   Style.ColumnLimit = 0;
7973   verifyFormat("#import \"abc.h\"", Style);
7974 
7975   // But 'import' might also be a regular C++ namespace.
7976   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7977                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7978 }
7979 
7980 //===----------------------------------------------------------------------===//
7981 // Error recovery tests.
7982 //===----------------------------------------------------------------------===//
7983 
TEST_F(FormatTest,IncompleteParameterLists)7984 TEST_F(FormatTest, IncompleteParameterLists) {
7985   FormatStyle NoBinPacking = getLLVMStyle();
7986   NoBinPacking.BinPackParameters = false;
7987   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
7988                "                        double *min_x,\n"
7989                "                        double *max_x,\n"
7990                "                        double *min_y,\n"
7991                "                        double *max_y,\n"
7992                "                        double *min_z,\n"
7993                "                        double *max_z, ) {}",
7994                NoBinPacking);
7995 }
7996 
TEST_F(FormatTest,IncorrectCodeTrailingStuff)7997 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
7998   verifyFormat("void f() { return; }\n42");
7999   verifyFormat("void f() {\n"
8000                "  if (0)\n"
8001                "    return;\n"
8002                "}\n"
8003                "42");
8004   verifyFormat("void f() { return }\n42");
8005   verifyFormat("void f() {\n"
8006                "  if (0)\n"
8007                "    return\n"
8008                "}\n"
8009                "42");
8010 }
8011 
TEST_F(FormatTest,IncorrectCodeMissingSemicolon)8012 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
8013   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
8014   EXPECT_EQ("void f() {\n"
8015             "  if (a)\n"
8016             "    return\n"
8017             "}",
8018             format("void  f  (  )  {  if  ( a )  return  }"));
8019   EXPECT_EQ("namespace N {\n"
8020             "void f()\n"
8021             "}",
8022             format("namespace  N  {  void f()  }"));
8023   EXPECT_EQ("namespace N {\n"
8024             "void f() {}\n"
8025             "void g()\n"
8026             "} // namespace N",
8027             format("namespace N  { void f( ) { } void g( ) }"));
8028 }
8029 
TEST_F(FormatTest,IndentationWithinColumnLimitNotPossible)8030 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
8031   verifyFormat("int aaaaaaaa =\n"
8032                "    // Overlylongcomment\n"
8033                "    b;",
8034                getLLVMStyleWithColumns(20));
8035   verifyFormat("function(\n"
8036                "    ShortArgument,\n"
8037                "    LoooooooooooongArgument);\n",
8038                getLLVMStyleWithColumns(20));
8039 }
8040 
TEST_F(FormatTest,IncorrectAccessSpecifier)8041 TEST_F(FormatTest, IncorrectAccessSpecifier) {
8042   verifyFormat("public:");
8043   verifyFormat("class A {\n"
8044                "public\n"
8045                "  void f() {}\n"
8046                "};");
8047   verifyFormat("public\n"
8048                "int qwerty;");
8049   verifyFormat("public\n"
8050                "B {}");
8051   verifyFormat("public\n"
8052                "{}");
8053   verifyFormat("public\n"
8054                "B { int x; }");
8055 }
8056 
TEST_F(FormatTest,IncorrectCodeUnbalancedBraces)8057 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
8058   verifyFormat("{");
8059   verifyFormat("#})");
8060   verifyNoCrash("(/**/[:!] ?[).");
8061 }
8062 
TEST_F(FormatTest,IncorrectUnbalancedBracesInMacrosWithUnicode)8063 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
8064   // Found by oss-fuzz:
8065   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
8066   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
8067   Style.ColumnLimit = 60;
8068   verifyNoCrash(
8069       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
8070       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
8071       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
8072       Style);
8073 }
8074 
TEST_F(FormatTest,IncorrectCodeDoNoWhile)8075 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
8076   verifyFormat("do {\n}");
8077   verifyFormat("do {\n}\n"
8078                "f();");
8079   verifyFormat("do {\n}\n"
8080                "wheeee(fun);");
8081   verifyFormat("do {\n"
8082                "  f();\n"
8083                "}");
8084 }
8085 
TEST_F(FormatTest,IncorrectCodeMissingParens)8086 TEST_F(FormatTest, IncorrectCodeMissingParens) {
8087   verifyFormat("if {\n  foo;\n  foo();\n}");
8088   verifyFormat("switch {\n  foo;\n  foo();\n}");
8089   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
8090   verifyFormat("while {\n  foo;\n  foo();\n}");
8091   verifyFormat("do {\n  foo;\n  foo();\n} while;");
8092 }
8093 
TEST_F(FormatTest,DoesNotTouchUnwrappedLinesWithErrors)8094 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
8095   verifyIncompleteFormat("namespace {\n"
8096                          "class Foo { Foo (\n"
8097                          "};\n"
8098                          "} // namespace");
8099 }
8100 
TEST_F(FormatTest,IncorrectCodeErrorDetection)8101 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
8102   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
8103   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
8104   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
8105   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
8106 
8107   EXPECT_EQ("{\n"
8108             "  {\n"
8109             "    breakme(\n"
8110             "        qwe);\n"
8111             "  }\n",
8112             format("{\n"
8113                    "    {\n"
8114                    " breakme(qwe);\n"
8115                    "}\n",
8116                    getLLVMStyleWithColumns(10)));
8117 }
8118 
TEST_F(FormatTest,LayoutCallsInsideBraceInitializers)8119 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
8120   verifyFormat("int x = {\n"
8121                "    avariable,\n"
8122                "    b(alongervariable)};",
8123                getLLVMStyleWithColumns(25));
8124 }
8125 
TEST_F(FormatTest,LayoutBraceInitializersInReturnStatement)8126 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
8127   verifyFormat("return (a)(b){1, 2, 3};");
8128 }
8129 
TEST_F(FormatTest,LayoutCxx11BraceInitializers)8130 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
8131   verifyFormat("vector<int> x{1, 2, 3, 4};");
8132   verifyFormat("vector<int> x{\n"
8133                "    1,\n"
8134                "    2,\n"
8135                "    3,\n"
8136                "    4,\n"
8137                "};");
8138   verifyFormat("vector<T> x{{}, {}, {}, {}};");
8139   verifyFormat("f({1, 2});");
8140   verifyFormat("auto v = Foo{-1};");
8141   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
8142   verifyFormat("Class::Class : member{1, 2, 3} {}");
8143   verifyFormat("new vector<int>{1, 2, 3};");
8144   verifyFormat("new int[3]{1, 2, 3};");
8145   verifyFormat("new int{1};");
8146   verifyFormat("return {arg1, arg2};");
8147   verifyFormat("return {arg1, SomeType{parameter}};");
8148   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
8149   verifyFormat("new T{arg1, arg2};");
8150   verifyFormat("f(MyMap[{composite, key}]);");
8151   verifyFormat("class Class {\n"
8152                "  T member = {arg1, arg2};\n"
8153                "};");
8154   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
8155   verifyFormat("const struct A a = {.a = 1, .b = 2};");
8156   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
8157   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
8158   verifyFormat("int a = std::is_integral<int>{} + 0;");
8159 
8160   verifyFormat("int foo(int i) { return fo1{}(i); }");
8161   verifyFormat("int foo(int i) { return fo1{}(i); }");
8162   verifyFormat("auto i = decltype(x){};");
8163   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
8164   verifyFormat("Node n{1, Node{1000}, //\n"
8165                "       2};");
8166   verifyFormat("Aaaa aaaaaaa{\n"
8167                "    {\n"
8168                "        aaaa,\n"
8169                "    },\n"
8170                "};");
8171   verifyFormat("class C : public D {\n"
8172                "  SomeClass SC{2};\n"
8173                "};");
8174   verifyFormat("class C : public A {\n"
8175                "  class D : public B {\n"
8176                "    void f() { int i{2}; }\n"
8177                "  };\n"
8178                "};");
8179   verifyFormat("#define A {a, a},");
8180 
8181   // Avoid breaking between equal sign and opening brace
8182   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
8183   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
8184   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
8185                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
8186                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
8187                "     {\"ccccccccccccccccccccc\", 2}};",
8188                AvoidBreakingFirstArgument);
8189 
8190   // Binpacking only if there is no trailing comma
8191   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
8192                "                      cccccccccc, dddddddddd};",
8193                getLLVMStyleWithColumns(50));
8194   verifyFormat("const Aaaaaa aaaaa = {\n"
8195                "    aaaaaaaaaaa,\n"
8196                "    bbbbbbbbbbb,\n"
8197                "    ccccccccccc,\n"
8198                "    ddddddddddd,\n"
8199                "};",
8200                getLLVMStyleWithColumns(50));
8201 
8202   // Cases where distinguising braced lists and blocks is hard.
8203   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
8204   verifyFormat("void f() {\n"
8205                "  return; // comment\n"
8206                "}\n"
8207                "SomeType t;");
8208   verifyFormat("void f() {\n"
8209                "  if (a) {\n"
8210                "    f();\n"
8211                "  }\n"
8212                "}\n"
8213                "SomeType t;");
8214 
8215   // In combination with BinPackArguments = false.
8216   FormatStyle NoBinPacking = getLLVMStyle();
8217   NoBinPacking.BinPackArguments = false;
8218   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
8219                "                      bbbbb,\n"
8220                "                      ccccc,\n"
8221                "                      ddddd,\n"
8222                "                      eeeee,\n"
8223                "                      ffffff,\n"
8224                "                      ggggg,\n"
8225                "                      hhhhhh,\n"
8226                "                      iiiiii,\n"
8227                "                      jjjjjj,\n"
8228                "                      kkkkkk};",
8229                NoBinPacking);
8230   verifyFormat("const Aaaaaa aaaaa = {\n"
8231                "    aaaaa,\n"
8232                "    bbbbb,\n"
8233                "    ccccc,\n"
8234                "    ddddd,\n"
8235                "    eeeee,\n"
8236                "    ffffff,\n"
8237                "    ggggg,\n"
8238                "    hhhhhh,\n"
8239                "    iiiiii,\n"
8240                "    jjjjjj,\n"
8241                "    kkkkkk,\n"
8242                "};",
8243                NoBinPacking);
8244   verifyFormat(
8245       "const Aaaaaa aaaaa = {\n"
8246       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
8247       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
8248       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
8249       "};",
8250       NoBinPacking);
8251 
8252   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8253   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
8254             "    CDDDP83848_BMCR_REGISTER,\n"
8255             "    CDDDP83848_BMSR_REGISTER,\n"
8256             "    CDDDP83848_RBR_REGISTER};",
8257             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
8258                    "                                CDDDP83848_BMSR_REGISTER,\n"
8259                    "                                CDDDP83848_RBR_REGISTER};",
8260                    NoBinPacking));
8261 
8262   // FIXME: The alignment of these trailing comments might be bad. Then again,
8263   // this might be utterly useless in real code.
8264   verifyFormat("Constructor::Constructor()\n"
8265                "    : some_value{         //\n"
8266                "                 aaaaaaa, //\n"
8267                "                 bbbbbbb} {}");
8268 
8269   // In braced lists, the first comment is always assumed to belong to the
8270   // first element. Thus, it can be moved to the next or previous line as
8271   // appropriate.
8272   EXPECT_EQ("function({// First element:\n"
8273             "          1,\n"
8274             "          // Second element:\n"
8275             "          2});",
8276             format("function({\n"
8277                    "    // First element:\n"
8278                    "    1,\n"
8279                    "    // Second element:\n"
8280                    "    2});"));
8281   EXPECT_EQ("std::vector<int> MyNumbers{\n"
8282             "    // First element:\n"
8283             "    1,\n"
8284             "    // Second element:\n"
8285             "    2};",
8286             format("std::vector<int> MyNumbers{// First element:\n"
8287                    "                           1,\n"
8288                    "                           // Second element:\n"
8289                    "                           2};",
8290                    getLLVMStyleWithColumns(30)));
8291   // A trailing comma should still lead to an enforced line break and no
8292   // binpacking.
8293   EXPECT_EQ("vector<int> SomeVector = {\n"
8294             "    // aaa\n"
8295             "    1,\n"
8296             "    2,\n"
8297             "};",
8298             format("vector<int> SomeVector = { // aaa\n"
8299                    "    1, 2, };"));
8300 
8301   FormatStyle ExtraSpaces = getLLVMStyle();
8302   ExtraSpaces.Cpp11BracedListStyle = false;
8303   ExtraSpaces.ColumnLimit = 75;
8304   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
8305   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
8306   verifyFormat("f({ 1, 2 });", ExtraSpaces);
8307   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
8308   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
8309   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
8310   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
8311   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
8312   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
8313   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
8314   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
8315   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
8316   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
8317   verifyFormat("class Class {\n"
8318                "  T member = { arg1, arg2 };\n"
8319                "};",
8320                ExtraSpaces);
8321   verifyFormat(
8322       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8323       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
8324       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
8325       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
8326       ExtraSpaces);
8327   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
8328   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
8329                ExtraSpaces);
8330   verifyFormat(
8331       "someFunction(OtherParam,\n"
8332       "             BracedList{ // comment 1 (Forcing interesting break)\n"
8333       "                         param1, param2,\n"
8334       "                         // comment 2\n"
8335       "                         param3, param4 });",
8336       ExtraSpaces);
8337   verifyFormat(
8338       "std::this_thread::sleep_for(\n"
8339       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
8340       ExtraSpaces);
8341   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
8342                "    aaaaaaa,\n"
8343                "    aaaaaaaaaa,\n"
8344                "    aaaaa,\n"
8345                "    aaaaaaaaaaaaaaa,\n"
8346                "    aaa,\n"
8347                "    aaaaaaaaaa,\n"
8348                "    a,\n"
8349                "    aaaaaaaaaaaaaaaaaaaaa,\n"
8350                "    aaaaaaaaaaaa,\n"
8351                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
8352                "    aaaaaaa,\n"
8353                "    a};");
8354   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
8355   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
8356   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
8357 
8358   // Avoid breaking between initializer/equal sign and opening brace
8359   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
8360   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
8361                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
8362                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
8363                "  { \"ccccccccccccccccccccc\", 2 }\n"
8364                "};",
8365                ExtraSpaces);
8366   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
8367                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
8368                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
8369                "  { \"ccccccccccccccccccccc\", 2 }\n"
8370                "};",
8371                ExtraSpaces);
8372 
8373   FormatStyle SpaceBeforeBrace = getLLVMStyle();
8374   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
8375   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
8376   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
8377 
8378   FormatStyle SpaceBetweenBraces = getLLVMStyle();
8379   SpaceBetweenBraces.SpacesInAngles = true;
8380   SpaceBetweenBraces.SpacesInParentheses = true;
8381   SpaceBetweenBraces.SpacesInSquareBrackets = true;
8382   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
8383   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
8384   verifyFormat("vector< int > x{ // comment 1\n"
8385                "                 1, 2, 3, 4 };",
8386                SpaceBetweenBraces);
8387   SpaceBetweenBraces.ColumnLimit = 20;
8388   EXPECT_EQ("vector< int > x{\n"
8389             "    1, 2, 3, 4 };",
8390             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
8391   SpaceBetweenBraces.ColumnLimit = 24;
8392   EXPECT_EQ("vector< int > x{ 1, 2,\n"
8393             "                 3, 4 };",
8394             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
8395   EXPECT_EQ("vector< int > x{\n"
8396             "    1,\n"
8397             "    2,\n"
8398             "    3,\n"
8399             "    4,\n"
8400             "};",
8401             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
8402   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
8403   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
8404   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
8405 }
8406 
TEST_F(FormatTest,FormatsBracedListsInColumnLayout)8407 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
8408   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8409                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8410                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8411                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8412                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8413                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
8414   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
8415                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8416                "                 1, 22, 333, 4444, 55555, //\n"
8417                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8418                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
8419   verifyFormat(
8420       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
8421       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
8422       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
8423       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
8424       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
8425       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
8426       "                 7777777};");
8427   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
8428                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
8429                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
8430   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
8431                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
8432                "    // Separating comment.\n"
8433                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
8434   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
8435                "    // Leading comment\n"
8436                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
8437                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
8438   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
8439                "                 1, 1, 1, 1};",
8440                getLLVMStyleWithColumns(39));
8441   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
8442                "                 1, 1, 1, 1};",
8443                getLLVMStyleWithColumns(38));
8444   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
8445                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
8446                getLLVMStyleWithColumns(43));
8447   verifyFormat(
8448       "static unsigned SomeValues[10][3] = {\n"
8449       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
8450       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
8451   verifyFormat("static auto fields = new vector<string>{\n"
8452                "    \"aaaaaaaaaaaaa\",\n"
8453                "    \"aaaaaaaaaaaaa\",\n"
8454                "    \"aaaaaaaaaaaa\",\n"
8455                "    \"aaaaaaaaaaaaaa\",\n"
8456                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
8457                "    \"aaaaaaaaaaaa\",\n"
8458                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
8459                "};");
8460   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
8461   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
8462                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
8463                "                 3, cccccccccccccccccccccc};",
8464                getLLVMStyleWithColumns(60));
8465 
8466   // Trailing commas.
8467   verifyFormat("vector<int> x = {\n"
8468                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
8469                "};",
8470                getLLVMStyleWithColumns(39));
8471   verifyFormat("vector<int> x = {\n"
8472                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
8473                "};",
8474                getLLVMStyleWithColumns(39));
8475   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
8476                "                 1, 1, 1, 1,\n"
8477                "                 /**/ /**/};",
8478                getLLVMStyleWithColumns(39));
8479 
8480   // Trailing comment in the first line.
8481   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
8482                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
8483                "    111111111,  222222222,  3333333333,  444444444,  //\n"
8484                "    11111111,   22222222,   333333333,   44444444};");
8485   // Trailing comment in the last line.
8486   verifyFormat("int aaaaa[] = {\n"
8487                "    1, 2, 3, // comment\n"
8488                "    4, 5, 6  // comment\n"
8489                "};");
8490 
8491   // With nested lists, we should either format one item per line or all nested
8492   // lists one on line.
8493   // FIXME: For some nested lists, we can do better.
8494   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
8495                "        {aaaaaaaaaaaaaaaaaaa},\n"
8496                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
8497                "        {aaaaaaaaaaaaaaaaa}};",
8498                getLLVMStyleWithColumns(60));
8499   verifyFormat(
8500       "SomeStruct my_struct_array = {\n"
8501       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
8502       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
8503       "    {aaa, aaa},\n"
8504       "    {aaa, aaa},\n"
8505       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
8506       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
8507       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
8508 
8509   // No column layout should be used here.
8510   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
8511                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
8512 
8513   verifyNoCrash("a<,");
8514 
8515   // No braced initializer here.
8516   verifyFormat("void f() {\n"
8517                "  struct Dummy {};\n"
8518                "  f(v);\n"
8519                "}");
8520 
8521   // Long lists should be formatted in columns even if they are nested.
8522   verifyFormat(
8523       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8524       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8525       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8526       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8527       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8528       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
8529 
8530   // Allow "single-column" layout even if that violates the column limit. There
8531   // isn't going to be a better way.
8532   verifyFormat("std::vector<int> a = {\n"
8533                "    aaaaaaaa,\n"
8534                "    aaaaaaaa,\n"
8535                "    aaaaaaaa,\n"
8536                "    aaaaaaaa,\n"
8537                "    aaaaaaaaaa,\n"
8538                "    aaaaaaaa,\n"
8539                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
8540                getLLVMStyleWithColumns(30));
8541   verifyFormat("vector<int> aaaa = {\n"
8542                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8543                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8544                "    aaaaaa.aaaaaaa,\n"
8545                "    aaaaaa.aaaaaaa,\n"
8546                "    aaaaaa.aaaaaaa,\n"
8547                "    aaaaaa.aaaaaaa,\n"
8548                "};");
8549 
8550   // Don't create hanging lists.
8551   verifyFormat("someFunction(Param, {List1, List2,\n"
8552                "                     List3});",
8553                getLLVMStyleWithColumns(35));
8554   verifyFormat("someFunction(Param, Param,\n"
8555                "             {List1, List2,\n"
8556                "              List3});",
8557                getLLVMStyleWithColumns(35));
8558   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
8559                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
8560 }
8561 
TEST_F(FormatTest,PullTrivialFunctionDefinitionsIntoSingleLine)8562 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
8563   FormatStyle DoNotMerge = getLLVMStyle();
8564   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8565 
8566   verifyFormat("void f() { return 42; }");
8567   verifyFormat("void f() {\n"
8568                "  return 42;\n"
8569                "}",
8570                DoNotMerge);
8571   verifyFormat("void f() {\n"
8572                "  // Comment\n"
8573                "}");
8574   verifyFormat("{\n"
8575                "#error {\n"
8576                "  int a;\n"
8577                "}");
8578   verifyFormat("{\n"
8579                "  int a;\n"
8580                "#error {\n"
8581                "}");
8582   verifyFormat("void f() {} // comment");
8583   verifyFormat("void f() { int a; } // comment");
8584   verifyFormat("void f() {\n"
8585                "} // comment",
8586                DoNotMerge);
8587   verifyFormat("void f() {\n"
8588                "  int a;\n"
8589                "} // comment",
8590                DoNotMerge);
8591   verifyFormat("void f() {\n"
8592                "} // comment",
8593                getLLVMStyleWithColumns(15));
8594 
8595   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
8596   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
8597 
8598   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
8599   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
8600   verifyFormat("class C {\n"
8601                "  C()\n"
8602                "      : iiiiiiii(nullptr),\n"
8603                "        kkkkkkk(nullptr),\n"
8604                "        mmmmmmm(nullptr),\n"
8605                "        nnnnnnn(nullptr) {}\n"
8606                "};",
8607                getGoogleStyle());
8608 
8609   FormatStyle NoColumnLimit = getLLVMStyle();
8610   NoColumnLimit.ColumnLimit = 0;
8611   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
8612   EXPECT_EQ("class C {\n"
8613             "  A() : b(0) {}\n"
8614             "};",
8615             format("class C{A():b(0){}};", NoColumnLimit));
8616   EXPECT_EQ("A()\n"
8617             "    : b(0) {\n"
8618             "}",
8619             format("A()\n:b(0)\n{\n}", NoColumnLimit));
8620 
8621   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
8622   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
8623       FormatStyle::SFS_None;
8624   EXPECT_EQ("A()\n"
8625             "    : b(0) {\n"
8626             "}",
8627             format("A():b(0){}", DoNotMergeNoColumnLimit));
8628   EXPECT_EQ("A()\n"
8629             "    : b(0) {\n"
8630             "}",
8631             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
8632 
8633   verifyFormat("#define A          \\\n"
8634                "  void f() {       \\\n"
8635                "    int i;         \\\n"
8636                "  }",
8637                getLLVMStyleWithColumns(20));
8638   verifyFormat("#define A           \\\n"
8639                "  void f() { int i; }",
8640                getLLVMStyleWithColumns(21));
8641   verifyFormat("#define A            \\\n"
8642                "  void f() {         \\\n"
8643                "    int i;           \\\n"
8644                "  }                  \\\n"
8645                "  int j;",
8646                getLLVMStyleWithColumns(22));
8647   verifyFormat("#define A             \\\n"
8648                "  void f() { int i; } \\\n"
8649                "  int j;",
8650                getLLVMStyleWithColumns(23));
8651 }
8652 
TEST_F(FormatTest,PullEmptyFunctionDefinitionsIntoSingleLine)8653 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
8654   FormatStyle MergeEmptyOnly = getLLVMStyle();
8655   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
8656   verifyFormat("class C {\n"
8657                "  int f() {}\n"
8658                "};",
8659                MergeEmptyOnly);
8660   verifyFormat("class C {\n"
8661                "  int f() {\n"
8662                "    return 42;\n"
8663                "  }\n"
8664                "};",
8665                MergeEmptyOnly);
8666   verifyFormat("int f() {}", MergeEmptyOnly);
8667   verifyFormat("int f() {\n"
8668                "  return 42;\n"
8669                "}",
8670                MergeEmptyOnly);
8671 
8672   // Also verify behavior when BraceWrapping.AfterFunction = true
8673   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
8674   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
8675   verifyFormat("int f() {}", MergeEmptyOnly);
8676   verifyFormat("class C {\n"
8677                "  int f() {}\n"
8678                "};",
8679                MergeEmptyOnly);
8680 }
8681 
TEST_F(FormatTest,PullInlineFunctionDefinitionsIntoSingleLine)8682 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
8683   FormatStyle MergeInlineOnly = getLLVMStyle();
8684   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
8685   verifyFormat("class C {\n"
8686                "  int f() { return 42; }\n"
8687                "};",
8688                MergeInlineOnly);
8689   verifyFormat("int f() {\n"
8690                "  return 42;\n"
8691                "}",
8692                MergeInlineOnly);
8693 
8694   // SFS_Inline implies SFS_Empty
8695   verifyFormat("class C {\n"
8696                "  int f() {}\n"
8697                "};",
8698                MergeInlineOnly);
8699   verifyFormat("int f() {}", MergeInlineOnly);
8700 
8701   // Also verify behavior when BraceWrapping.AfterFunction = true
8702   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
8703   MergeInlineOnly.BraceWrapping.AfterFunction = true;
8704   verifyFormat("class C {\n"
8705                "  int f() { return 42; }\n"
8706                "};",
8707                MergeInlineOnly);
8708   verifyFormat("int f()\n"
8709                "{\n"
8710                "  return 42;\n"
8711                "}",
8712                MergeInlineOnly);
8713 
8714   // SFS_Inline implies SFS_Empty
8715   verifyFormat("int f() {}", MergeInlineOnly);
8716   verifyFormat("class C {\n"
8717                "  int f() {}\n"
8718                "};",
8719                MergeInlineOnly);
8720 }
8721 
TEST_F(FormatTest,PullInlineOnlyFunctionDefinitionsIntoSingleLine)8722 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
8723   FormatStyle MergeInlineOnly = getLLVMStyle();
8724   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
8725       FormatStyle::SFS_InlineOnly;
8726   verifyFormat("class C {\n"
8727                "  int f() { return 42; }\n"
8728                "};",
8729                MergeInlineOnly);
8730   verifyFormat("int f() {\n"
8731                "  return 42;\n"
8732                "}",
8733                MergeInlineOnly);
8734 
8735   // SFS_InlineOnly does not imply SFS_Empty
8736   verifyFormat("class C {\n"
8737                "  int f() {}\n"
8738                "};",
8739                MergeInlineOnly);
8740   verifyFormat("int f() {\n"
8741                "}",
8742                MergeInlineOnly);
8743 
8744   // Also verify behavior when BraceWrapping.AfterFunction = true
8745   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
8746   MergeInlineOnly.BraceWrapping.AfterFunction = true;
8747   verifyFormat("class C {\n"
8748                "  int f() { return 42; }\n"
8749                "};",
8750                MergeInlineOnly);
8751   verifyFormat("int f()\n"
8752                "{\n"
8753                "  return 42;\n"
8754                "}",
8755                MergeInlineOnly);
8756 
8757   // SFS_InlineOnly does not imply SFS_Empty
8758   verifyFormat("int f()\n"
8759                "{\n"
8760                "}",
8761                MergeInlineOnly);
8762   verifyFormat("class C {\n"
8763                "  int f() {}\n"
8764                "};",
8765                MergeInlineOnly);
8766 }
8767 
TEST_F(FormatTest,SplitEmptyFunction)8768 TEST_F(FormatTest, SplitEmptyFunction) {
8769   FormatStyle Style = getLLVMStyle();
8770   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8771   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8772   Style.BraceWrapping.AfterFunction = true;
8773   Style.BraceWrapping.SplitEmptyFunction = false;
8774   Style.ColumnLimit = 40;
8775 
8776   verifyFormat("int f()\n"
8777                "{}",
8778                Style);
8779   verifyFormat("int f()\n"
8780                "{\n"
8781                "  return 42;\n"
8782                "}",
8783                Style);
8784   verifyFormat("int f()\n"
8785                "{\n"
8786                "  // some comment\n"
8787                "}",
8788                Style);
8789 
8790   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
8791   verifyFormat("int f() {}", Style);
8792   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
8793                "{}",
8794                Style);
8795   verifyFormat("int f()\n"
8796                "{\n"
8797                "  return 0;\n"
8798                "}",
8799                Style);
8800 
8801   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
8802   verifyFormat("class Foo {\n"
8803                "  int f() {}\n"
8804                "};\n",
8805                Style);
8806   verifyFormat("class Foo {\n"
8807                "  int f() { return 0; }\n"
8808                "};\n",
8809                Style);
8810   verifyFormat("class Foo {\n"
8811                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
8812                "  {}\n"
8813                "};\n",
8814                Style);
8815   verifyFormat("class Foo {\n"
8816                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
8817                "  {\n"
8818                "    return 0;\n"
8819                "  }\n"
8820                "};\n",
8821                Style);
8822 
8823   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
8824   verifyFormat("int f() {}", Style);
8825   verifyFormat("int f() { return 0; }", Style);
8826   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
8827                "{}",
8828                Style);
8829   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
8830                "{\n"
8831                "  return 0;\n"
8832                "}",
8833                Style);
8834 }
TEST_F(FormatTest,KeepShortFunctionAfterPPElse)8835 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
8836   FormatStyle Style = getLLVMStyle();
8837   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
8838   verifyFormat("#ifdef A\n"
8839                "int f() {}\n"
8840                "#else\n"
8841                "int g() {}\n"
8842                "#endif",
8843                Style);
8844 }
8845 
TEST_F(FormatTest,SplitEmptyClass)8846 TEST_F(FormatTest, SplitEmptyClass) {
8847   FormatStyle Style = getLLVMStyle();
8848   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8849   Style.BraceWrapping.AfterClass = true;
8850   Style.BraceWrapping.SplitEmptyRecord = false;
8851 
8852   verifyFormat("class Foo\n"
8853                "{};",
8854                Style);
8855   verifyFormat("/* something */ class Foo\n"
8856                "{};",
8857                Style);
8858   verifyFormat("template <typename X> class Foo\n"
8859                "{};",
8860                Style);
8861   verifyFormat("class Foo\n"
8862                "{\n"
8863                "  Foo();\n"
8864                "};",
8865                Style);
8866   verifyFormat("typedef class Foo\n"
8867                "{\n"
8868                "} Foo_t;",
8869                Style);
8870 }
8871 
TEST_F(FormatTest,SplitEmptyStruct)8872 TEST_F(FormatTest, SplitEmptyStruct) {
8873   FormatStyle Style = getLLVMStyle();
8874   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8875   Style.BraceWrapping.AfterStruct = true;
8876   Style.BraceWrapping.SplitEmptyRecord = false;
8877 
8878   verifyFormat("struct Foo\n"
8879                "{};",
8880                Style);
8881   verifyFormat("/* something */ struct Foo\n"
8882                "{};",
8883                Style);
8884   verifyFormat("template <typename X> struct Foo\n"
8885                "{};",
8886                Style);
8887   verifyFormat("struct Foo\n"
8888                "{\n"
8889                "  Foo();\n"
8890                "};",
8891                Style);
8892   verifyFormat("typedef struct Foo\n"
8893                "{\n"
8894                "} Foo_t;",
8895                Style);
8896   // typedef struct Bar {} Bar_t;
8897 }
8898 
TEST_F(FormatTest,SplitEmptyUnion)8899 TEST_F(FormatTest, SplitEmptyUnion) {
8900   FormatStyle Style = getLLVMStyle();
8901   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8902   Style.BraceWrapping.AfterUnion = true;
8903   Style.BraceWrapping.SplitEmptyRecord = false;
8904 
8905   verifyFormat("union Foo\n"
8906                "{};",
8907                Style);
8908   verifyFormat("/* something */ union Foo\n"
8909                "{};",
8910                Style);
8911   verifyFormat("union Foo\n"
8912                "{\n"
8913                "  A,\n"
8914                "};",
8915                Style);
8916   verifyFormat("typedef union Foo\n"
8917                "{\n"
8918                "} Foo_t;",
8919                Style);
8920 }
8921 
TEST_F(FormatTest,SplitEmptyNamespace)8922 TEST_F(FormatTest, SplitEmptyNamespace) {
8923   FormatStyle Style = getLLVMStyle();
8924   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8925   Style.BraceWrapping.AfterNamespace = true;
8926   Style.BraceWrapping.SplitEmptyNamespace = false;
8927 
8928   verifyFormat("namespace Foo\n"
8929                "{};",
8930                Style);
8931   verifyFormat("/* something */ namespace Foo\n"
8932                "{};",
8933                Style);
8934   verifyFormat("inline namespace Foo\n"
8935                "{};",
8936                Style);
8937   verifyFormat("/* something */ inline namespace Foo\n"
8938                "{};",
8939                Style);
8940   verifyFormat("export namespace Foo\n"
8941                "{};",
8942                Style);
8943   verifyFormat("namespace Foo\n"
8944                "{\n"
8945                "void Bar();\n"
8946                "};",
8947                Style);
8948 }
8949 
TEST_F(FormatTest,NeverMergeShortRecords)8950 TEST_F(FormatTest, NeverMergeShortRecords) {
8951   FormatStyle Style = getLLVMStyle();
8952 
8953   verifyFormat("class Foo {\n"
8954                "  Foo();\n"
8955                "};",
8956                Style);
8957   verifyFormat("typedef class Foo {\n"
8958                "  Foo();\n"
8959                "} Foo_t;",
8960                Style);
8961   verifyFormat("struct Foo {\n"
8962                "  Foo();\n"
8963                "};",
8964                Style);
8965   verifyFormat("typedef struct Foo {\n"
8966                "  Foo();\n"
8967                "} Foo_t;",
8968                Style);
8969   verifyFormat("union Foo {\n"
8970                "  A,\n"
8971                "};",
8972                Style);
8973   verifyFormat("typedef union Foo {\n"
8974                "  A,\n"
8975                "} Foo_t;",
8976                Style);
8977   verifyFormat("namespace Foo {\n"
8978                "void Bar();\n"
8979                "};",
8980                Style);
8981 
8982   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8983   Style.BraceWrapping.AfterClass = true;
8984   Style.BraceWrapping.AfterStruct = true;
8985   Style.BraceWrapping.AfterUnion = true;
8986   Style.BraceWrapping.AfterNamespace = true;
8987   verifyFormat("class Foo\n"
8988                "{\n"
8989                "  Foo();\n"
8990                "};",
8991                Style);
8992   verifyFormat("typedef class Foo\n"
8993                "{\n"
8994                "  Foo();\n"
8995                "} Foo_t;",
8996                Style);
8997   verifyFormat("struct Foo\n"
8998                "{\n"
8999                "  Foo();\n"
9000                "};",
9001                Style);
9002   verifyFormat("typedef struct Foo\n"
9003                "{\n"
9004                "  Foo();\n"
9005                "} Foo_t;",
9006                Style);
9007   verifyFormat("union Foo\n"
9008                "{\n"
9009                "  A,\n"
9010                "};",
9011                Style);
9012   verifyFormat("typedef union Foo\n"
9013                "{\n"
9014                "  A,\n"
9015                "} Foo_t;",
9016                Style);
9017   verifyFormat("namespace Foo\n"
9018                "{\n"
9019                "void Bar();\n"
9020                "};",
9021                Style);
9022 }
9023 
TEST_F(FormatTest,UnderstandContextOfRecordTypeKeywords)9024 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
9025   // Elaborate type variable declarations.
9026   verifyFormat("struct foo a = {bar};\nint n;");
9027   verifyFormat("class foo a = {bar};\nint n;");
9028   verifyFormat("union foo a = {bar};\nint n;");
9029 
9030   // Elaborate types inside function definitions.
9031   verifyFormat("struct foo f() {}\nint n;");
9032   verifyFormat("class foo f() {}\nint n;");
9033   verifyFormat("union foo f() {}\nint n;");
9034 
9035   // Templates.
9036   verifyFormat("template <class X> void f() {}\nint n;");
9037   verifyFormat("template <struct X> void f() {}\nint n;");
9038   verifyFormat("template <union X> void f() {}\nint n;");
9039 
9040   // Actual definitions...
9041   verifyFormat("struct {\n} n;");
9042   verifyFormat(
9043       "template <template <class T, class Y>, class Z> class X {\n} n;");
9044   verifyFormat("union Z {\n  int n;\n} x;");
9045   verifyFormat("class MACRO Z {\n} n;");
9046   verifyFormat("class MACRO(X) Z {\n} n;");
9047   verifyFormat("class __attribute__(X) Z {\n} n;");
9048   verifyFormat("class __declspec(X) Z {\n} n;");
9049   verifyFormat("class A##B##C {\n} n;");
9050   verifyFormat("class alignas(16) Z {\n} n;");
9051   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
9052   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
9053 
9054   // Redefinition from nested context:
9055   verifyFormat("class A::B::C {\n} n;");
9056 
9057   // Template definitions.
9058   verifyFormat(
9059       "template <typename F>\n"
9060       "Matcher(const Matcher<F> &Other,\n"
9061       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
9062       "                             !is_same<F, T>::value>::type * = 0)\n"
9063       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
9064 
9065   // FIXME: This is still incorrectly handled at the formatter side.
9066   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
9067   verifyFormat("int i = SomeFunction(a<b, a> b);");
9068 
9069   // FIXME:
9070   // This now gets parsed incorrectly as class definition.
9071   // verifyFormat("class A<int> f() {\n}\nint n;");
9072 
9073   // Elaborate types where incorrectly parsing the structural element would
9074   // break the indent.
9075   verifyFormat("if (true)\n"
9076                "  class X x;\n"
9077                "else\n"
9078                "  f();\n");
9079 
9080   // This is simply incomplete. Formatting is not important, but must not crash.
9081   verifyFormat("class A:");
9082 }
9083 
TEST_F(FormatTest,DoNotInterfereWithErrorAndWarning)9084 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
9085   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
9086             format("#error Leave     all         white!!!!! space* alone!\n"));
9087   EXPECT_EQ(
9088       "#warning Leave     all         white!!!!! space* alone!\n",
9089       format("#warning Leave     all         white!!!!! space* alone!\n"));
9090   EXPECT_EQ("#error 1", format("  #  error   1"));
9091   EXPECT_EQ("#warning 1", format("  #  warning 1"));
9092 }
9093 
TEST_F(FormatTest,FormatHashIfExpressions)9094 TEST_F(FormatTest, FormatHashIfExpressions) {
9095   verifyFormat("#if AAAA && BBBB");
9096   verifyFormat("#if (AAAA && BBBB)");
9097   verifyFormat("#elif (AAAA && BBBB)");
9098   // FIXME: Come up with a better indentation for #elif.
9099   verifyFormat(
9100       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
9101       "    defined(BBBBBBBB)\n"
9102       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
9103       "    defined(BBBBBBBB)\n"
9104       "#endif",
9105       getLLVMStyleWithColumns(65));
9106 }
9107 
TEST_F(FormatTest,MergeHandlingInTheFaceOfPreprocessorDirectives)9108 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
9109   FormatStyle AllowsMergedIf = getGoogleStyle();
9110   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
9111       FormatStyle::SIS_WithoutElse;
9112   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
9113   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
9114   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
9115   EXPECT_EQ("if (true) return 42;",
9116             format("if (true)\nreturn 42;", AllowsMergedIf));
9117   FormatStyle ShortMergedIf = AllowsMergedIf;
9118   ShortMergedIf.ColumnLimit = 25;
9119   verifyFormat("#define A \\\n"
9120                "  if (true) return 42;",
9121                ShortMergedIf);
9122   verifyFormat("#define A \\\n"
9123                "  f();    \\\n"
9124                "  if (true)\n"
9125                "#define B",
9126                ShortMergedIf);
9127   verifyFormat("#define A \\\n"
9128                "  f();    \\\n"
9129                "  if (true)\n"
9130                "g();",
9131                ShortMergedIf);
9132   verifyFormat("{\n"
9133                "#ifdef A\n"
9134                "  // Comment\n"
9135                "  if (true) continue;\n"
9136                "#endif\n"
9137                "  // Comment\n"
9138                "  if (true) continue;\n"
9139                "}",
9140                ShortMergedIf);
9141   ShortMergedIf.ColumnLimit = 33;
9142   verifyFormat("#define A \\\n"
9143                "  if constexpr (true) return 42;",
9144                ShortMergedIf);
9145   verifyFormat("#define A \\\n"
9146                "  if CONSTEXPR (true) return 42;",
9147                ShortMergedIf);
9148   ShortMergedIf.ColumnLimit = 29;
9149   verifyFormat("#define A                   \\\n"
9150                "  if (aaaaaaaaaa) return 1; \\\n"
9151                "  return 2;",
9152                ShortMergedIf);
9153   ShortMergedIf.ColumnLimit = 28;
9154   verifyFormat("#define A         \\\n"
9155                "  if (aaaaaaaaaa) \\\n"
9156                "    return 1;     \\\n"
9157                "  return 2;",
9158                ShortMergedIf);
9159   verifyFormat("#define A                \\\n"
9160                "  if constexpr (aaaaaaa) \\\n"
9161                "    return 1;            \\\n"
9162                "  return 2;",
9163                ShortMergedIf);
9164   verifyFormat("#define A                \\\n"
9165                "  if CONSTEXPR (aaaaaaa) \\\n"
9166                "    return 1;            \\\n"
9167                "  return 2;",
9168                ShortMergedIf);
9169 }
9170 
TEST_F(FormatTest,FormatStarDependingOnContext)9171 TEST_F(FormatTest, FormatStarDependingOnContext) {
9172   verifyFormat("void f(int *a);");
9173   verifyFormat("void f() { f(fint * b); }");
9174   verifyFormat("class A {\n  void f(int *a);\n};");
9175   verifyFormat("class A {\n  int *a;\n};");
9176   verifyFormat("namespace a {\n"
9177                "namespace b {\n"
9178                "class A {\n"
9179                "  void f() {}\n"
9180                "  int *a;\n"
9181                "};\n"
9182                "} // namespace b\n"
9183                "} // namespace a");
9184 }
9185 
TEST_F(FormatTest,SpecialTokensAtEndOfLine)9186 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
9187   verifyFormat("while");
9188   verifyFormat("operator");
9189 }
9190 
TEST_F(FormatTest,SkipsDeeplyNestedLines)9191 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
9192   // This code would be painfully slow to format if we didn't skip it.
9193   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
9194                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
9195                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
9196                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
9197                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
9198                    "A(1, 1)\n"
9199                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
9200                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9201                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9202                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9203                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9204                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9205                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9206                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9207                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9208                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
9209   // Deeply nested part is untouched, rest is formatted.
9210   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
9211             format(std::string("int    i;\n") + Code + "int    j;\n",
9212                    getLLVMStyle(), SC_ExpectIncomplete));
9213 }
9214 
9215 //===----------------------------------------------------------------------===//
9216 // Objective-C tests.
9217 //===----------------------------------------------------------------------===//
9218 
TEST_F(FormatTest,FormatForObjectiveCMethodDecls)9219 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
9220   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
9221   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
9222             format("-(NSUInteger)indexOfObject:(id)anObject;"));
9223   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
9224   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
9225   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
9226             format("-(NSInteger)Method3:(id)anObject;"));
9227   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
9228             format("-(NSInteger)Method4:(id)anObject;"));
9229   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
9230             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
9231   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
9232             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
9233   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
9234             "forAllCells:(BOOL)flag;",
9235             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
9236                    "forAllCells:(BOOL)flag;"));
9237 
9238   // Very long objectiveC method declaration.
9239   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
9240                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
9241   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
9242                "                    inRange:(NSRange)range\n"
9243                "                   outRange:(NSRange)out_range\n"
9244                "                  outRange1:(NSRange)out_range1\n"
9245                "                  outRange2:(NSRange)out_range2\n"
9246                "                  outRange3:(NSRange)out_range3\n"
9247                "                  outRange4:(NSRange)out_range4\n"
9248                "                  outRange5:(NSRange)out_range5\n"
9249                "                  outRange6:(NSRange)out_range6\n"
9250                "                  outRange7:(NSRange)out_range7\n"
9251                "                  outRange8:(NSRange)out_range8\n"
9252                "                  outRange9:(NSRange)out_range9;");
9253 
9254   // When the function name has to be wrapped.
9255   FormatStyle Style = getLLVMStyle();
9256   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
9257   // and always indents instead.
9258   Style.IndentWrappedFunctionNames = false;
9259   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
9260                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
9261                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
9262                "}",
9263                Style);
9264   Style.IndentWrappedFunctionNames = true;
9265   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
9266                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
9267                "               anotherName:(NSString)dddddddddddddd {\n"
9268                "}",
9269                Style);
9270 
9271   verifyFormat("- (int)sum:(vector<int>)numbers;");
9272   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
9273   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
9274   // protocol lists (but not for template classes):
9275   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
9276 
9277   verifyFormat("- (int (*)())foo:(int (*)())f;");
9278   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
9279 
9280   // If there's no return type (very rare in practice!), LLVM and Google style
9281   // agree.
9282   verifyFormat("- foo;");
9283   verifyFormat("- foo:(int)f;");
9284   verifyGoogleFormat("- foo:(int)foo;");
9285 }
9286 
TEST_F(FormatTest,BreaksStringLiterals)9287 TEST_F(FormatTest, BreaksStringLiterals) {
9288   EXPECT_EQ("\"some text \"\n"
9289             "\"other\";",
9290             format("\"some text other\";", getLLVMStyleWithColumns(12)));
9291   EXPECT_EQ("\"some text \"\n"
9292             "\"other\";",
9293             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
9294   EXPECT_EQ(
9295       "#define A  \\\n"
9296       "  \"some \"  \\\n"
9297       "  \"text \"  \\\n"
9298       "  \"other\";",
9299       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
9300   EXPECT_EQ(
9301       "#define A  \\\n"
9302       "  \"so \"    \\\n"
9303       "  \"text \"  \\\n"
9304       "  \"other\";",
9305       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
9306 
9307   EXPECT_EQ("\"some text\"",
9308             format("\"some text\"", getLLVMStyleWithColumns(1)));
9309   EXPECT_EQ("\"some text\"",
9310             format("\"some text\"", getLLVMStyleWithColumns(11)));
9311   EXPECT_EQ("\"some \"\n"
9312             "\"text\"",
9313             format("\"some text\"", getLLVMStyleWithColumns(10)));
9314   EXPECT_EQ("\"some \"\n"
9315             "\"text\"",
9316             format("\"some text\"", getLLVMStyleWithColumns(7)));
9317   EXPECT_EQ("\"some\"\n"
9318             "\" tex\"\n"
9319             "\"t\"",
9320             format("\"some text\"", getLLVMStyleWithColumns(6)));
9321   EXPECT_EQ("\"some\"\n"
9322             "\" tex\"\n"
9323             "\" and\"",
9324             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
9325   EXPECT_EQ("\"some\"\n"
9326             "\"/tex\"\n"
9327             "\"/and\"",
9328             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
9329 
9330   EXPECT_EQ("variable =\n"
9331             "    \"long string \"\n"
9332             "    \"literal\";",
9333             format("variable = \"long string literal\";",
9334                    getLLVMStyleWithColumns(20)));
9335 
9336   EXPECT_EQ("variable = f(\n"
9337             "    \"long string \"\n"
9338             "    \"literal\",\n"
9339             "    short,\n"
9340             "    loooooooooooooooooooong);",
9341             format("variable = f(\"long string literal\", short, "
9342                    "loooooooooooooooooooong);",
9343                    getLLVMStyleWithColumns(20)));
9344 
9345   EXPECT_EQ(
9346       "f(g(\"long string \"\n"
9347       "    \"literal\"),\n"
9348       "  b);",
9349       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
9350   EXPECT_EQ("f(g(\"long string \"\n"
9351             "    \"literal\",\n"
9352             "    a),\n"
9353             "  b);",
9354             format("f(g(\"long string literal\", a), b);",
9355                    getLLVMStyleWithColumns(20)));
9356   EXPECT_EQ(
9357       "f(\"one two\".split(\n"
9358       "    variable));",
9359       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
9360   EXPECT_EQ("f(\"one two three four five six \"\n"
9361             "  \"seven\".split(\n"
9362             "      really_looooong_variable));",
9363             format("f(\"one two three four five six seven\"."
9364                    "split(really_looooong_variable));",
9365                    getLLVMStyleWithColumns(33)));
9366 
9367   EXPECT_EQ("f(\"some \"\n"
9368             "  \"text\",\n"
9369             "  other);",
9370             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
9371 
9372   // Only break as a last resort.
9373   verifyFormat(
9374       "aaaaaaaaaaaaaaaaaaaa(\n"
9375       "    aaaaaaaaaaaaaaaaaaaa,\n"
9376       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
9377 
9378   EXPECT_EQ("\"splitmea\"\n"
9379             "\"trandomp\"\n"
9380             "\"oint\"",
9381             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
9382 
9383   EXPECT_EQ("\"split/\"\n"
9384             "\"pathat/\"\n"
9385             "\"slashes\"",
9386             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
9387 
9388   EXPECT_EQ("\"split/\"\n"
9389             "\"pathat/\"\n"
9390             "\"slashes\"",
9391             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
9392   EXPECT_EQ("\"split at \"\n"
9393             "\"spaces/at/\"\n"
9394             "\"slashes.at.any$\"\n"
9395             "\"non-alphanumeric%\"\n"
9396             "\"1111111111characte\"\n"
9397             "\"rs\"",
9398             format("\"split at "
9399                    "spaces/at/"
9400                    "slashes.at."
9401                    "any$non-"
9402                    "alphanumeric%"
9403                    "1111111111characte"
9404                    "rs\"",
9405                    getLLVMStyleWithColumns(20)));
9406 
9407   // Verify that splitting the strings understands
9408   // Style::AlwaysBreakBeforeMultilineStrings.
9409   EXPECT_EQ("aaaaaaaaaaaa(\n"
9410             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
9411             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
9412             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
9413                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
9414                    "aaaaaaaaaaaaaaaaaaaaaa\");",
9415                    getGoogleStyle()));
9416   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
9417             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
9418             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
9419                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
9420                    "aaaaaaaaaaaaaaaaaaaaaa\";",
9421                    getGoogleStyle()));
9422   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
9423             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
9424             format("llvm::outs() << "
9425                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
9426                    "aaaaaaaaaaaaaaaaaaa\";"));
9427   EXPECT_EQ("ffff(\n"
9428             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
9429             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
9430             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
9431                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
9432                    getGoogleStyle()));
9433 
9434   FormatStyle Style = getLLVMStyleWithColumns(12);
9435   Style.BreakStringLiterals = false;
9436   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
9437 
9438   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
9439   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
9440   EXPECT_EQ("#define A \\\n"
9441             "  \"some \" \\\n"
9442             "  \"text \" \\\n"
9443             "  \"other\";",
9444             format("#define A \"some text other\";", AlignLeft));
9445 }
9446 
TEST_F(FormatTest,BreaksStringLiteralsAtColumnLimit)9447 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
9448   EXPECT_EQ("C a = \"some more \"\n"
9449             "      \"text\";",
9450             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
9451 }
9452 
TEST_F(FormatTest,FullyRemoveEmptyLines)9453 TEST_F(FormatTest, FullyRemoveEmptyLines) {
9454   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
9455   NoEmptyLines.MaxEmptyLinesToKeep = 0;
9456   EXPECT_EQ("int i = a(b());",
9457             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
9458 }
9459 
TEST_F(FormatTest,BreaksStringLiteralsWithTabs)9460 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
9461   EXPECT_EQ(
9462       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
9463       "(\n"
9464       "    \"x\t\");",
9465       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
9466              "aaaaaaa("
9467              "\"x\t\");"));
9468 }
9469 
TEST_F(FormatTest,BreaksWideAndNSStringLiterals)9470 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
9471   EXPECT_EQ(
9472       "u8\"utf8 string \"\n"
9473       "u8\"literal\";",
9474       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
9475   EXPECT_EQ(
9476       "u\"utf16 string \"\n"
9477       "u\"literal\";",
9478       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
9479   EXPECT_EQ(
9480       "U\"utf32 string \"\n"
9481       "U\"literal\";",
9482       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
9483   EXPECT_EQ("L\"wide string \"\n"
9484             "L\"literal\";",
9485             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
9486   EXPECT_EQ("@\"NSString \"\n"
9487             "@\"literal\";",
9488             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
9489   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
9490 
9491   // This input makes clang-format try to split the incomplete unicode escape
9492   // sequence, which used to lead to a crasher.
9493   verifyNoCrash(
9494       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
9495       getLLVMStyleWithColumns(60));
9496 }
9497 
TEST_F(FormatTest,DoesNotBreakRawStringLiterals)9498 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
9499   FormatStyle Style = getGoogleStyleWithColumns(15);
9500   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
9501   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
9502   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
9503   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
9504   EXPECT_EQ("u8R\"x(raw literal)x\";",
9505             format("u8R\"x(raw literal)x\";", Style));
9506 }
9507 
TEST_F(FormatTest,BreaksStringLiteralsWithin_TMacro)9508 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
9509   FormatStyle Style = getLLVMStyleWithColumns(20);
9510   EXPECT_EQ(
9511       "_T(\"aaaaaaaaaaaaaa\")\n"
9512       "_T(\"aaaaaaaaaaaaaa\")\n"
9513       "_T(\"aaaaaaaaaaaa\")",
9514       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
9515   EXPECT_EQ("f(x,\n"
9516             "  _T(\"aaaaaaaaaaaa\")\n"
9517             "  _T(\"aaa\"),\n"
9518             "  z);",
9519             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
9520 
9521   // FIXME: Handle embedded spaces in one iteration.
9522   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
9523   //            "_T(\"aaaaaaaaaaaaa\")\n"
9524   //            "_T(\"aaaaaaaaaaaaa\")\n"
9525   //            "_T(\"a\")",
9526   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
9527   //                   getLLVMStyleWithColumns(20)));
9528   EXPECT_EQ(
9529       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
9530       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
9531   EXPECT_EQ("f(\n"
9532             "#if !TEST\n"
9533             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
9534             "#endif\n"
9535             ");",
9536             format("f(\n"
9537                    "#if !TEST\n"
9538                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
9539                    "#endif\n"
9540                    ");"));
9541   EXPECT_EQ("f(\n"
9542             "\n"
9543             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
9544             format("f(\n"
9545                    "\n"
9546                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
9547 }
9548 
TEST_F(FormatTest,BreaksStringLiteralOperands)9549 TEST_F(FormatTest, BreaksStringLiteralOperands) {
9550   // In a function call with two operands, the second can be broken with no line
9551   // break before it.
9552   EXPECT_EQ(
9553       "func(a, \"long long \"\n"
9554       "        \"long long\");",
9555       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
9556   // In a function call with three operands, the second must be broken with a
9557   // line break before it.
9558   EXPECT_EQ("func(a,\n"
9559             "     \"long long long \"\n"
9560             "     \"long\",\n"
9561             "     c);",
9562             format("func(a, \"long long long long\", c);",
9563                    getLLVMStyleWithColumns(24)));
9564   // In a function call with three operands, the third must be broken with a
9565   // line break before it.
9566   EXPECT_EQ("func(a, b,\n"
9567             "     \"long long long \"\n"
9568             "     \"long\");",
9569             format("func(a, b, \"long long long long\");",
9570                    getLLVMStyleWithColumns(24)));
9571   // In a function call with three operands, both the second and the third must
9572   // be broken with a line break before them.
9573   EXPECT_EQ("func(a,\n"
9574             "     \"long long long \"\n"
9575             "     \"long\",\n"
9576             "     \"long long long \"\n"
9577             "     \"long\");",
9578             format("func(a, \"long long long long\", \"long long long long\");",
9579                    getLLVMStyleWithColumns(24)));
9580   // In a chain of << with two operands, the second can be broken with no line
9581   // break before it.
9582   EXPECT_EQ("a << \"line line \"\n"
9583             "     \"line\";",
9584             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
9585   // In a chain of << with three operands, the second can be broken with no line
9586   // break before it.
9587   EXPECT_EQ(
9588       "abcde << \"line \"\n"
9589       "         \"line line\"\n"
9590       "      << c;",
9591       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
9592   // In a chain of << with three operands, the third must be broken with a line
9593   // break before it.
9594   EXPECT_EQ(
9595       "a << b\n"
9596       "  << \"line line \"\n"
9597       "     \"line\";",
9598       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
9599   // In a chain of << with three operands, the second can be broken with no line
9600   // break before it and the third must be broken with a line break before it.
9601   EXPECT_EQ("abcd << \"line line \"\n"
9602             "        \"line\"\n"
9603             "     << \"line line \"\n"
9604             "        \"line\";",
9605             format("abcd << \"line line line\" << \"line line line\";",
9606                    getLLVMStyleWithColumns(20)));
9607   // In a chain of binary operators with two operands, the second can be broken
9608   // with no line break before it.
9609   EXPECT_EQ(
9610       "abcd + \"line line \"\n"
9611       "       \"line line\";",
9612       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
9613   // In a chain of binary operators with three operands, the second must be
9614   // broken with a line break before it.
9615   EXPECT_EQ("abcd +\n"
9616             "    \"line line \"\n"
9617             "    \"line line\" +\n"
9618             "    e;",
9619             format("abcd + \"line line line line\" + e;",
9620                    getLLVMStyleWithColumns(20)));
9621   // In a function call with two operands, with AlignAfterOpenBracket enabled,
9622   // the first must be broken with a line break before it.
9623   FormatStyle Style = getLLVMStyleWithColumns(25);
9624   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9625   EXPECT_EQ("someFunction(\n"
9626             "    \"long long long \"\n"
9627             "    \"long\",\n"
9628             "    a);",
9629             format("someFunction(\"long long long long\", a);", Style));
9630 }
9631 
TEST_F(FormatTest,DontSplitStringLiteralsWithEscapedNewlines)9632 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
9633   EXPECT_EQ(
9634       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
9635       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
9636       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
9637       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
9638              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
9639              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
9640 }
9641 
TEST_F(FormatTest,CountsCharactersInMultilineRawStringLiterals)9642 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
9643   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
9644             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
9645   EXPECT_EQ("fffffffffff(g(R\"x(\n"
9646             "multiline raw string literal xxxxxxxxxxxxxx\n"
9647             ")x\",\n"
9648             "              a),\n"
9649             "            b);",
9650             format("fffffffffff(g(R\"x(\n"
9651                    "multiline raw string literal xxxxxxxxxxxxxx\n"
9652                    ")x\", a), b);",
9653                    getGoogleStyleWithColumns(20)));
9654   EXPECT_EQ("fffffffffff(\n"
9655             "    g(R\"x(qqq\n"
9656             "multiline raw string literal xxxxxxxxxxxxxx\n"
9657             ")x\",\n"
9658             "      a),\n"
9659             "    b);",
9660             format("fffffffffff(g(R\"x(qqq\n"
9661                    "multiline raw string literal xxxxxxxxxxxxxx\n"
9662                    ")x\", a), b);",
9663                    getGoogleStyleWithColumns(20)));
9664 
9665   EXPECT_EQ("fffffffffff(R\"x(\n"
9666             "multiline raw string literal xxxxxxxxxxxxxx\n"
9667             ")x\");",
9668             format("fffffffffff(R\"x(\n"
9669                    "multiline raw string literal xxxxxxxxxxxxxx\n"
9670                    ")x\");",
9671                    getGoogleStyleWithColumns(20)));
9672   EXPECT_EQ("fffffffffff(R\"x(\n"
9673             "multiline raw string literal xxxxxxxxxxxxxx\n"
9674             ")x\" + bbbbbb);",
9675             format("fffffffffff(R\"x(\n"
9676                    "multiline raw string literal xxxxxxxxxxxxxx\n"
9677                    ")x\" +   bbbbbb);",
9678                    getGoogleStyleWithColumns(20)));
9679   EXPECT_EQ("fffffffffff(\n"
9680             "    R\"x(\n"
9681             "multiline raw string literal xxxxxxxxxxxxxx\n"
9682             ")x\" +\n"
9683             "    bbbbbb);",
9684             format("fffffffffff(\n"
9685                    " R\"x(\n"
9686                    "multiline raw string literal xxxxxxxxxxxxxx\n"
9687                    ")x\" + bbbbbb);",
9688                    getGoogleStyleWithColumns(20)));
9689   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
9690             format("fffffffffff(\n"
9691                    " R\"(single line raw string)\" + bbbbbb);"));
9692 }
9693 
TEST_F(FormatTest,SkipsUnknownStringLiterals)9694 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
9695   verifyFormat("string a = \"unterminated;");
9696   EXPECT_EQ("function(\"unterminated,\n"
9697             "         OtherParameter);",
9698             format("function(  \"unterminated,\n"
9699                    "    OtherParameter);"));
9700 }
9701 
TEST_F(FormatTest,DoesNotTryToParseUDLiteralsInPreCpp11Code)9702 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
9703   FormatStyle Style = getLLVMStyle();
9704   Style.Standard = FormatStyle::LS_Cpp03;
9705   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
9706             format("#define x(_a) printf(\"foo\"_a);", Style));
9707 }
9708 
TEST_F(FormatTest,CppLexVersion)9709 TEST_F(FormatTest, CppLexVersion) {
9710   FormatStyle Style = getLLVMStyle();
9711   // Formatting of x * y differs if x is a type.
9712   verifyFormat("void foo() { MACRO(a * b); }", Style);
9713   verifyFormat("void foo() { MACRO(int *b); }", Style);
9714 
9715   // LLVM style uses latest lexer.
9716   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
9717   Style.Standard = FormatStyle::LS_Cpp17;
9718   // But in c++17, char8_t isn't a keyword.
9719   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
9720 }
9721 
TEST_F(FormatTest,UnderstandsCpp1y)9722 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
9723 
TEST_F(FormatTest,BreakStringLiteralsBeforeUnbreakableTokenSequence)9724 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
9725   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
9726             "             \"ddeeefff\");",
9727             format("someFunction(\"aaabbbcccdddeeefff\");",
9728                    getLLVMStyleWithColumns(25)));
9729   EXPECT_EQ("someFunction1234567890(\n"
9730             "    \"aaabbbcccdddeeefff\");",
9731             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
9732                    getLLVMStyleWithColumns(26)));
9733   EXPECT_EQ("someFunction1234567890(\n"
9734             "    \"aaabbbcccdddeeeff\"\n"
9735             "    \"f\");",
9736             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
9737                    getLLVMStyleWithColumns(25)));
9738   EXPECT_EQ("someFunction1234567890(\n"
9739             "    \"aaabbbcccdddeeeff\"\n"
9740             "    \"f\");",
9741             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
9742                    getLLVMStyleWithColumns(24)));
9743   EXPECT_EQ("someFunction(\n"
9744             "    \"aaabbbcc ddde \"\n"
9745             "    \"efff\");",
9746             format("someFunction(\"aaabbbcc ddde efff\");",
9747                    getLLVMStyleWithColumns(25)));
9748   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
9749             "             \"ddeeefff\");",
9750             format("someFunction(\"aaabbbccc ddeeefff\");",
9751                    getLLVMStyleWithColumns(25)));
9752   EXPECT_EQ("someFunction1234567890(\n"
9753             "    \"aaabb \"\n"
9754             "    \"cccdddeeefff\");",
9755             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
9756                    getLLVMStyleWithColumns(25)));
9757   EXPECT_EQ("#define A          \\\n"
9758             "  string s =       \\\n"
9759             "      \"123456789\"  \\\n"
9760             "      \"0\";         \\\n"
9761             "  int i;",
9762             format("#define A string s = \"1234567890\"; int i;",
9763                    getLLVMStyleWithColumns(20)));
9764   EXPECT_EQ("someFunction(\n"
9765             "    \"aaabbbcc \"\n"
9766             "    \"dddeeefff\");",
9767             format("someFunction(\"aaabbbcc dddeeefff\");",
9768                    getLLVMStyleWithColumns(25)));
9769 }
9770 
TEST_F(FormatTest,DoNotBreakStringLiteralsInEscapeSequence)9771 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
9772   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
9773   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
9774   EXPECT_EQ("\"test\"\n"
9775             "\"\\n\"",
9776             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
9777   EXPECT_EQ("\"tes\\\\\"\n"
9778             "\"n\"",
9779             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
9780   EXPECT_EQ("\"\\\\\\\\\"\n"
9781             "\"\\n\"",
9782             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
9783   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
9784   EXPECT_EQ("\"\\uff01\"\n"
9785             "\"test\"",
9786             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
9787   EXPECT_EQ("\"\\Uff01ff02\"",
9788             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
9789   EXPECT_EQ("\"\\x000000000001\"\n"
9790             "\"next\"",
9791             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
9792   EXPECT_EQ("\"\\x000000000001next\"",
9793             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
9794   EXPECT_EQ("\"\\x000000000001\"",
9795             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
9796   EXPECT_EQ("\"test\"\n"
9797             "\"\\000000\"\n"
9798             "\"000001\"",
9799             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
9800   EXPECT_EQ("\"test\\000\"\n"
9801             "\"00000000\"\n"
9802             "\"1\"",
9803             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
9804 }
9805 
TEST_F(FormatTest,DoNotCreateUnreasonableUnwrappedLines)9806 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
9807   verifyFormat("void f() {\n"
9808                "  return g() {}\n"
9809                "  void h() {}");
9810   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
9811                "g();\n"
9812                "}");
9813 }
9814 
TEST_F(FormatTest,DoNotPrematurelyEndUnwrappedLineForReturnStatements)9815 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
9816   verifyFormat(
9817       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
9818 }
9819 
TEST_F(FormatTest,FormatsClosingBracesInEmptyNestedBlocks)9820 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
9821   verifyFormat("class X {\n"
9822                "  void f() {\n"
9823                "  }\n"
9824                "};",
9825                getLLVMStyleWithColumns(12));
9826 }
9827 
TEST_F(FormatTest,ConfigurableIndentWidth)9828 TEST_F(FormatTest, ConfigurableIndentWidth) {
9829   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
9830   EightIndent.IndentWidth = 8;
9831   EightIndent.ContinuationIndentWidth = 8;
9832   verifyFormat("void f() {\n"
9833                "        someFunction();\n"
9834                "        if (true) {\n"
9835                "                f();\n"
9836                "        }\n"
9837                "}",
9838                EightIndent);
9839   verifyFormat("class X {\n"
9840                "        void f() {\n"
9841                "        }\n"
9842                "};",
9843                EightIndent);
9844   verifyFormat("int x[] = {\n"
9845                "        call(),\n"
9846                "        call()};",
9847                EightIndent);
9848 }
9849 
TEST_F(FormatTest,ConfigurableFunctionDeclarationIndentAfterType)9850 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
9851   verifyFormat("double\n"
9852                "f();",
9853                getLLVMStyleWithColumns(8));
9854 }
9855 
TEST_F(FormatTest,ConfigurableUseOfTab)9856 TEST_F(FormatTest, ConfigurableUseOfTab) {
9857   FormatStyle Tab = getLLVMStyleWithColumns(42);
9858   Tab.IndentWidth = 8;
9859   Tab.UseTab = FormatStyle::UT_Always;
9860   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
9861 
9862   EXPECT_EQ("if (aaaaaaaa && // q\n"
9863             "    bb)\t\t// w\n"
9864             "\t;",
9865             format("if (aaaaaaaa &&// q\n"
9866                    "bb)// w\n"
9867                    ";",
9868                    Tab));
9869   EXPECT_EQ("if (aaa && bbb) // w\n"
9870             "\t;",
9871             format("if(aaa&&bbb)// w\n"
9872                    ";",
9873                    Tab));
9874 
9875   verifyFormat("class X {\n"
9876                "\tvoid f() {\n"
9877                "\t\tsomeFunction(parameter1,\n"
9878                "\t\t\t     parameter2);\n"
9879                "\t}\n"
9880                "};",
9881                Tab);
9882   verifyFormat("#define A                        \\\n"
9883                "\tvoid f() {               \\\n"
9884                "\t\tsomeFunction(    \\\n"
9885                "\t\t    parameter1,  \\\n"
9886                "\t\t    parameter2); \\\n"
9887                "\t}",
9888                Tab);
9889   verifyFormat("int a;\t      // x\n"
9890                "int bbbbbbbb; // x\n",
9891                Tab);
9892 
9893   Tab.TabWidth = 4;
9894   Tab.IndentWidth = 8;
9895   verifyFormat("class TabWidth4Indent8 {\n"
9896                "\t\tvoid f() {\n"
9897                "\t\t\t\tsomeFunction(parameter1,\n"
9898                "\t\t\t\t\t\t\t parameter2);\n"
9899                "\t\t}\n"
9900                "};",
9901                Tab);
9902 
9903   Tab.TabWidth = 4;
9904   Tab.IndentWidth = 4;
9905   verifyFormat("class TabWidth4Indent4 {\n"
9906                "\tvoid f() {\n"
9907                "\t\tsomeFunction(parameter1,\n"
9908                "\t\t\t\t\t parameter2);\n"
9909                "\t}\n"
9910                "};",
9911                Tab);
9912 
9913   Tab.TabWidth = 8;
9914   Tab.IndentWidth = 4;
9915   verifyFormat("class TabWidth8Indent4 {\n"
9916                "    void f() {\n"
9917                "\tsomeFunction(parameter1,\n"
9918                "\t\t     parameter2);\n"
9919                "    }\n"
9920                "};",
9921                Tab);
9922 
9923   Tab.TabWidth = 8;
9924   Tab.IndentWidth = 8;
9925   EXPECT_EQ("/*\n"
9926             "\t      a\t\tcomment\n"
9927             "\t      in multiple lines\n"
9928             "       */",
9929             format("   /*\t \t \n"
9930                    " \t \t a\t\tcomment\t \t\n"
9931                    " \t \t in multiple lines\t\n"
9932                    " \t  */",
9933                    Tab));
9934 
9935   Tab.UseTab = FormatStyle::UT_ForIndentation;
9936   verifyFormat("{\n"
9937                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
9938                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
9939                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
9940                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
9941                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
9942                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
9943                "};",
9944                Tab);
9945   verifyFormat("enum AA {\n"
9946                "\ta1, // Force multiple lines\n"
9947                "\ta2,\n"
9948                "\ta3\n"
9949                "};",
9950                Tab);
9951   EXPECT_EQ("if (aaaaaaaa && // q\n"
9952             "    bb)         // w\n"
9953             "\t;",
9954             format("if (aaaaaaaa &&// q\n"
9955                    "bb)// w\n"
9956                    ";",
9957                    Tab));
9958   verifyFormat("class X {\n"
9959                "\tvoid f() {\n"
9960                "\t\tsomeFunction(parameter1,\n"
9961                "\t\t             parameter2);\n"
9962                "\t}\n"
9963                "};",
9964                Tab);
9965   verifyFormat("{\n"
9966                "\tQ(\n"
9967                "\t    {\n"
9968                "\t\t    int a;\n"
9969                "\t\t    someFunction(aaaaaaaa,\n"
9970                "\t\t                 bbbbbbb);\n"
9971                "\t    },\n"
9972                "\t    p);\n"
9973                "}",
9974                Tab);
9975   EXPECT_EQ("{\n"
9976             "\t/* aaaa\n"
9977             "\t   bbbb */\n"
9978             "}",
9979             format("{\n"
9980                    "/* aaaa\n"
9981                    "   bbbb */\n"
9982                    "}",
9983                    Tab));
9984   EXPECT_EQ("{\n"
9985             "\t/*\n"
9986             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9987             "\t  bbbbbbbbbbbbb\n"
9988             "\t*/\n"
9989             "}",
9990             format("{\n"
9991                    "/*\n"
9992                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
9993                    "*/\n"
9994                    "}",
9995                    Tab));
9996   EXPECT_EQ("{\n"
9997             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9998             "\t// bbbbbbbbbbbbb\n"
9999             "}",
10000             format("{\n"
10001                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10002                    "}",
10003                    Tab));
10004   EXPECT_EQ("{\n"
10005             "\t/*\n"
10006             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10007             "\t  bbbbbbbbbbbbb\n"
10008             "\t*/\n"
10009             "}",
10010             format("{\n"
10011                    "\t/*\n"
10012                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10013                    "\t*/\n"
10014                    "}",
10015                    Tab));
10016   EXPECT_EQ("{\n"
10017             "\t/*\n"
10018             "\n"
10019             "\t*/\n"
10020             "}",
10021             format("{\n"
10022                    "\t/*\n"
10023                    "\n"
10024                    "\t*/\n"
10025                    "}",
10026                    Tab));
10027   EXPECT_EQ("{\n"
10028             "\t/*\n"
10029             " asdf\n"
10030             "\t*/\n"
10031             "}",
10032             format("{\n"
10033                    "\t/*\n"
10034                    " asdf\n"
10035                    "\t*/\n"
10036                    "}",
10037                    Tab));
10038 
10039   Tab.UseTab = FormatStyle::UT_Never;
10040   EXPECT_EQ("/*\n"
10041             "              a\t\tcomment\n"
10042             "              in multiple lines\n"
10043             "       */",
10044             format("   /*\t \t \n"
10045                    " \t \t a\t\tcomment\t \t\n"
10046                    " \t \t in multiple lines\t\n"
10047                    " \t  */",
10048                    Tab));
10049   EXPECT_EQ("/* some\n"
10050             "   comment */",
10051             format(" \t \t /* some\n"
10052                    " \t \t    comment */",
10053                    Tab));
10054   EXPECT_EQ("int a; /* some\n"
10055             "   comment */",
10056             format(" \t \t int a; /* some\n"
10057                    " \t \t    comment */",
10058                    Tab));
10059 
10060   EXPECT_EQ("int a; /* some\n"
10061             "comment */",
10062             format(" \t \t int\ta; /* some\n"
10063                    " \t \t    comment */",
10064                    Tab));
10065   EXPECT_EQ("f(\"\t\t\"); /* some\n"
10066             "    comment */",
10067             format(" \t \t f(\"\t\t\"); /* some\n"
10068                    " \t \t    comment */",
10069                    Tab));
10070   EXPECT_EQ("{\n"
10071             "  /*\n"
10072             "   * Comment\n"
10073             "   */\n"
10074             "  int i;\n"
10075             "}",
10076             format("{\n"
10077                    "\t/*\n"
10078                    "\t * Comment\n"
10079                    "\t */\n"
10080                    "\t int i;\n"
10081                    "}"));
10082 
10083   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
10084   Tab.TabWidth = 8;
10085   Tab.IndentWidth = 8;
10086   EXPECT_EQ("if (aaaaaaaa && // q\n"
10087             "    bb)         // w\n"
10088             "\t;",
10089             format("if (aaaaaaaa &&// q\n"
10090                    "bb)// w\n"
10091                    ";",
10092                    Tab));
10093   EXPECT_EQ("if (aaa && bbb) // w\n"
10094             "\t;",
10095             format("if(aaa&&bbb)// w\n"
10096                    ";",
10097                    Tab));
10098   verifyFormat("class X {\n"
10099                "\tvoid f() {\n"
10100                "\t\tsomeFunction(parameter1,\n"
10101                "\t\t\t     parameter2);\n"
10102                "\t}\n"
10103                "};",
10104                Tab);
10105   verifyFormat("#define A                        \\\n"
10106                "\tvoid f() {               \\\n"
10107                "\t\tsomeFunction(    \\\n"
10108                "\t\t    parameter1,  \\\n"
10109                "\t\t    parameter2); \\\n"
10110                "\t}",
10111                Tab);
10112   Tab.TabWidth = 4;
10113   Tab.IndentWidth = 8;
10114   verifyFormat("class TabWidth4Indent8 {\n"
10115                "\t\tvoid f() {\n"
10116                "\t\t\t\tsomeFunction(parameter1,\n"
10117                "\t\t\t\t\t\t\t parameter2);\n"
10118                "\t\t}\n"
10119                "};",
10120                Tab);
10121   Tab.TabWidth = 4;
10122   Tab.IndentWidth = 4;
10123   verifyFormat("class TabWidth4Indent4 {\n"
10124                "\tvoid f() {\n"
10125                "\t\tsomeFunction(parameter1,\n"
10126                "\t\t\t\t\t parameter2);\n"
10127                "\t}\n"
10128                "};",
10129                Tab);
10130   Tab.TabWidth = 8;
10131   Tab.IndentWidth = 4;
10132   verifyFormat("class TabWidth8Indent4 {\n"
10133                "    void f() {\n"
10134                "\tsomeFunction(parameter1,\n"
10135                "\t\t     parameter2);\n"
10136                "    }\n"
10137                "};",
10138                Tab);
10139   Tab.TabWidth = 8;
10140   Tab.IndentWidth = 8;
10141   EXPECT_EQ("/*\n"
10142             "\t      a\t\tcomment\n"
10143             "\t      in multiple lines\n"
10144             "       */",
10145             format("   /*\t \t \n"
10146                    " \t \t a\t\tcomment\t \t\n"
10147                    " \t \t in multiple lines\t\n"
10148                    " \t  */",
10149                    Tab));
10150   verifyFormat("{\n"
10151                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10152                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10153                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10154                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10155                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10156                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10157                "};",
10158                Tab);
10159   verifyFormat("enum AA {\n"
10160                "\ta1, // Force multiple lines\n"
10161                "\ta2,\n"
10162                "\ta3\n"
10163                "};",
10164                Tab);
10165   EXPECT_EQ("if (aaaaaaaa && // q\n"
10166             "    bb)         // w\n"
10167             "\t;",
10168             format("if (aaaaaaaa &&// q\n"
10169                    "bb)// w\n"
10170                    ";",
10171                    Tab));
10172   verifyFormat("class X {\n"
10173                "\tvoid f() {\n"
10174                "\t\tsomeFunction(parameter1,\n"
10175                "\t\t\t     parameter2);\n"
10176                "\t}\n"
10177                "};",
10178                Tab);
10179   verifyFormat("{\n"
10180                "\tQ(\n"
10181                "\t    {\n"
10182                "\t\t    int a;\n"
10183                "\t\t    someFunction(aaaaaaaa,\n"
10184                "\t\t\t\t bbbbbbb);\n"
10185                "\t    },\n"
10186                "\t    p);\n"
10187                "}",
10188                Tab);
10189   EXPECT_EQ("{\n"
10190             "\t/* aaaa\n"
10191             "\t   bbbb */\n"
10192             "}",
10193             format("{\n"
10194                    "/* aaaa\n"
10195                    "   bbbb */\n"
10196                    "}",
10197                    Tab));
10198   EXPECT_EQ("{\n"
10199             "\t/*\n"
10200             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10201             "\t  bbbbbbbbbbbbb\n"
10202             "\t*/\n"
10203             "}",
10204             format("{\n"
10205                    "/*\n"
10206                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10207                    "*/\n"
10208                    "}",
10209                    Tab));
10210   EXPECT_EQ("{\n"
10211             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10212             "\t// bbbbbbbbbbbbb\n"
10213             "}",
10214             format("{\n"
10215                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10216                    "}",
10217                    Tab));
10218   EXPECT_EQ("{\n"
10219             "\t/*\n"
10220             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10221             "\t  bbbbbbbbbbbbb\n"
10222             "\t*/\n"
10223             "}",
10224             format("{\n"
10225                    "\t/*\n"
10226                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10227                    "\t*/\n"
10228                    "}",
10229                    Tab));
10230   EXPECT_EQ("{\n"
10231             "\t/*\n"
10232             "\n"
10233             "\t*/\n"
10234             "}",
10235             format("{\n"
10236                    "\t/*\n"
10237                    "\n"
10238                    "\t*/\n"
10239                    "}",
10240                    Tab));
10241   EXPECT_EQ("{\n"
10242             "\t/*\n"
10243             " asdf\n"
10244             "\t*/\n"
10245             "}",
10246             format("{\n"
10247                    "\t/*\n"
10248                    " asdf\n"
10249                    "\t*/\n"
10250                    "}",
10251                    Tab));
10252   EXPECT_EQ("/*\n"
10253             "\t      a\t\tcomment\n"
10254             "\t      in multiple lines\n"
10255             "       */",
10256             format("   /*\t \t \n"
10257                    " \t \t a\t\tcomment\t \t\n"
10258                    " \t \t in multiple lines\t\n"
10259                    " \t  */",
10260                    Tab));
10261   EXPECT_EQ("/* some\n"
10262             "   comment */",
10263             format(" \t \t /* some\n"
10264                    " \t \t    comment */",
10265                    Tab));
10266   EXPECT_EQ("int a; /* some\n"
10267             "   comment */",
10268             format(" \t \t int a; /* some\n"
10269                    " \t \t    comment */",
10270                    Tab));
10271   EXPECT_EQ("int a; /* some\n"
10272             "comment */",
10273             format(" \t \t int\ta; /* some\n"
10274                    " \t \t    comment */",
10275                    Tab));
10276   EXPECT_EQ("f(\"\t\t\"); /* some\n"
10277             "    comment */",
10278             format(" \t \t f(\"\t\t\"); /* some\n"
10279                    " \t \t    comment */",
10280                    Tab));
10281   EXPECT_EQ("{\n"
10282             "  /*\n"
10283             "   * Comment\n"
10284             "   */\n"
10285             "  int i;\n"
10286             "}",
10287             format("{\n"
10288                    "\t/*\n"
10289                    "\t * Comment\n"
10290                    "\t */\n"
10291                    "\t int i;\n"
10292                    "}"));
10293   Tab.AlignConsecutiveAssignments = true;
10294   Tab.AlignConsecutiveDeclarations = true;
10295   Tab.TabWidth = 4;
10296   Tab.IndentWidth = 4;
10297   verifyFormat("class Assign {\n"
10298                "\tvoid f() {\n"
10299                "\t\tint         x      = 123;\n"
10300                "\t\tint         random = 4;\n"
10301                "\t\tstd::string alphabet =\n"
10302                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
10303                "\t}\n"
10304                "};",
10305                Tab);
10306 }
10307 
TEST_F(FormatTest,ZeroTabWidth)10308 TEST_F(FormatTest, ZeroTabWidth) {
10309   FormatStyle Tab = getLLVMStyleWithColumns(42);
10310   Tab.IndentWidth = 8;
10311   Tab.UseTab = FormatStyle::UT_Never;
10312   Tab.TabWidth = 0;
10313   EXPECT_EQ("void a(){\n"
10314             "    // line starts with '\t'\n"
10315             "};",
10316             format("void a(){\n"
10317                    "\t// line starts with '\t'\n"
10318                    "};",
10319                    Tab));
10320 
10321   EXPECT_EQ("void a(){\n"
10322             "    // line starts with '\t'\n"
10323             "};",
10324             format("void a(){\n"
10325                    "\t\t// line starts with '\t'\n"
10326                    "};",
10327                    Tab));
10328 
10329   Tab.UseTab = FormatStyle::UT_ForIndentation;
10330   EXPECT_EQ("void a(){\n"
10331             "    // line starts with '\t'\n"
10332             "};",
10333             format("void a(){\n"
10334                    "\t// line starts with '\t'\n"
10335                    "};",
10336                    Tab));
10337 
10338   EXPECT_EQ("void a(){\n"
10339             "    // line starts with '\t'\n"
10340             "};",
10341             format("void a(){\n"
10342                    "\t\t// line starts with '\t'\n"
10343                    "};",
10344                    Tab));
10345 
10346   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
10347   EXPECT_EQ("void a(){\n"
10348             "    // line starts with '\t'\n"
10349             "};",
10350             format("void a(){\n"
10351                    "\t// line starts with '\t'\n"
10352                    "};",
10353                    Tab));
10354 
10355   EXPECT_EQ("void a(){\n"
10356             "    // line starts with '\t'\n"
10357             "};",
10358             format("void a(){\n"
10359                    "\t\t// line starts with '\t'\n"
10360                    "};",
10361                    Tab));
10362 
10363   Tab.UseTab = FormatStyle::UT_Always;
10364   EXPECT_EQ("void a(){\n"
10365             "// line starts with '\t'\n"
10366             "};",
10367             format("void a(){\n"
10368                    "\t// line starts with '\t'\n"
10369                    "};",
10370                    Tab));
10371 
10372   EXPECT_EQ("void a(){\n"
10373             "// line starts with '\t'\n"
10374             "};",
10375             format("void a(){\n"
10376                    "\t\t// line starts with '\t'\n"
10377                    "};",
10378                    Tab));
10379 }
10380 
TEST_F(FormatTest,CalculatesOriginalColumn)10381 TEST_F(FormatTest, CalculatesOriginalColumn) {
10382   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10383             "q\"; /* some\n"
10384             "       comment */",
10385             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10386                    "q\"; /* some\n"
10387                    "       comment */",
10388                    getLLVMStyle()));
10389   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
10390             "/* some\n"
10391             "   comment */",
10392             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
10393                    " /* some\n"
10394                    "    comment */",
10395                    getLLVMStyle()));
10396   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10397             "qqq\n"
10398             "/* some\n"
10399             "   comment */",
10400             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10401                    "qqq\n"
10402                    " /* some\n"
10403                    "    comment */",
10404                    getLLVMStyle()));
10405   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10406             "wwww; /* some\n"
10407             "         comment */",
10408             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10409                    "wwww; /* some\n"
10410                    "         comment */",
10411                    getLLVMStyle()));
10412 }
10413 
TEST_F(FormatTest,ConfigurableSpaceBeforeParens)10414 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
10415   FormatStyle NoSpace = getLLVMStyle();
10416   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
10417 
10418   verifyFormat("while(true)\n"
10419                "  continue;",
10420                NoSpace);
10421   verifyFormat("for(;;)\n"
10422                "  continue;",
10423                NoSpace);
10424   verifyFormat("if(true)\n"
10425                "  f();\n"
10426                "else if(true)\n"
10427                "  f();",
10428                NoSpace);
10429   verifyFormat("do {\n"
10430                "  do_something();\n"
10431                "} while(something());",
10432                NoSpace);
10433   verifyFormat("switch(x) {\n"
10434                "default:\n"
10435                "  break;\n"
10436                "}",
10437                NoSpace);
10438   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
10439   verifyFormat("size_t x = sizeof(x);", NoSpace);
10440   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
10441   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
10442   verifyFormat("alignas(128) char a[128];", NoSpace);
10443   verifyFormat("size_t x = alignof(MyType);", NoSpace);
10444   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
10445   verifyFormat("int f() throw(Deprecated);", NoSpace);
10446   verifyFormat("typedef void (*cb)(int);", NoSpace);
10447   verifyFormat("T A::operator()();", NoSpace);
10448   verifyFormat("X A::operator++(T);", NoSpace);
10449   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
10450 
10451   FormatStyle Space = getLLVMStyle();
10452   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
10453 
10454   verifyFormat("int f ();", Space);
10455   verifyFormat("void f (int a, T b) {\n"
10456                "  while (true)\n"
10457                "    continue;\n"
10458                "}",
10459                Space);
10460   verifyFormat("if (true)\n"
10461                "  f ();\n"
10462                "else if (true)\n"
10463                "  f ();",
10464                Space);
10465   verifyFormat("do {\n"
10466                "  do_something ();\n"
10467                "} while (something ());",
10468                Space);
10469   verifyFormat("switch (x) {\n"
10470                "default:\n"
10471                "  break;\n"
10472                "}",
10473                Space);
10474   verifyFormat("A::A () : a (1) {}", Space);
10475   verifyFormat("void f () __attribute__ ((asdf));", Space);
10476   verifyFormat("*(&a + 1);\n"
10477                "&((&a)[1]);\n"
10478                "a[(b + c) * d];\n"
10479                "(((a + 1) * 2) + 3) * 4;",
10480                Space);
10481   verifyFormat("#define A(x) x", Space);
10482   verifyFormat("#define A (x) x", Space);
10483   verifyFormat("#if defined(x)\n"
10484                "#endif",
10485                Space);
10486   verifyFormat("auto i = std::make_unique<int> (5);", Space);
10487   verifyFormat("size_t x = sizeof (x);", Space);
10488   verifyFormat("auto f (int x) -> decltype (x);", Space);
10489   verifyFormat("int f (T x) noexcept (x.create ());", Space);
10490   verifyFormat("alignas (128) char a[128];", Space);
10491   verifyFormat("size_t x = alignof (MyType);", Space);
10492   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
10493   verifyFormat("int f () throw (Deprecated);", Space);
10494   verifyFormat("typedef void (*cb) (int);", Space);
10495   verifyFormat("T A::operator() ();", Space);
10496   verifyFormat("X A::operator++ (T);", Space);
10497   verifyFormat("auto lambda = [] () { return 0; };", Space);
10498   verifyFormat("int x = int (y);", Space);
10499 
10500   FormatStyle SomeSpace = getLLVMStyle();
10501   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
10502 
10503   verifyFormat("[]() -> float {}", SomeSpace);
10504   verifyFormat("[] (auto foo) {}", SomeSpace);
10505   verifyFormat("[foo]() -> int {}", SomeSpace);
10506   verifyFormat("int f();", SomeSpace);
10507   verifyFormat("void f (int a, T b) {\n"
10508                "  while (true)\n"
10509                "    continue;\n"
10510                "}",
10511                SomeSpace);
10512   verifyFormat("if (true)\n"
10513                "  f();\n"
10514                "else if (true)\n"
10515                "  f();",
10516                SomeSpace);
10517   verifyFormat("do {\n"
10518                "  do_something();\n"
10519                "} while (something());",
10520                SomeSpace);
10521   verifyFormat("switch (x) {\n"
10522                "default:\n"
10523                "  break;\n"
10524                "}",
10525                SomeSpace);
10526   verifyFormat("A::A() : a (1) {}", SomeSpace);
10527   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
10528   verifyFormat("*(&a + 1);\n"
10529                "&((&a)[1]);\n"
10530                "a[(b + c) * d];\n"
10531                "(((a + 1) * 2) + 3) * 4;",
10532                SomeSpace);
10533   verifyFormat("#define A(x) x", SomeSpace);
10534   verifyFormat("#define A (x) x", SomeSpace);
10535   verifyFormat("#if defined(x)\n"
10536                "#endif",
10537                SomeSpace);
10538   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
10539   verifyFormat("size_t x = sizeof (x);", SomeSpace);
10540   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
10541   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
10542   verifyFormat("alignas (128) char a[128];", SomeSpace);
10543   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
10544   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
10545                SomeSpace);
10546   verifyFormat("int f() throw (Deprecated);", SomeSpace);
10547   verifyFormat("typedef void (*cb) (int);", SomeSpace);
10548   verifyFormat("T A::operator()();", SomeSpace);
10549   verifyFormat("X A::operator++ (T);", SomeSpace);
10550   verifyFormat("int x = int (y);", SomeSpace);
10551   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
10552 }
10553 
TEST_F(FormatTest,SpaceAfterLogicalNot)10554 TEST_F(FormatTest, SpaceAfterLogicalNot) {
10555   FormatStyle Spaces = getLLVMStyle();
10556   Spaces.SpaceAfterLogicalNot = true;
10557 
10558   verifyFormat("bool x = ! y", Spaces);
10559   verifyFormat("if (! isFailure())", Spaces);
10560   verifyFormat("if (! (a && b))", Spaces);
10561   verifyFormat("\"Error!\"", Spaces);
10562   verifyFormat("! ! x", Spaces);
10563 }
10564 
TEST_F(FormatTest,ConfigurableSpacesInParentheses)10565 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
10566   FormatStyle Spaces = getLLVMStyle();
10567 
10568   Spaces.SpacesInParentheses = true;
10569   verifyFormat("do_something( ::globalVar );", Spaces);
10570   verifyFormat("call( x, y, z );", Spaces);
10571   verifyFormat("call();", Spaces);
10572   verifyFormat("std::function<void( int, int )> callback;", Spaces);
10573   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
10574                Spaces);
10575   verifyFormat("while ( (bool)1 )\n"
10576                "  continue;",
10577                Spaces);
10578   verifyFormat("for ( ;; )\n"
10579                "  continue;",
10580                Spaces);
10581   verifyFormat("if ( true )\n"
10582                "  f();\n"
10583                "else if ( true )\n"
10584                "  f();",
10585                Spaces);
10586   verifyFormat("do {\n"
10587                "  do_something( (int)i );\n"
10588                "} while ( something() );",
10589                Spaces);
10590   verifyFormat("switch ( x ) {\n"
10591                "default:\n"
10592                "  break;\n"
10593                "}",
10594                Spaces);
10595 
10596   Spaces.SpacesInParentheses = false;
10597   Spaces.SpacesInCStyleCastParentheses = true;
10598   verifyFormat("Type *A = ( Type * )P;", Spaces);
10599   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
10600   verifyFormat("x = ( int32 )y;", Spaces);
10601   verifyFormat("int a = ( int )(2.0f);", Spaces);
10602   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
10603   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
10604   verifyFormat("#define x (( int )-1)", Spaces);
10605 
10606   // Run the first set of tests again with:
10607   Spaces.SpacesInParentheses = false;
10608   Spaces.SpaceInEmptyParentheses = true;
10609   Spaces.SpacesInCStyleCastParentheses = true;
10610   verifyFormat("call(x, y, z);", Spaces);
10611   verifyFormat("call( );", Spaces);
10612   verifyFormat("std::function<void(int, int)> callback;", Spaces);
10613   verifyFormat("while (( bool )1)\n"
10614                "  continue;",
10615                Spaces);
10616   verifyFormat("for (;;)\n"
10617                "  continue;",
10618                Spaces);
10619   verifyFormat("if (true)\n"
10620                "  f( );\n"
10621                "else if (true)\n"
10622                "  f( );",
10623                Spaces);
10624   verifyFormat("do {\n"
10625                "  do_something(( int )i);\n"
10626                "} while (something( ));",
10627                Spaces);
10628   verifyFormat("switch (x) {\n"
10629                "default:\n"
10630                "  break;\n"
10631                "}",
10632                Spaces);
10633 
10634   // Run the first set of tests again with:
10635   Spaces.SpaceAfterCStyleCast = true;
10636   verifyFormat("call(x, y, z);", Spaces);
10637   verifyFormat("call( );", Spaces);
10638   verifyFormat("std::function<void(int, int)> callback;", Spaces);
10639   verifyFormat("while (( bool ) 1)\n"
10640                "  continue;",
10641                Spaces);
10642   verifyFormat("for (;;)\n"
10643                "  continue;",
10644                Spaces);
10645   verifyFormat("if (true)\n"
10646                "  f( );\n"
10647                "else if (true)\n"
10648                "  f( );",
10649                Spaces);
10650   verifyFormat("do {\n"
10651                "  do_something(( int ) i);\n"
10652                "} while (something( ));",
10653                Spaces);
10654   verifyFormat("switch (x) {\n"
10655                "default:\n"
10656                "  break;\n"
10657                "}",
10658                Spaces);
10659 
10660   // Run subset of tests again with:
10661   Spaces.SpacesInCStyleCastParentheses = false;
10662   Spaces.SpaceAfterCStyleCast = true;
10663   verifyFormat("while ((bool) 1)\n"
10664                "  continue;",
10665                Spaces);
10666   verifyFormat("do {\n"
10667                "  do_something((int) i);\n"
10668                "} while (something( ));",
10669                Spaces);
10670 }
10671 
TEST_F(FormatTest,ConfigurableSpacesInSquareBrackets)10672 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
10673   verifyFormat("int a[5];");
10674   verifyFormat("a[3] += 42;");
10675 
10676   FormatStyle Spaces = getLLVMStyle();
10677   Spaces.SpacesInSquareBrackets = true;
10678   // Not lambdas.
10679   verifyFormat("int a[ 5 ];", Spaces);
10680   verifyFormat("a[ 3 ] += 42;", Spaces);
10681   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
10682   verifyFormat("double &operator[](int i) { return 0; }\n"
10683                "int i;",
10684                Spaces);
10685   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
10686   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
10687   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
10688   // Lambdas.
10689   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
10690   verifyFormat("return [ i, args... ] {};", Spaces);
10691   verifyFormat("int foo = [ &bar ]() {};", Spaces);
10692   verifyFormat("int foo = [ = ]() {};", Spaces);
10693   verifyFormat("int foo = [ & ]() {};", Spaces);
10694   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
10695   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
10696 }
10697 
TEST_F(FormatTest,ConfigurableSpaceBeforeBrackets)10698 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
10699   FormatStyle NoSpaceStyle = getLLVMStyle();
10700   verifyFormat("int a[5];", NoSpaceStyle);
10701   verifyFormat("a[3] += 42;", NoSpaceStyle);
10702 
10703   verifyFormat("int a[1];", NoSpaceStyle);
10704   verifyFormat("int 1 [a];", NoSpaceStyle);
10705   verifyFormat("int a[1][2];", NoSpaceStyle);
10706   verifyFormat("a[7] = 5;", NoSpaceStyle);
10707   verifyFormat("int a = (f())[23];", NoSpaceStyle);
10708   verifyFormat("f([] {})", NoSpaceStyle);
10709 
10710   FormatStyle Space = getLLVMStyle();
10711   Space.SpaceBeforeSquareBrackets = true;
10712   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
10713   verifyFormat("return [i, args...] {};", Space);
10714 
10715   verifyFormat("int a [5];", Space);
10716   verifyFormat("a [3] += 42;", Space);
10717   verifyFormat("constexpr char hello []{\"hello\"};", Space);
10718   verifyFormat("double &operator[](int i) { return 0; }\n"
10719                "int i;",
10720                Space);
10721   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
10722   verifyFormat("int i = a [a][a]->f();", Space);
10723   verifyFormat("int i = (*b) [a]->f();", Space);
10724 
10725   verifyFormat("int a [1];", Space);
10726   verifyFormat("int 1 [a];", Space);
10727   verifyFormat("int a [1][2];", Space);
10728   verifyFormat("a [7] = 5;", Space);
10729   verifyFormat("int a = (f()) [23];", Space);
10730   verifyFormat("f([] {})", Space);
10731 }
10732 
TEST_F(FormatTest,ConfigurableSpaceBeforeAssignmentOperators)10733 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
10734   verifyFormat("int a = 5;");
10735   verifyFormat("a += 42;");
10736   verifyFormat("a or_eq 8;");
10737 
10738   FormatStyle Spaces = getLLVMStyle();
10739   Spaces.SpaceBeforeAssignmentOperators = false;
10740   verifyFormat("int a= 5;", Spaces);
10741   verifyFormat("a+= 42;", Spaces);
10742   verifyFormat("a or_eq 8;", Spaces);
10743 }
10744 
TEST_F(FormatTest,ConfigurableSpaceBeforeColon)10745 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
10746   verifyFormat("class Foo : public Bar {};");
10747   verifyFormat("Foo::Foo() : foo(1) {}");
10748   verifyFormat("for (auto a : b) {\n}");
10749   verifyFormat("int x = a ? b : c;");
10750   verifyFormat("{\n"
10751                "label0:\n"
10752                "  int x = 0;\n"
10753                "}");
10754   verifyFormat("switch (x) {\n"
10755                "case 1:\n"
10756                "default:\n"
10757                "}");
10758 
10759   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
10760   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
10761   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
10762   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
10763   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
10764   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
10765   verifyFormat("{\n"
10766                "label1:\n"
10767                "  int x = 0;\n"
10768                "}",
10769                CtorInitializerStyle);
10770   verifyFormat("switch (x) {\n"
10771                "case 1:\n"
10772                "default:\n"
10773                "}",
10774                CtorInitializerStyle);
10775   CtorInitializerStyle.BreakConstructorInitializers =
10776       FormatStyle::BCIS_AfterColon;
10777   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
10778                "    aaaaaaaaaaaaaaaa(1),\n"
10779                "    bbbbbbbbbbbbbbbb(2) {}",
10780                CtorInitializerStyle);
10781   CtorInitializerStyle.BreakConstructorInitializers =
10782       FormatStyle::BCIS_BeforeComma;
10783   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
10784                "    : aaaaaaaaaaaaaaaa(1)\n"
10785                "    , bbbbbbbbbbbbbbbb(2) {}",
10786                CtorInitializerStyle);
10787   CtorInitializerStyle.BreakConstructorInitializers =
10788       FormatStyle::BCIS_BeforeColon;
10789   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
10790                "    : aaaaaaaaaaaaaaaa(1),\n"
10791                "      bbbbbbbbbbbbbbbb(2) {}",
10792                CtorInitializerStyle);
10793   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
10794   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
10795                ": aaaaaaaaaaaaaaaa(1),\n"
10796                "  bbbbbbbbbbbbbbbb(2) {}",
10797                CtorInitializerStyle);
10798 
10799   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
10800   InheritanceStyle.SpaceBeforeInheritanceColon = false;
10801   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
10802   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
10803   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
10804   verifyFormat("int x = a ? b : c;", InheritanceStyle);
10805   verifyFormat("{\n"
10806                "label2:\n"
10807                "  int x = 0;\n"
10808                "}",
10809                InheritanceStyle);
10810   verifyFormat("switch (x) {\n"
10811                "case 1:\n"
10812                "default:\n"
10813                "}",
10814                InheritanceStyle);
10815   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
10816   verifyFormat("class Foooooooooooooooooooooo:\n"
10817                "    public aaaaaaaaaaaaaaaaaa,\n"
10818                "    public bbbbbbbbbbbbbbbbbb {\n"
10819                "}",
10820                InheritanceStyle);
10821   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
10822   verifyFormat("class Foooooooooooooooooooooo\n"
10823                "    : public aaaaaaaaaaaaaaaaaa\n"
10824                "    , public bbbbbbbbbbbbbbbbbb {\n"
10825                "}",
10826                InheritanceStyle);
10827   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
10828   verifyFormat("class Foooooooooooooooooooooo\n"
10829                "    : public aaaaaaaaaaaaaaaaaa,\n"
10830                "      public bbbbbbbbbbbbbbbbbb {\n"
10831                "}",
10832                InheritanceStyle);
10833   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
10834   verifyFormat("class Foooooooooooooooooooooo\n"
10835                ": public aaaaaaaaaaaaaaaaaa,\n"
10836                "  public bbbbbbbbbbbbbbbbbb {}",
10837                InheritanceStyle);
10838 
10839   FormatStyle ForLoopStyle = getLLVMStyle();
10840   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
10841   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
10842   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
10843   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
10844   verifyFormat("int x = a ? b : c;", ForLoopStyle);
10845   verifyFormat("{\n"
10846                "label2:\n"
10847                "  int x = 0;\n"
10848                "}",
10849                ForLoopStyle);
10850   verifyFormat("switch (x) {\n"
10851                "case 1:\n"
10852                "default:\n"
10853                "}",
10854                ForLoopStyle);
10855 
10856   FormatStyle NoSpaceStyle = getLLVMStyle();
10857   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
10858   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
10859   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
10860   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
10861   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
10862   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
10863   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
10864   verifyFormat("{\n"
10865                "label3:\n"
10866                "  int x = 0;\n"
10867                "}",
10868                NoSpaceStyle);
10869   verifyFormat("switch (x) {\n"
10870                "case 1:\n"
10871                "default:\n"
10872                "}",
10873                NoSpaceStyle);
10874 }
10875 
TEST_F(FormatTest,AlignConsecutiveMacros)10876 TEST_F(FormatTest, AlignConsecutiveMacros) {
10877   FormatStyle Style = getLLVMStyle();
10878   Style.AlignConsecutiveAssignments = true;
10879   Style.AlignConsecutiveDeclarations = true;
10880   Style.AlignConsecutiveMacros = false;
10881 
10882   verifyFormat("#define a 3\n"
10883                "#define bbbb 4\n"
10884                "#define ccc (5)",
10885                Style);
10886 
10887   verifyFormat("#define f(x) (x * x)\n"
10888                "#define fff(x, y, z) (x * y + z)\n"
10889                "#define ffff(x, y) (x - y)",
10890                Style);
10891 
10892   verifyFormat("#define foo(x, y) (x + y)\n"
10893                "#define bar (5, 6)(2 + 2)",
10894                Style);
10895 
10896   verifyFormat("#define a 3\n"
10897                "#define bbbb 4\n"
10898                "#define ccc (5)\n"
10899                "#define f(x) (x * x)\n"
10900                "#define fff(x, y, z) (x * y + z)\n"
10901                "#define ffff(x, y) (x - y)",
10902                Style);
10903 
10904   Style.AlignConsecutiveMacros = true;
10905   verifyFormat("#define a    3\n"
10906                "#define bbbb 4\n"
10907                "#define ccc  (5)",
10908                Style);
10909 
10910   verifyFormat("#define f(x)         (x * x)\n"
10911                "#define fff(x, y, z) (x * y + z)\n"
10912                "#define ffff(x, y)   (x - y)",
10913                Style);
10914 
10915   verifyFormat("#define foo(x, y) (x + y)\n"
10916                "#define bar       (5, 6)(2 + 2)",
10917                Style);
10918 
10919   verifyFormat("#define a            3\n"
10920                "#define bbbb         4\n"
10921                "#define ccc          (5)\n"
10922                "#define f(x)         (x * x)\n"
10923                "#define fff(x, y, z) (x * y + z)\n"
10924                "#define ffff(x, y)   (x - y)",
10925                Style);
10926 
10927   verifyFormat("#define a         5\n"
10928                "#define foo(x, y) (x + y)\n"
10929                "#define CCC       (6)\n"
10930                "auto lambda = []() {\n"
10931                "  auto  ii = 0;\n"
10932                "  float j  = 0;\n"
10933                "  return 0;\n"
10934                "};\n"
10935                "int   i  = 0;\n"
10936                "float i2 = 0;\n"
10937                "auto  v  = type{\n"
10938                "    i = 1,   //\n"
10939                "    (i = 2), //\n"
10940                "    i = 3    //\n"
10941                "};",
10942                Style);
10943 
10944   Style.AlignConsecutiveMacros = false;
10945   Style.ColumnLimit = 20;
10946 
10947   verifyFormat("#define a          \\\n"
10948                "  \"aabbbbbbbbbbbb\"\n"
10949                "#define D          \\\n"
10950                "  \"aabbbbbbbbbbbb\" \\\n"
10951                "  \"ccddeeeeeeeee\"\n"
10952                "#define B          \\\n"
10953                "  \"QQQQQQQQQQQQQ\"  \\\n"
10954                "  \"FFFFFFFFFFFFF\"  \\\n"
10955                "  \"LLLLLLLL\"\n",
10956                Style);
10957 
10958   Style.AlignConsecutiveMacros = true;
10959   verifyFormat("#define a          \\\n"
10960                "  \"aabbbbbbbbbbbb\"\n"
10961                "#define D          \\\n"
10962                "  \"aabbbbbbbbbbbb\" \\\n"
10963                "  \"ccddeeeeeeeee\"\n"
10964                "#define B          \\\n"
10965                "  \"QQQQQQQQQQQQQ\"  \\\n"
10966                "  \"FFFFFFFFFFFFF\"  \\\n"
10967                "  \"LLLLLLLL\"\n",
10968                Style);
10969 }
10970 
TEST_F(FormatTest,AlignConsecutiveAssignments)10971 TEST_F(FormatTest, AlignConsecutiveAssignments) {
10972   FormatStyle Alignment = getLLVMStyle();
10973   Alignment.AlignConsecutiveMacros = true;
10974   Alignment.AlignConsecutiveAssignments = false;
10975   verifyFormat("int a = 5;\n"
10976                "int oneTwoThree = 123;",
10977                Alignment);
10978   verifyFormat("int a = 5;\n"
10979                "int oneTwoThree = 123;",
10980                Alignment);
10981 
10982   Alignment.AlignConsecutiveAssignments = true;
10983   verifyFormat("int a           = 5;\n"
10984                "int oneTwoThree = 123;",
10985                Alignment);
10986   verifyFormat("int a           = method();\n"
10987                "int oneTwoThree = 133;",
10988                Alignment);
10989   verifyFormat("a &= 5;\n"
10990                "bcd *= 5;\n"
10991                "ghtyf += 5;\n"
10992                "dvfvdb -= 5;\n"
10993                "a /= 5;\n"
10994                "vdsvsv %= 5;\n"
10995                "sfdbddfbdfbb ^= 5;\n"
10996                "dvsdsv |= 5;\n"
10997                "int dsvvdvsdvvv = 123;",
10998                Alignment);
10999   verifyFormat("int i = 1, j = 10;\n"
11000                "something = 2000;",
11001                Alignment);
11002   verifyFormat("something = 2000;\n"
11003                "int i = 1, j = 10;\n",
11004                Alignment);
11005   verifyFormat("something = 2000;\n"
11006                "another   = 911;\n"
11007                "int i = 1, j = 10;\n"
11008                "oneMore = 1;\n"
11009                "i       = 2;",
11010                Alignment);
11011   verifyFormat("int a   = 5;\n"
11012                "int one = 1;\n"
11013                "method();\n"
11014                "int oneTwoThree = 123;\n"
11015                "int oneTwo      = 12;",
11016                Alignment);
11017   verifyFormat("int oneTwoThree = 123;\n"
11018                "int oneTwo      = 12;\n"
11019                "method();\n",
11020                Alignment);
11021   verifyFormat("int oneTwoThree = 123; // comment\n"
11022                "int oneTwo      = 12;  // comment",
11023                Alignment);
11024   EXPECT_EQ("int a = 5;\n"
11025             "\n"
11026             "int oneTwoThree = 123;",
11027             format("int a       = 5;\n"
11028                    "\n"
11029                    "int oneTwoThree= 123;",
11030                    Alignment));
11031   EXPECT_EQ("int a   = 5;\n"
11032             "int one = 1;\n"
11033             "\n"
11034             "int oneTwoThree = 123;",
11035             format("int a = 5;\n"
11036                    "int one = 1;\n"
11037                    "\n"
11038                    "int oneTwoThree = 123;",
11039                    Alignment));
11040   EXPECT_EQ("int a   = 5;\n"
11041             "int one = 1;\n"
11042             "\n"
11043             "int oneTwoThree = 123;\n"
11044             "int oneTwo      = 12;",
11045             format("int a = 5;\n"
11046                    "int one = 1;\n"
11047                    "\n"
11048                    "int oneTwoThree = 123;\n"
11049                    "int oneTwo = 12;",
11050                    Alignment));
11051   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
11052   verifyFormat("#define A \\\n"
11053                "  int aaaa       = 12; \\\n"
11054                "  int b          = 23; \\\n"
11055                "  int ccc        = 234; \\\n"
11056                "  int dddddddddd = 2345;",
11057                Alignment);
11058   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11059   verifyFormat("#define A               \\\n"
11060                "  int aaaa       = 12;  \\\n"
11061                "  int b          = 23;  \\\n"
11062                "  int ccc        = 234; \\\n"
11063                "  int dddddddddd = 2345;",
11064                Alignment);
11065   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
11066   verifyFormat("#define A                                                      "
11067                "                \\\n"
11068                "  int aaaa       = 12;                                         "
11069                "                \\\n"
11070                "  int b          = 23;                                         "
11071                "                \\\n"
11072                "  int ccc        = 234;                                        "
11073                "                \\\n"
11074                "  int dddddddddd = 2345;",
11075                Alignment);
11076   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
11077                "k = 4, int l = 5,\n"
11078                "                  int m = 6) {\n"
11079                "  int j      = 10;\n"
11080                "  otherThing = 1;\n"
11081                "}",
11082                Alignment);
11083   verifyFormat("void SomeFunction(int parameter = 0) {\n"
11084                "  int i   = 1;\n"
11085                "  int j   = 2;\n"
11086                "  int big = 10000;\n"
11087                "}",
11088                Alignment);
11089   verifyFormat("class C {\n"
11090                "public:\n"
11091                "  int i            = 1;\n"
11092                "  virtual void f() = 0;\n"
11093                "};",
11094                Alignment);
11095   verifyFormat("int i = 1;\n"
11096                "if (SomeType t = getSomething()) {\n"
11097                "}\n"
11098                "int j   = 2;\n"
11099                "int big = 10000;",
11100                Alignment);
11101   verifyFormat("int j = 7;\n"
11102                "for (int k = 0; k < N; ++k) {\n"
11103                "}\n"
11104                "int j   = 2;\n"
11105                "int big = 10000;\n"
11106                "}",
11107                Alignment);
11108   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
11109   verifyFormat("int i = 1;\n"
11110                "LooooooooooongType loooooooooooooooooooooongVariable\n"
11111                "    = someLooooooooooooooooongFunction();\n"
11112                "int j = 2;",
11113                Alignment);
11114   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
11115   verifyFormat("int i = 1;\n"
11116                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
11117                "    someLooooooooooooooooongFunction();\n"
11118                "int j = 2;",
11119                Alignment);
11120 
11121   verifyFormat("auto lambda = []() {\n"
11122                "  auto i = 0;\n"
11123                "  return 0;\n"
11124                "};\n"
11125                "int i  = 0;\n"
11126                "auto v = type{\n"
11127                "    i = 1,   //\n"
11128                "    (i = 2), //\n"
11129                "    i = 3    //\n"
11130                "};",
11131                Alignment);
11132 
11133   verifyFormat(
11134       "int i      = 1;\n"
11135       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
11136       "                          loooooooooooooooooooooongParameterB);\n"
11137       "int j      = 2;",
11138       Alignment);
11139 
11140   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
11141                "          typename B   = very_long_type_name_1,\n"
11142                "          typename T_2 = very_long_type_name_2>\n"
11143                "auto foo() {}\n",
11144                Alignment);
11145   verifyFormat("int a, b = 1;\n"
11146                "int c  = 2;\n"
11147                "int dd = 3;\n",
11148                Alignment);
11149   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
11150                "float b[1][] = {{3.f}};\n",
11151                Alignment);
11152   verifyFormat("for (int i = 0; i < 1; i++)\n"
11153                "  int x = 1;\n",
11154                Alignment);
11155   verifyFormat("for (i = 0; i < 1; i++)\n"
11156                "  x = 1;\n"
11157                "y = 1;\n",
11158                Alignment);
11159 }
11160 
TEST_F(FormatTest,AlignConsecutiveDeclarations)11161 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
11162   FormatStyle Alignment = getLLVMStyle();
11163   Alignment.AlignConsecutiveMacros = true;
11164   Alignment.AlignConsecutiveDeclarations = false;
11165   verifyFormat("float const a = 5;\n"
11166                "int oneTwoThree = 123;",
11167                Alignment);
11168   verifyFormat("int a = 5;\n"
11169                "float const oneTwoThree = 123;",
11170                Alignment);
11171 
11172   Alignment.AlignConsecutiveDeclarations = true;
11173   verifyFormat("float const a = 5;\n"
11174                "int         oneTwoThree = 123;",
11175                Alignment);
11176   verifyFormat("int         a = method();\n"
11177                "float const oneTwoThree = 133;",
11178                Alignment);
11179   verifyFormat("int i = 1, j = 10;\n"
11180                "something = 2000;",
11181                Alignment);
11182   verifyFormat("something = 2000;\n"
11183                "int i = 1, j = 10;\n",
11184                Alignment);
11185   verifyFormat("float      something = 2000;\n"
11186                "double     another = 911;\n"
11187                "int        i = 1, j = 10;\n"
11188                "const int *oneMore = 1;\n"
11189                "unsigned   i = 2;",
11190                Alignment);
11191   verifyFormat("float a = 5;\n"
11192                "int   one = 1;\n"
11193                "method();\n"
11194                "const double       oneTwoThree = 123;\n"
11195                "const unsigned int oneTwo = 12;",
11196                Alignment);
11197   verifyFormat("int      oneTwoThree{0}; // comment\n"
11198                "unsigned oneTwo;         // comment",
11199                Alignment);
11200   EXPECT_EQ("float const a = 5;\n"
11201             "\n"
11202             "int oneTwoThree = 123;",
11203             format("float const   a = 5;\n"
11204                    "\n"
11205                    "int           oneTwoThree= 123;",
11206                    Alignment));
11207   EXPECT_EQ("float a = 5;\n"
11208             "int   one = 1;\n"
11209             "\n"
11210             "unsigned oneTwoThree = 123;",
11211             format("float    a = 5;\n"
11212                    "int      one = 1;\n"
11213                    "\n"
11214                    "unsigned oneTwoThree = 123;",
11215                    Alignment));
11216   EXPECT_EQ("float a = 5;\n"
11217             "int   one = 1;\n"
11218             "\n"
11219             "unsigned oneTwoThree = 123;\n"
11220             "int      oneTwo = 12;",
11221             format("float    a = 5;\n"
11222                    "int one = 1;\n"
11223                    "\n"
11224                    "unsigned oneTwoThree = 123;\n"
11225                    "int oneTwo = 12;",
11226                    Alignment));
11227   // Function prototype alignment
11228   verifyFormat("int    a();\n"
11229                "double b();",
11230                Alignment);
11231   verifyFormat("int    a(int x);\n"
11232                "double b();",
11233                Alignment);
11234   unsigned OldColumnLimit = Alignment.ColumnLimit;
11235   // We need to set ColumnLimit to zero, in order to stress nested alignments,
11236   // otherwise the function parameters will be re-flowed onto a single line.
11237   Alignment.ColumnLimit = 0;
11238   EXPECT_EQ("int    a(int   x,\n"
11239             "         float y);\n"
11240             "double b(int    x,\n"
11241             "         double y);",
11242             format("int a(int x,\n"
11243                    " float y);\n"
11244                    "double b(int x,\n"
11245                    " double y);",
11246                    Alignment));
11247   // This ensures that function parameters of function declarations are
11248   // correctly indented when their owning functions are indented.
11249   // The failure case here is for 'double y' to not be indented enough.
11250   EXPECT_EQ("double a(int x);\n"
11251             "int    b(int    y,\n"
11252             "         double z);",
11253             format("double a(int x);\n"
11254                    "int b(int y,\n"
11255                    " double z);",
11256                    Alignment));
11257   // Set ColumnLimit low so that we induce wrapping immediately after
11258   // the function name and opening paren.
11259   Alignment.ColumnLimit = 13;
11260   verifyFormat("int function(\n"
11261                "    int  x,\n"
11262                "    bool y);",
11263                Alignment);
11264   Alignment.ColumnLimit = OldColumnLimit;
11265   // Ensure function pointers don't screw up recursive alignment
11266   verifyFormat("int    a(int x, void (*fp)(int y));\n"
11267                "double b();",
11268                Alignment);
11269   Alignment.AlignConsecutiveAssignments = true;
11270   // Ensure recursive alignment is broken by function braces, so that the
11271   // "a = 1" does not align with subsequent assignments inside the function
11272   // body.
11273   verifyFormat("int func(int a = 1) {\n"
11274                "  int b  = 2;\n"
11275                "  int cc = 3;\n"
11276                "}",
11277                Alignment);
11278   verifyFormat("float      something = 2000;\n"
11279                "double     another   = 911;\n"
11280                "int        i = 1, j = 10;\n"
11281                "const int *oneMore = 1;\n"
11282                "unsigned   i       = 2;",
11283                Alignment);
11284   verifyFormat("int      oneTwoThree = {0}; // comment\n"
11285                "unsigned oneTwo      = 0;   // comment",
11286                Alignment);
11287   // Make sure that scope is correctly tracked, in the absence of braces
11288   verifyFormat("for (int i = 0; i < n; i++)\n"
11289                "  j = i;\n"
11290                "double x = 1;\n",
11291                Alignment);
11292   verifyFormat("if (int i = 0)\n"
11293                "  j = i;\n"
11294                "double x = 1;\n",
11295                Alignment);
11296   // Ensure operator[] and operator() are comprehended
11297   verifyFormat("struct test {\n"
11298                "  long long int foo();\n"
11299                "  int           operator[](int a);\n"
11300                "  double        bar();\n"
11301                "};\n",
11302                Alignment);
11303   verifyFormat("struct test {\n"
11304                "  long long int foo();\n"
11305                "  int           operator()(int a);\n"
11306                "  double        bar();\n"
11307                "};\n",
11308                Alignment);
11309   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
11310             "  int const i   = 1;\n"
11311             "  int *     j   = 2;\n"
11312             "  int       big = 10000;\n"
11313             "\n"
11314             "  unsigned oneTwoThree = 123;\n"
11315             "  int      oneTwo      = 12;\n"
11316             "  method();\n"
11317             "  float k  = 2;\n"
11318             "  int   ll = 10000;\n"
11319             "}",
11320             format("void SomeFunction(int parameter= 0) {\n"
11321                    " int const  i= 1;\n"
11322                    "  int *j=2;\n"
11323                    " int big  =  10000;\n"
11324                    "\n"
11325                    "unsigned oneTwoThree  =123;\n"
11326                    "int oneTwo = 12;\n"
11327                    "  method();\n"
11328                    "float k= 2;\n"
11329                    "int ll=10000;\n"
11330                    "}",
11331                    Alignment));
11332   Alignment.AlignConsecutiveAssignments = false;
11333   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
11334   verifyFormat("#define A \\\n"
11335                "  int       aaaa = 12; \\\n"
11336                "  float     b = 23; \\\n"
11337                "  const int ccc = 234; \\\n"
11338                "  unsigned  dddddddddd = 2345;",
11339                Alignment);
11340   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11341   verifyFormat("#define A              \\\n"
11342                "  int       aaaa = 12; \\\n"
11343                "  float     b = 23;    \\\n"
11344                "  const int ccc = 234; \\\n"
11345                "  unsigned  dddddddddd = 2345;",
11346                Alignment);
11347   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
11348   Alignment.ColumnLimit = 30;
11349   verifyFormat("#define A                    \\\n"
11350                "  int       aaaa = 12;       \\\n"
11351                "  float     b = 23;          \\\n"
11352                "  const int ccc = 234;       \\\n"
11353                "  int       dddddddddd = 2345;",
11354                Alignment);
11355   Alignment.ColumnLimit = 80;
11356   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
11357                "k = 4, int l = 5,\n"
11358                "                  int m = 6) {\n"
11359                "  const int j = 10;\n"
11360                "  otherThing = 1;\n"
11361                "}",
11362                Alignment);
11363   verifyFormat("void SomeFunction(int parameter = 0) {\n"
11364                "  int const i = 1;\n"
11365                "  int *     j = 2;\n"
11366                "  int       big = 10000;\n"
11367                "}",
11368                Alignment);
11369   verifyFormat("class C {\n"
11370                "public:\n"
11371                "  int          i = 1;\n"
11372                "  virtual void f() = 0;\n"
11373                "};",
11374                Alignment);
11375   verifyFormat("float i = 1;\n"
11376                "if (SomeType t = getSomething()) {\n"
11377                "}\n"
11378                "const unsigned j = 2;\n"
11379                "int            big = 10000;",
11380                Alignment);
11381   verifyFormat("float j = 7;\n"
11382                "for (int k = 0; k < N; ++k) {\n"
11383                "}\n"
11384                "unsigned j = 2;\n"
11385                "int      big = 10000;\n"
11386                "}",
11387                Alignment);
11388   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
11389   verifyFormat("float              i = 1;\n"
11390                "LooooooooooongType loooooooooooooooooooooongVariable\n"
11391                "    = someLooooooooooooooooongFunction();\n"
11392                "int j = 2;",
11393                Alignment);
11394   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
11395   verifyFormat("int                i = 1;\n"
11396                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
11397                "    someLooooooooooooooooongFunction();\n"
11398                "int j = 2;",
11399                Alignment);
11400 
11401   Alignment.AlignConsecutiveAssignments = true;
11402   verifyFormat("auto lambda = []() {\n"
11403                "  auto  ii = 0;\n"
11404                "  float j  = 0;\n"
11405                "  return 0;\n"
11406                "};\n"
11407                "int   i  = 0;\n"
11408                "float i2 = 0;\n"
11409                "auto  v  = type{\n"
11410                "    i = 1,   //\n"
11411                "    (i = 2), //\n"
11412                "    i = 3    //\n"
11413                "};",
11414                Alignment);
11415   Alignment.AlignConsecutiveAssignments = false;
11416 
11417   verifyFormat(
11418       "int      i = 1;\n"
11419       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
11420       "                          loooooooooooooooooooooongParameterB);\n"
11421       "int      j = 2;",
11422       Alignment);
11423 
11424   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
11425   // We expect declarations and assignments to align, as long as it doesn't
11426   // exceed the column limit, starting a new alignment sequence whenever it
11427   // happens.
11428   Alignment.AlignConsecutiveAssignments = true;
11429   Alignment.ColumnLimit = 30;
11430   verifyFormat("float    ii              = 1;\n"
11431                "unsigned j               = 2;\n"
11432                "int someVerylongVariable = 1;\n"
11433                "AnotherLongType  ll = 123456;\n"
11434                "VeryVeryLongType k  = 2;\n"
11435                "int              myvar = 1;",
11436                Alignment);
11437   Alignment.ColumnLimit = 80;
11438   Alignment.AlignConsecutiveAssignments = false;
11439 
11440   verifyFormat(
11441       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
11442       "          typename LongType, typename B>\n"
11443       "auto foo() {}\n",
11444       Alignment);
11445   verifyFormat("float a, b = 1;\n"
11446                "int   c = 2;\n"
11447                "int   dd = 3;\n",
11448                Alignment);
11449   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
11450                "float b[1][] = {{3.f}};\n",
11451                Alignment);
11452   Alignment.AlignConsecutiveAssignments = true;
11453   verifyFormat("float a, b = 1;\n"
11454                "int   c  = 2;\n"
11455                "int   dd = 3;\n",
11456                Alignment);
11457   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
11458                "float b[1][] = {{3.f}};\n",
11459                Alignment);
11460   Alignment.AlignConsecutiveAssignments = false;
11461 
11462   Alignment.ColumnLimit = 30;
11463   Alignment.BinPackParameters = false;
11464   verifyFormat("void foo(float     a,\n"
11465                "         float     b,\n"
11466                "         int       c,\n"
11467                "         uint32_t *d) {\n"
11468                "  int *  e = 0;\n"
11469                "  float  f = 0;\n"
11470                "  double g = 0;\n"
11471                "}\n"
11472                "void bar(ino_t     a,\n"
11473                "         int       b,\n"
11474                "         uint32_t *c,\n"
11475                "         bool      d) {}\n",
11476                Alignment);
11477   Alignment.BinPackParameters = true;
11478   Alignment.ColumnLimit = 80;
11479 
11480   // Bug 33507
11481   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
11482   verifyFormat(
11483       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
11484       "  static const Version verVs2017;\n"
11485       "  return true;\n"
11486       "});\n",
11487       Alignment);
11488   Alignment.PointerAlignment = FormatStyle::PAS_Right;
11489 
11490   // See llvm.org/PR35641
11491   Alignment.AlignConsecutiveDeclarations = true;
11492   verifyFormat("int func() { //\n"
11493                "  int      b;\n"
11494                "  unsigned c;\n"
11495                "}",
11496                Alignment);
11497 
11498   // See PR37175
11499   FormatStyle Style = getMozillaStyle();
11500   Style.AlignConsecutiveDeclarations = true;
11501   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
11502             "foo(int a);",
11503             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
11504 }
11505 
TEST_F(FormatTest,LinuxBraceBreaking)11506 TEST_F(FormatTest, LinuxBraceBreaking) {
11507   FormatStyle LinuxBraceStyle = getLLVMStyle();
11508   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
11509   verifyFormat("namespace a\n"
11510                "{\n"
11511                "class A\n"
11512                "{\n"
11513                "  void f()\n"
11514                "  {\n"
11515                "    if (true) {\n"
11516                "      a();\n"
11517                "      b();\n"
11518                "    } else {\n"
11519                "      a();\n"
11520                "    }\n"
11521                "  }\n"
11522                "  void g() { return; }\n"
11523                "};\n"
11524                "struct B {\n"
11525                "  int x;\n"
11526                "};\n"
11527                "} // namespace a\n",
11528                LinuxBraceStyle);
11529   verifyFormat("enum X {\n"
11530                "  Y = 0,\n"
11531                "}\n",
11532                LinuxBraceStyle);
11533   verifyFormat("struct S {\n"
11534                "  int Type;\n"
11535                "  union {\n"
11536                "    int x;\n"
11537                "    double y;\n"
11538                "  } Value;\n"
11539                "  class C\n"
11540                "  {\n"
11541                "    MyFavoriteType Value;\n"
11542                "  } Class;\n"
11543                "}\n",
11544                LinuxBraceStyle);
11545 }
11546 
TEST_F(FormatTest,MozillaBraceBreaking)11547 TEST_F(FormatTest, MozillaBraceBreaking) {
11548   FormatStyle MozillaBraceStyle = getLLVMStyle();
11549   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
11550   MozillaBraceStyle.FixNamespaceComments = false;
11551   verifyFormat("namespace a {\n"
11552                "class A\n"
11553                "{\n"
11554                "  void f()\n"
11555                "  {\n"
11556                "    if (true) {\n"
11557                "      a();\n"
11558                "      b();\n"
11559                "    }\n"
11560                "  }\n"
11561                "  void g() { return; }\n"
11562                "};\n"
11563                "enum E\n"
11564                "{\n"
11565                "  A,\n"
11566                "  // foo\n"
11567                "  B,\n"
11568                "  C\n"
11569                "};\n"
11570                "struct B\n"
11571                "{\n"
11572                "  int x;\n"
11573                "};\n"
11574                "}\n",
11575                MozillaBraceStyle);
11576   verifyFormat("struct S\n"
11577                "{\n"
11578                "  int Type;\n"
11579                "  union\n"
11580                "  {\n"
11581                "    int x;\n"
11582                "    double y;\n"
11583                "  } Value;\n"
11584                "  class C\n"
11585                "  {\n"
11586                "    MyFavoriteType Value;\n"
11587                "  } Class;\n"
11588                "}\n",
11589                MozillaBraceStyle);
11590 }
11591 
TEST_F(FormatTest,StroustrupBraceBreaking)11592 TEST_F(FormatTest, StroustrupBraceBreaking) {
11593   FormatStyle StroustrupBraceStyle = getLLVMStyle();
11594   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
11595   verifyFormat("namespace a {\n"
11596                "class A {\n"
11597                "  void f()\n"
11598                "  {\n"
11599                "    if (true) {\n"
11600                "      a();\n"
11601                "      b();\n"
11602                "    }\n"
11603                "  }\n"
11604                "  void g() { return; }\n"
11605                "};\n"
11606                "struct B {\n"
11607                "  int x;\n"
11608                "};\n"
11609                "} // namespace a\n",
11610                StroustrupBraceStyle);
11611 
11612   verifyFormat("void foo()\n"
11613                "{\n"
11614                "  if (a) {\n"
11615                "    a();\n"
11616                "  }\n"
11617                "  else {\n"
11618                "    b();\n"
11619                "  }\n"
11620                "}\n",
11621                StroustrupBraceStyle);
11622 
11623   verifyFormat("#ifdef _DEBUG\n"
11624                "int foo(int i = 0)\n"
11625                "#else\n"
11626                "int foo(int i = 5)\n"
11627                "#endif\n"
11628                "{\n"
11629                "  return i;\n"
11630                "}",
11631                StroustrupBraceStyle);
11632 
11633   verifyFormat("void foo() {}\n"
11634                "void bar()\n"
11635                "#ifdef _DEBUG\n"
11636                "{\n"
11637                "  foo();\n"
11638                "}\n"
11639                "#else\n"
11640                "{\n"
11641                "}\n"
11642                "#endif",
11643                StroustrupBraceStyle);
11644 
11645   verifyFormat("void foobar() { int i = 5; }\n"
11646                "#ifdef _DEBUG\n"
11647                "void bar() {}\n"
11648                "#else\n"
11649                "void bar() { foobar(); }\n"
11650                "#endif",
11651                StroustrupBraceStyle);
11652 }
11653 
TEST_F(FormatTest,AllmanBraceBreaking)11654 TEST_F(FormatTest, AllmanBraceBreaking) {
11655   FormatStyle AllmanBraceStyle = getLLVMStyle();
11656   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
11657 
11658   EXPECT_EQ("namespace a\n"
11659             "{\n"
11660             "void f();\n"
11661             "void g();\n"
11662             "} // namespace a\n",
11663             format("namespace a\n"
11664                    "{\n"
11665                    "void f();\n"
11666                    "void g();\n"
11667                    "}\n",
11668                    AllmanBraceStyle));
11669 
11670   verifyFormat("namespace a\n"
11671                "{\n"
11672                "class A\n"
11673                "{\n"
11674                "  void f()\n"
11675                "  {\n"
11676                "    if (true)\n"
11677                "    {\n"
11678                "      a();\n"
11679                "      b();\n"
11680                "    }\n"
11681                "  }\n"
11682                "  void g() { return; }\n"
11683                "};\n"
11684                "struct B\n"
11685                "{\n"
11686                "  int x;\n"
11687                "};\n"
11688                "union C\n"
11689                "{\n"
11690                "};\n"
11691                "} // namespace a",
11692                AllmanBraceStyle);
11693 
11694   verifyFormat("void f()\n"
11695                "{\n"
11696                "  if (true)\n"
11697                "  {\n"
11698                "    a();\n"
11699                "  }\n"
11700                "  else if (false)\n"
11701                "  {\n"
11702                "    b();\n"
11703                "  }\n"
11704                "  else\n"
11705                "  {\n"
11706                "    c();\n"
11707                "  }\n"
11708                "}\n",
11709                AllmanBraceStyle);
11710 
11711   verifyFormat("void f()\n"
11712                "{\n"
11713                "  for (int i = 0; i < 10; ++i)\n"
11714                "  {\n"
11715                "    a();\n"
11716                "  }\n"
11717                "  while (false)\n"
11718                "  {\n"
11719                "    b();\n"
11720                "  }\n"
11721                "  do\n"
11722                "  {\n"
11723                "    c();\n"
11724                "  } while (false)\n"
11725                "}\n",
11726                AllmanBraceStyle);
11727 
11728   verifyFormat("void f(int a)\n"
11729                "{\n"
11730                "  switch (a)\n"
11731                "  {\n"
11732                "  case 0:\n"
11733                "    break;\n"
11734                "  case 1:\n"
11735                "  {\n"
11736                "    break;\n"
11737                "  }\n"
11738                "  case 2:\n"
11739                "  {\n"
11740                "  }\n"
11741                "  break;\n"
11742                "  default:\n"
11743                "    break;\n"
11744                "  }\n"
11745                "}\n",
11746                AllmanBraceStyle);
11747 
11748   verifyFormat("enum X\n"
11749                "{\n"
11750                "  Y = 0,\n"
11751                "}\n",
11752                AllmanBraceStyle);
11753   verifyFormat("enum X\n"
11754                "{\n"
11755                "  Y = 0\n"
11756                "}\n",
11757                AllmanBraceStyle);
11758 
11759   verifyFormat("@interface BSApplicationController ()\n"
11760                "{\n"
11761                "@private\n"
11762                "  id _extraIvar;\n"
11763                "}\n"
11764                "@end\n",
11765                AllmanBraceStyle);
11766 
11767   verifyFormat("#ifdef _DEBUG\n"
11768                "int foo(int i = 0)\n"
11769                "#else\n"
11770                "int foo(int i = 5)\n"
11771                "#endif\n"
11772                "{\n"
11773                "  return i;\n"
11774                "}",
11775                AllmanBraceStyle);
11776 
11777   verifyFormat("void foo() {}\n"
11778                "void bar()\n"
11779                "#ifdef _DEBUG\n"
11780                "{\n"
11781                "  foo();\n"
11782                "}\n"
11783                "#else\n"
11784                "{\n"
11785                "}\n"
11786                "#endif",
11787                AllmanBraceStyle);
11788 
11789   verifyFormat("void foobar() { int i = 5; }\n"
11790                "#ifdef _DEBUG\n"
11791                "void bar() {}\n"
11792                "#else\n"
11793                "void bar() { foobar(); }\n"
11794                "#endif",
11795                AllmanBraceStyle);
11796 
11797   // This shouldn't affect ObjC blocks..
11798   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
11799                "  // ...\n"
11800                "  int i;\n"
11801                "}];",
11802                AllmanBraceStyle);
11803   verifyFormat("void (^block)(void) = ^{\n"
11804                "  // ...\n"
11805                "  int i;\n"
11806                "};",
11807                AllmanBraceStyle);
11808   // .. or dict literals.
11809   verifyFormat("void f()\n"
11810                "{\n"
11811                "  // ...\n"
11812                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
11813                "}",
11814                AllmanBraceStyle);
11815   verifyFormat("void f()\n"
11816                "{\n"
11817                "  // ...\n"
11818                "  [object someMethod:@{a : @\"b\"}];\n"
11819                "}",
11820                AllmanBraceStyle);
11821   verifyFormat("int f()\n"
11822                "{ // comment\n"
11823                "  return 42;\n"
11824                "}",
11825                AllmanBraceStyle);
11826 
11827   AllmanBraceStyle.ColumnLimit = 19;
11828   verifyFormat("void f() { int i; }", AllmanBraceStyle);
11829   AllmanBraceStyle.ColumnLimit = 18;
11830   verifyFormat("void f()\n"
11831                "{\n"
11832                "  int i;\n"
11833                "}",
11834                AllmanBraceStyle);
11835   AllmanBraceStyle.ColumnLimit = 80;
11836 
11837   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
11838   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
11839       FormatStyle::SIS_WithoutElse;
11840   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
11841   verifyFormat("void f(bool b)\n"
11842                "{\n"
11843                "  if (b)\n"
11844                "  {\n"
11845                "    return;\n"
11846                "  }\n"
11847                "}\n",
11848                BreakBeforeBraceShortIfs);
11849   verifyFormat("void f(bool b)\n"
11850                "{\n"
11851                "  if constexpr (b)\n"
11852                "  {\n"
11853                "    return;\n"
11854                "  }\n"
11855                "}\n",
11856                BreakBeforeBraceShortIfs);
11857   verifyFormat("void f(bool b)\n"
11858                "{\n"
11859                "  if CONSTEXPR (b)\n"
11860                "  {\n"
11861                "    return;\n"
11862                "  }\n"
11863                "}\n",
11864                BreakBeforeBraceShortIfs);
11865   verifyFormat("void f(bool b)\n"
11866                "{\n"
11867                "  if (b) return;\n"
11868                "}\n",
11869                BreakBeforeBraceShortIfs);
11870   verifyFormat("void f(bool b)\n"
11871                "{\n"
11872                "  if constexpr (b) return;\n"
11873                "}\n",
11874                BreakBeforeBraceShortIfs);
11875   verifyFormat("void f(bool b)\n"
11876                "{\n"
11877                "  if CONSTEXPR (b) return;\n"
11878                "}\n",
11879                BreakBeforeBraceShortIfs);
11880   verifyFormat("void f(bool b)\n"
11881                "{\n"
11882                "  while (b)\n"
11883                "  {\n"
11884                "    return;\n"
11885                "  }\n"
11886                "}\n",
11887                BreakBeforeBraceShortIfs);
11888 }
11889 
TEST_F(FormatTest,WhitesmithsBraceBreaking)11890 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
11891   FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
11892   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
11893 
11894   // Make a few changes to the style for testing purposes
11895   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
11896       FormatStyle::SFS_Empty;
11897   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
11898   WhitesmithsBraceStyle.ColumnLimit = 0;
11899 
11900   // FIXME: this test case can't decide whether there should be a blank line
11901   // after the ~D() line or not. It adds one if one doesn't exist in the test
11902   // and it removes the line if one exists.
11903   /*
11904   verifyFormat("class A;\n"
11905                "namespace B\n"
11906                "  {\n"
11907                "class C;\n"
11908                "// Comment\n"
11909                "class D\n"
11910                "  {\n"
11911                "public:\n"
11912                "  D();\n"
11913                "  ~D() {}\n"
11914                "private:\n"
11915                "  enum E\n"
11916                "    {\n"
11917                "    F\n"
11918                "    }\n"
11919                "  };\n"
11920                "  } // namespace B\n",
11921                WhitesmithsBraceStyle);
11922   */
11923 
11924   verifyFormat("namespace a\n"
11925                "  {\n"
11926                "class A\n"
11927                "  {\n"
11928                "  void f()\n"
11929                "    {\n"
11930                "    if (true)\n"
11931                "      {\n"
11932                "      a();\n"
11933                "      b();\n"
11934                "      }\n"
11935                "    }\n"
11936                "  void g()\n"
11937                "    {\n"
11938                "    return;\n"
11939                "    }\n"
11940                "  };\n"
11941                "struct B\n"
11942                "  {\n"
11943                "  int x;\n"
11944                "  };\n"
11945                "  } // namespace a",
11946                WhitesmithsBraceStyle);
11947 
11948   verifyFormat("void f()\n"
11949                "  {\n"
11950                "  if (true)\n"
11951                "    {\n"
11952                "    a();\n"
11953                "    }\n"
11954                "  else if (false)\n"
11955                "    {\n"
11956                "    b();\n"
11957                "    }\n"
11958                "  else\n"
11959                "    {\n"
11960                "    c();\n"
11961                "    }\n"
11962                "  }\n",
11963                WhitesmithsBraceStyle);
11964 
11965   verifyFormat("void f()\n"
11966                "  {\n"
11967                "  for (int i = 0; i < 10; ++i)\n"
11968                "    {\n"
11969                "    a();\n"
11970                "    }\n"
11971                "  while (false)\n"
11972                "    {\n"
11973                "    b();\n"
11974                "    }\n"
11975                "  do\n"
11976                "    {\n"
11977                "    c();\n"
11978                "    } while (false)\n"
11979                "  }\n",
11980                WhitesmithsBraceStyle);
11981 
11982   // FIXME: the block and the break under case 2 in this test don't get indented
11983   // correctly
11984   /*
11985   verifyFormat("void switchTest1(int a)\n"
11986                "  {\n"
11987                "  switch (a)\n"
11988                "    {\n"
11989                "    case 2:\n"
11990                "      {\n"
11991                "      }\n"
11992                "      break;\n"
11993                "    }\n"
11994                "  }\n",
11995                WhitesmithsBraceStyle);
11996   */
11997 
11998   // FIXME: the block and the break under case 2 in this test don't get indented
11999   // correctly
12000   /*
12001   verifyFormat("void switchTest2(int a)\n"
12002                "  {\n"
12003                "  switch (a)\n"
12004                "    {\n"
12005                "  case 0:\n"
12006                "    break;\n"
12007                "  case 1:\n"
12008                "    {\n"
12009                "    break;\n"
12010                "    }\n"
12011                "  case 2:\n"
12012                "    {\n"
12013                "    }\n"
12014                "    break;\n"
12015                "  default:\n"
12016                "    break;\n"
12017                "    }\n"
12018                "  }\n",
12019                WhitesmithsBraceStyle);
12020   */
12021 
12022   verifyFormat("enum X\n"
12023                "  {\n"
12024                "  Y = 0, // testing\n"
12025                "  }\n",
12026                WhitesmithsBraceStyle);
12027 
12028   verifyFormat("enum X\n"
12029                "  {\n"
12030                "  Y = 0\n"
12031                "  }\n",
12032                WhitesmithsBraceStyle);
12033   verifyFormat("enum X\n"
12034                "  {\n"
12035                "  Y = 0,\n"
12036                "  Z = 1\n"
12037                "  };\n",
12038                WhitesmithsBraceStyle);
12039 
12040   verifyFormat("@interface BSApplicationController ()\n"
12041                "  {\n"
12042                "@private\n"
12043                "  id _extraIvar;\n"
12044                "  }\n"
12045                "@end\n",
12046                WhitesmithsBraceStyle);
12047 
12048   verifyFormat("#ifdef _DEBUG\n"
12049                "int foo(int i = 0)\n"
12050                "#else\n"
12051                "int foo(int i = 5)\n"
12052                "#endif\n"
12053                "  {\n"
12054                "  return i;\n"
12055                "  }",
12056                WhitesmithsBraceStyle);
12057 
12058   verifyFormat("void foo() {}\n"
12059                "void bar()\n"
12060                "#ifdef _DEBUG\n"
12061                "  {\n"
12062                "  foo();\n"
12063                "  }\n"
12064                "#else\n"
12065                "  {\n"
12066                "  }\n"
12067                "#endif",
12068                WhitesmithsBraceStyle);
12069 
12070   verifyFormat("void foobar()\n"
12071                "  {\n"
12072                "  int i = 5;\n"
12073                "  }\n"
12074                "#ifdef _DEBUG\n"
12075                "void bar()\n"
12076                "  {\n"
12077                "  }\n"
12078                "#else\n"
12079                "void bar()\n"
12080                "  {\n"
12081                "  foobar();\n"
12082                "  }\n"
12083                "#endif",
12084                WhitesmithsBraceStyle);
12085 
12086   // This shouldn't affect ObjC blocks..
12087   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
12088                "  // ...\n"
12089                "  int i;\n"
12090                "}];",
12091                WhitesmithsBraceStyle);
12092   verifyFormat("void (^block)(void) = ^{\n"
12093                "  // ...\n"
12094                "  int i;\n"
12095                "};",
12096                WhitesmithsBraceStyle);
12097   // .. or dict literals.
12098   verifyFormat("void f()\n"
12099                "  {\n"
12100                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
12101                "  }",
12102                WhitesmithsBraceStyle);
12103 
12104   verifyFormat("int f()\n"
12105                "  { // comment\n"
12106                "  return 42;\n"
12107                "  }",
12108                WhitesmithsBraceStyle);
12109 
12110   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
12111   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
12112       FormatStyle::SIS_Always;
12113   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
12114   verifyFormat("void f(bool b)\n"
12115                "  {\n"
12116                "  if (b)\n"
12117                "    {\n"
12118                "    return;\n"
12119                "    }\n"
12120                "  }\n",
12121                BreakBeforeBraceShortIfs);
12122   verifyFormat("void f(bool b)\n"
12123                "  {\n"
12124                "  if (b) return;\n"
12125                "  }\n",
12126                BreakBeforeBraceShortIfs);
12127   verifyFormat("void f(bool b)\n"
12128                "  {\n"
12129                "  while (b)\n"
12130                "    {\n"
12131                "    return;\n"
12132                "    }\n"
12133                "  }\n",
12134                BreakBeforeBraceShortIfs);
12135 }
12136 
TEST_F(FormatTest,GNUBraceBreaking)12137 TEST_F(FormatTest, GNUBraceBreaking) {
12138   FormatStyle GNUBraceStyle = getLLVMStyle();
12139   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
12140   verifyFormat("namespace a\n"
12141                "{\n"
12142                "class A\n"
12143                "{\n"
12144                "  void f()\n"
12145                "  {\n"
12146                "    int a;\n"
12147                "    {\n"
12148                "      int b;\n"
12149                "    }\n"
12150                "    if (true)\n"
12151                "      {\n"
12152                "        a();\n"
12153                "        b();\n"
12154                "      }\n"
12155                "  }\n"
12156                "  void g() { return; }\n"
12157                "}\n"
12158                "} // namespace a",
12159                GNUBraceStyle);
12160 
12161   verifyFormat("void f()\n"
12162                "{\n"
12163                "  if (true)\n"
12164                "    {\n"
12165                "      a();\n"
12166                "    }\n"
12167                "  else if (false)\n"
12168                "    {\n"
12169                "      b();\n"
12170                "    }\n"
12171                "  else\n"
12172                "    {\n"
12173                "      c();\n"
12174                "    }\n"
12175                "}\n",
12176                GNUBraceStyle);
12177 
12178   verifyFormat("void f()\n"
12179                "{\n"
12180                "  for (int i = 0; i < 10; ++i)\n"
12181                "    {\n"
12182                "      a();\n"
12183                "    }\n"
12184                "  while (false)\n"
12185                "    {\n"
12186                "      b();\n"
12187                "    }\n"
12188                "  do\n"
12189                "    {\n"
12190                "      c();\n"
12191                "    }\n"
12192                "  while (false);\n"
12193                "}\n",
12194                GNUBraceStyle);
12195 
12196   verifyFormat("void f(int a)\n"
12197                "{\n"
12198                "  switch (a)\n"
12199                "    {\n"
12200                "    case 0:\n"
12201                "      break;\n"
12202                "    case 1:\n"
12203                "      {\n"
12204                "        break;\n"
12205                "      }\n"
12206                "    case 2:\n"
12207                "      {\n"
12208                "      }\n"
12209                "      break;\n"
12210                "    default:\n"
12211                "      break;\n"
12212                "    }\n"
12213                "}\n",
12214                GNUBraceStyle);
12215 
12216   verifyFormat("enum X\n"
12217                "{\n"
12218                "  Y = 0,\n"
12219                "}\n",
12220                GNUBraceStyle);
12221 
12222   verifyFormat("@interface BSApplicationController ()\n"
12223                "{\n"
12224                "@private\n"
12225                "  id _extraIvar;\n"
12226                "}\n"
12227                "@end\n",
12228                GNUBraceStyle);
12229 
12230   verifyFormat("#ifdef _DEBUG\n"
12231                "int foo(int i = 0)\n"
12232                "#else\n"
12233                "int foo(int i = 5)\n"
12234                "#endif\n"
12235                "{\n"
12236                "  return i;\n"
12237                "}",
12238                GNUBraceStyle);
12239 
12240   verifyFormat("void foo() {}\n"
12241                "void bar()\n"
12242                "#ifdef _DEBUG\n"
12243                "{\n"
12244                "  foo();\n"
12245                "}\n"
12246                "#else\n"
12247                "{\n"
12248                "}\n"
12249                "#endif",
12250                GNUBraceStyle);
12251 
12252   verifyFormat("void foobar() { int i = 5; }\n"
12253                "#ifdef _DEBUG\n"
12254                "void bar() {}\n"
12255                "#else\n"
12256                "void bar() { foobar(); }\n"
12257                "#endif",
12258                GNUBraceStyle);
12259 }
12260 
TEST_F(FormatTest,WebKitBraceBreaking)12261 TEST_F(FormatTest, WebKitBraceBreaking) {
12262   FormatStyle WebKitBraceStyle = getLLVMStyle();
12263   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
12264   WebKitBraceStyle.FixNamespaceComments = false;
12265   verifyFormat("namespace a {\n"
12266                "class A {\n"
12267                "  void f()\n"
12268                "  {\n"
12269                "    if (true) {\n"
12270                "      a();\n"
12271                "      b();\n"
12272                "    }\n"
12273                "  }\n"
12274                "  void g() { return; }\n"
12275                "};\n"
12276                "enum E {\n"
12277                "  A,\n"
12278                "  // foo\n"
12279                "  B,\n"
12280                "  C\n"
12281                "};\n"
12282                "struct B {\n"
12283                "  int x;\n"
12284                "};\n"
12285                "}\n",
12286                WebKitBraceStyle);
12287   verifyFormat("struct S {\n"
12288                "  int Type;\n"
12289                "  union {\n"
12290                "    int x;\n"
12291                "    double y;\n"
12292                "  } Value;\n"
12293                "  class C {\n"
12294                "    MyFavoriteType Value;\n"
12295                "  } Class;\n"
12296                "};\n",
12297                WebKitBraceStyle);
12298 }
12299 
TEST_F(FormatTest,CatchExceptionReferenceBinding)12300 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
12301   verifyFormat("void f() {\n"
12302                "  try {\n"
12303                "  } catch (const Exception &e) {\n"
12304                "  }\n"
12305                "}\n",
12306                getLLVMStyle());
12307 }
12308 
TEST_F(FormatTest,UnderstandsPragmas)12309 TEST_F(FormatTest, UnderstandsPragmas) {
12310   verifyFormat("#pragma omp reduction(| : var)");
12311   verifyFormat("#pragma omp reduction(+ : var)");
12312 
12313   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
12314             "(including parentheses).",
12315             format("#pragma    mark   Any non-hyphenated or hyphenated string "
12316                    "(including parentheses)."));
12317 }
12318 
TEST_F(FormatTest,UnderstandPragmaOption)12319 TEST_F(FormatTest, UnderstandPragmaOption) {
12320   verifyFormat("#pragma option -C -A");
12321 
12322   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
12323 }
12324 
TEST_F(FormatTest,OptimizeBreakPenaltyVsExcess)12325 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
12326   FormatStyle Style = getLLVMStyle();
12327   Style.ColumnLimit = 20;
12328 
12329   // See PR41213
12330   EXPECT_EQ("/*\n"
12331             " *\t9012345\n"
12332             " * /8901\n"
12333             " */",
12334             format("/*\n"
12335                    " *\t9012345 /8901\n"
12336                    " */",
12337                    Style));
12338   EXPECT_EQ("/*\n"
12339             " *345678\n"
12340             " *\t/8901\n"
12341             " */",
12342             format("/*\n"
12343                    " *345678\t/8901\n"
12344                    " */",
12345                    Style));
12346 
12347   verifyFormat("int a; // the\n"
12348                "       // comment",
12349                Style);
12350   EXPECT_EQ("int a; /* first line\n"
12351             "        * second\n"
12352             "        * line third\n"
12353             "        * line\n"
12354             "        */",
12355             format("int a; /* first line\n"
12356                    "        * second\n"
12357                    "        * line third\n"
12358                    "        * line\n"
12359                    "        */",
12360                    Style));
12361   EXPECT_EQ("int a; // first line\n"
12362             "       // second\n"
12363             "       // line third\n"
12364             "       // line",
12365             format("int a; // first line\n"
12366                    "       // second line\n"
12367                    "       // third line",
12368                    Style));
12369 
12370   Style.PenaltyExcessCharacter = 90;
12371   verifyFormat("int a; // the comment", Style);
12372   EXPECT_EQ("int a; // the comment\n"
12373             "       // aaa",
12374             format("int a; // the comment aaa", Style));
12375   EXPECT_EQ("int a; /* first line\n"
12376             "        * second line\n"
12377             "        * third line\n"
12378             "        */",
12379             format("int a; /* first line\n"
12380                    "        * second line\n"
12381                    "        * third line\n"
12382                    "        */",
12383                    Style));
12384   EXPECT_EQ("int a; // first line\n"
12385             "       // second line\n"
12386             "       // third line",
12387             format("int a; // first line\n"
12388                    "       // second line\n"
12389                    "       // third line",
12390                    Style));
12391   // FIXME: Investigate why this is not getting the same layout as the test
12392   // above.
12393   EXPECT_EQ("int a; /* first line\n"
12394             "        * second line\n"
12395             "        * third line\n"
12396             "        */",
12397             format("int a; /* first line second line third line"
12398                    "\n*/",
12399                    Style));
12400 
12401   EXPECT_EQ("// foo bar baz bazfoo\n"
12402             "// foo bar foo bar\n",
12403             format("// foo bar baz bazfoo\n"
12404                    "// foo bar foo           bar\n",
12405                    Style));
12406   EXPECT_EQ("// foo bar baz bazfoo\n"
12407             "// foo bar foo bar\n",
12408             format("// foo bar baz      bazfoo\n"
12409                    "// foo            bar foo bar\n",
12410                    Style));
12411 
12412   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
12413   // next one.
12414   EXPECT_EQ("// foo bar baz bazfoo\n"
12415             "// bar foo bar\n",
12416             format("// foo bar baz      bazfoo bar\n"
12417                    "// foo            bar\n",
12418                    Style));
12419 
12420   EXPECT_EQ("// foo bar baz bazfoo\n"
12421             "// foo bar baz bazfoo\n"
12422             "// bar foo bar\n",
12423             format("// foo bar baz      bazfoo\n"
12424                    "// foo bar baz      bazfoo bar\n"
12425                    "// foo bar\n",
12426                    Style));
12427 
12428   EXPECT_EQ("// foo bar baz bazfoo\n"
12429             "// foo bar baz bazfoo\n"
12430             "// bar foo bar\n",
12431             format("// foo bar baz      bazfoo\n"
12432                    "// foo bar baz      bazfoo bar\n"
12433                    "// foo           bar\n",
12434                    Style));
12435 
12436   // Make sure we do not keep protruding characters if strict mode reflow is
12437   // cheaper than keeping protruding characters.
12438   Style.ColumnLimit = 21;
12439   EXPECT_EQ(
12440       "// foo foo foo foo\n"
12441       "// foo foo foo foo\n"
12442       "// foo foo foo foo\n",
12443       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
12444 
12445   EXPECT_EQ("int a = /* long block\n"
12446             "           comment */\n"
12447             "    42;",
12448             format("int a = /* long block comment */ 42;", Style));
12449 }
12450 
12451 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
12452   for (size_t i = 1; i < Styles.size(); ++i)                                   \
12453   EXPECT_EQ(Styles[0], Styles[i])                                              \
12454       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
12455 
TEST_F(FormatTest,GetsPredefinedStyleByName)12456 TEST_F(FormatTest, GetsPredefinedStyleByName) {
12457   SmallVector<FormatStyle, 3> Styles;
12458   Styles.resize(3);
12459 
12460   Styles[0] = getLLVMStyle();
12461   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
12462   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
12463   EXPECT_ALL_STYLES_EQUAL(Styles);
12464 
12465   Styles[0] = getGoogleStyle();
12466   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
12467   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
12468   EXPECT_ALL_STYLES_EQUAL(Styles);
12469 
12470   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
12471   EXPECT_TRUE(
12472       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
12473   EXPECT_TRUE(
12474       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
12475   EXPECT_ALL_STYLES_EQUAL(Styles);
12476 
12477   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
12478   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
12479   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
12480   EXPECT_ALL_STYLES_EQUAL(Styles);
12481 
12482   Styles[0] = getMozillaStyle();
12483   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
12484   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
12485   EXPECT_ALL_STYLES_EQUAL(Styles);
12486 
12487   Styles[0] = getWebKitStyle();
12488   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
12489   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
12490   EXPECT_ALL_STYLES_EQUAL(Styles);
12491 
12492   Styles[0] = getGNUStyle();
12493   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
12494   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
12495   EXPECT_ALL_STYLES_EQUAL(Styles);
12496 
12497   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
12498 }
12499 
TEST_F(FormatTest,GetsCorrectBasedOnStyle)12500 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
12501   SmallVector<FormatStyle, 8> Styles;
12502   Styles.resize(2);
12503 
12504   Styles[0] = getGoogleStyle();
12505   Styles[1] = getLLVMStyle();
12506   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
12507   EXPECT_ALL_STYLES_EQUAL(Styles);
12508 
12509   Styles.resize(5);
12510   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
12511   Styles[1] = getLLVMStyle();
12512   Styles[1].Language = FormatStyle::LK_JavaScript;
12513   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
12514 
12515   Styles[2] = getLLVMStyle();
12516   Styles[2].Language = FormatStyle::LK_JavaScript;
12517   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
12518                                   "BasedOnStyle: Google",
12519                                   &Styles[2])
12520                    .value());
12521 
12522   Styles[3] = getLLVMStyle();
12523   Styles[3].Language = FormatStyle::LK_JavaScript;
12524   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
12525                                   "Language: JavaScript",
12526                                   &Styles[3])
12527                    .value());
12528 
12529   Styles[4] = getLLVMStyle();
12530   Styles[4].Language = FormatStyle::LK_JavaScript;
12531   EXPECT_EQ(0, parseConfiguration("---\n"
12532                                   "BasedOnStyle: LLVM\n"
12533                                   "IndentWidth: 123\n"
12534                                   "---\n"
12535                                   "BasedOnStyle: Google\n"
12536                                   "Language: JavaScript",
12537                                   &Styles[4])
12538                    .value());
12539   EXPECT_ALL_STYLES_EQUAL(Styles);
12540 }
12541 
12542 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
12543   Style.FIELD = false;                                                         \
12544   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
12545   EXPECT_TRUE(Style.FIELD);                                                    \
12546   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
12547   EXPECT_FALSE(Style.FIELD);
12548 
12549 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
12550 
12551 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
12552   Style.STRUCT.FIELD = false;                                                  \
12553   EXPECT_EQ(0,                                                                 \
12554             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
12555                 .value());                                                     \
12556   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
12557   EXPECT_EQ(0,                                                                 \
12558             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
12559                 .value());                                                     \
12560   EXPECT_FALSE(Style.STRUCT.FIELD);
12561 
12562 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
12563   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
12564 
12565 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
12566   EXPECT_NE(VALUE, Style.FIELD);                                               \
12567   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
12568   EXPECT_EQ(VALUE, Style.FIELD)
12569 
TEST_F(FormatTest,ParsesConfigurationBools)12570 TEST_F(FormatTest, ParsesConfigurationBools) {
12571   FormatStyle Style = {};
12572   Style.Language = FormatStyle::LK_Cpp;
12573   CHECK_PARSE_BOOL(AlignOperands);
12574   CHECK_PARSE_BOOL(AlignTrailingComments);
12575   CHECK_PARSE_BOOL(AlignConsecutiveAssignments);
12576   CHECK_PARSE_BOOL(AlignConsecutiveDeclarations);
12577   CHECK_PARSE_BOOL(AlignConsecutiveMacros);
12578   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
12579   CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine);
12580   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
12581   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
12582   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
12583   CHECK_PARSE_BOOL(BinPackArguments);
12584   CHECK_PARSE_BOOL(BinPackParameters);
12585   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
12586   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
12587   CHECK_PARSE_BOOL(BreakStringLiterals);
12588   CHECK_PARSE_BOOL(CompactNamespaces);
12589   CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
12590   CHECK_PARSE_BOOL(DeriveLineEnding);
12591   CHECK_PARSE_BOOL(DerivePointerAlignment);
12592   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
12593   CHECK_PARSE_BOOL(DisableFormat);
12594   CHECK_PARSE_BOOL(IndentCaseLabels);
12595   CHECK_PARSE_BOOL(IndentGotoLabels);
12596   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
12597   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
12598   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
12599   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
12600   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
12601   CHECK_PARSE_BOOL(ReflowComments);
12602   CHECK_PARSE_BOOL(SortIncludes);
12603   CHECK_PARSE_BOOL(SortUsingDeclarations);
12604   CHECK_PARSE_BOOL(SpacesInParentheses);
12605   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
12606   CHECK_PARSE_BOOL(SpacesInAngles);
12607   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
12608   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
12609   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
12610   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
12611   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
12612   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
12613   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
12614   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
12615   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
12616   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
12617   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
12618   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
12619   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
12620   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
12621   CHECK_PARSE_BOOL(UseCRLF);
12622 
12623   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
12624   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
12625   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
12626   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
12627   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
12628   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
12629   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
12630   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
12631   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
12632   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
12633   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
12634   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
12635   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
12636   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
12637   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
12638 }
12639 
12640 #undef CHECK_PARSE_BOOL
12641 
TEST_F(FormatTest,ParsesConfiguration)12642 TEST_F(FormatTest, ParsesConfiguration) {
12643   FormatStyle Style = {};
12644   Style.Language = FormatStyle::LK_Cpp;
12645   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
12646   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
12647               ConstructorInitializerIndentWidth, 1234u);
12648   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
12649   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
12650   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
12651   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
12652   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
12653               PenaltyBreakBeforeFirstCallParameter, 1234u);
12654   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
12655               PenaltyBreakTemplateDeclaration, 1234u);
12656   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
12657   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
12658               PenaltyReturnTypeOnItsOwnLine, 1234u);
12659   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
12660               SpacesBeforeTrailingComments, 1234u);
12661   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
12662   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
12663   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
12664 
12665   Style.PointerAlignment = FormatStyle::PAS_Middle;
12666   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
12667               FormatStyle::PAS_Left);
12668   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
12669               FormatStyle::PAS_Right);
12670   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
12671               FormatStyle::PAS_Middle);
12672   // For backward compatibility:
12673   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
12674               FormatStyle::PAS_Left);
12675   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
12676               FormatStyle::PAS_Right);
12677   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
12678               FormatStyle::PAS_Middle);
12679 
12680   Style.Standard = FormatStyle::LS_Auto;
12681   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
12682   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
12683   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
12684   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
12685   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
12686   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
12687   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
12688   // Legacy aliases:
12689   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
12690   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
12691   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
12692   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
12693 
12694   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
12695   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
12696               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
12697   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
12698               FormatStyle::BOS_None);
12699   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
12700               FormatStyle::BOS_All);
12701   // For backward compatibility:
12702   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
12703               FormatStyle::BOS_None);
12704   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
12705               FormatStyle::BOS_All);
12706 
12707   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
12708   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
12709               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
12710   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
12711               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
12712   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
12713               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
12714   // For backward compatibility:
12715   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
12716               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
12717 
12718   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
12719   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
12720               FormatStyle::BILS_BeforeComma);
12721   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
12722               FormatStyle::BILS_AfterColon);
12723   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
12724               FormatStyle::BILS_BeforeColon);
12725   // For backward compatibility:
12726   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
12727               FormatStyle::BILS_BeforeComma);
12728 
12729   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12730   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
12731               FormatStyle::BAS_Align);
12732   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
12733               FormatStyle::BAS_DontAlign);
12734   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
12735               FormatStyle::BAS_AlwaysBreak);
12736   // For backward compatibility:
12737   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
12738               FormatStyle::BAS_DontAlign);
12739   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
12740               FormatStyle::BAS_Align);
12741 
12742   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
12743   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
12744               FormatStyle::ENAS_DontAlign);
12745   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
12746               FormatStyle::ENAS_Left);
12747   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
12748               FormatStyle::ENAS_Right);
12749   // For backward compatibility:
12750   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
12751               FormatStyle::ENAS_Left);
12752   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
12753               FormatStyle::ENAS_Right);
12754 
12755   Style.UseTab = FormatStyle::UT_ForIndentation;
12756   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
12757   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
12758   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
12759   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
12760               FormatStyle::UT_ForContinuationAndIndentation);
12761   // For backward compatibility:
12762   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
12763   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
12764 
12765   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
12766   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
12767               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
12768   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
12769               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
12770   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
12771               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
12772   // For backward compatibility:
12773   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
12774               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
12775   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
12776               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
12777 
12778   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12779   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
12780               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
12781   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
12782               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
12783   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
12784               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
12785   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
12786               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
12787   // For backward compatibility:
12788   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
12789               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
12790   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
12791               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
12792 
12793   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
12794   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
12795               FormatStyle::SBPO_Never);
12796   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
12797               FormatStyle::SBPO_Always);
12798   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
12799               FormatStyle::SBPO_ControlStatements);
12800   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
12801               FormatStyle::SBPO_NonEmptyParentheses);
12802   // For backward compatibility:
12803   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
12804               FormatStyle::SBPO_Never);
12805   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
12806               FormatStyle::SBPO_ControlStatements);
12807 
12808   Style.ColumnLimit = 123;
12809   FormatStyle BaseStyle = getLLVMStyle();
12810   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
12811   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
12812 
12813   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
12814   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
12815               FormatStyle::BS_Attach);
12816   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
12817               FormatStyle::BS_Linux);
12818   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
12819               FormatStyle::BS_Mozilla);
12820   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
12821               FormatStyle::BS_Stroustrup);
12822   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
12823               FormatStyle::BS_Allman);
12824   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
12825               FormatStyle::BS_Whitesmiths);
12826   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
12827   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
12828               FormatStyle::BS_WebKit);
12829   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
12830               FormatStyle::BS_Custom);
12831 
12832   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
12833   CHECK_PARSE("BraceWrapping:\n"
12834               "  AfterControlStatement: MultiLine",
12835               BraceWrapping.AfterControlStatement,
12836               FormatStyle::BWACS_MultiLine);
12837   CHECK_PARSE("BraceWrapping:\n"
12838               "  AfterControlStatement: Always",
12839               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
12840   CHECK_PARSE("BraceWrapping:\n"
12841               "  AfterControlStatement: Never",
12842               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
12843   // For backward compatibility:
12844   CHECK_PARSE("BraceWrapping:\n"
12845               "  AfterControlStatement: true",
12846               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
12847   CHECK_PARSE("BraceWrapping:\n"
12848               "  AfterControlStatement: false",
12849               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
12850 
12851   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
12852   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
12853               FormatStyle::RTBS_None);
12854   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
12855               FormatStyle::RTBS_All);
12856   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
12857               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
12858   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
12859               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
12860   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
12861               AlwaysBreakAfterReturnType,
12862               FormatStyle::RTBS_TopLevelDefinitions);
12863 
12864   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
12865   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
12866               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
12867   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
12868               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
12869   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
12870               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
12871   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
12872               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
12873   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
12874               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
12875 
12876   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
12877   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
12878               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
12879   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
12880               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
12881   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
12882               AlwaysBreakAfterDefinitionReturnType,
12883               FormatStyle::DRTBS_TopLevel);
12884 
12885   Style.NamespaceIndentation = FormatStyle::NI_All;
12886   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
12887               FormatStyle::NI_None);
12888   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
12889               FormatStyle::NI_Inner);
12890   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
12891               FormatStyle::NI_All);
12892 
12893   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
12894   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
12895               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
12896   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
12897               AllowShortIfStatementsOnASingleLine,
12898               FormatStyle::SIS_WithoutElse);
12899   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
12900               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Always);
12901   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
12902               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
12903   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
12904               AllowShortIfStatementsOnASingleLine,
12905               FormatStyle::SIS_WithoutElse);
12906 
12907   // FIXME: This is required because parsing a configuration simply overwrites
12908   // the first N elements of the list instead of resetting it.
12909   Style.ForEachMacros.clear();
12910   std::vector<std::string> BoostForeach;
12911   BoostForeach.push_back("BOOST_FOREACH");
12912   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
12913   std::vector<std::string> BoostAndQForeach;
12914   BoostAndQForeach.push_back("BOOST_FOREACH");
12915   BoostAndQForeach.push_back("Q_FOREACH");
12916   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
12917               BoostAndQForeach);
12918 
12919   Style.StatementMacros.clear();
12920   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
12921               std::vector<std::string>{"QUNUSED"});
12922   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
12923               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
12924 
12925   Style.NamespaceMacros.clear();
12926   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
12927               std::vector<std::string>{"TESTSUITE"});
12928   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
12929               std::vector<std::string>({"TESTSUITE", "SUITE"}));
12930 
12931   Style.IncludeStyle.IncludeCategories.clear();
12932   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
12933       {"abc/.*", 2, 0}, {".*", 1, 0}};
12934   CHECK_PARSE("IncludeCategories:\n"
12935               "  - Regex: abc/.*\n"
12936               "    Priority: 2\n"
12937               "  - Regex: .*\n"
12938               "    Priority: 1",
12939               IncludeStyle.IncludeCategories, ExpectedCategories);
12940   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
12941               "abc$");
12942   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
12943               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
12944 
12945   Style.RawStringFormats.clear();
12946   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
12947       {
12948           FormatStyle::LK_TextProto,
12949           {"pb", "proto"},
12950           {"PARSE_TEXT_PROTO"},
12951           /*CanonicalDelimiter=*/"",
12952           "llvm",
12953       },
12954       {
12955           FormatStyle::LK_Cpp,
12956           {"cc", "cpp"},
12957           {"C_CODEBLOCK", "CPPEVAL"},
12958           /*CanonicalDelimiter=*/"cc",
12959           /*BasedOnStyle=*/"",
12960       },
12961   };
12962 
12963   CHECK_PARSE("RawStringFormats:\n"
12964               "  - Language: TextProto\n"
12965               "    Delimiters:\n"
12966               "      - 'pb'\n"
12967               "      - 'proto'\n"
12968               "    EnclosingFunctions:\n"
12969               "      - 'PARSE_TEXT_PROTO'\n"
12970               "    BasedOnStyle: llvm\n"
12971               "  - Language: Cpp\n"
12972               "    Delimiters:\n"
12973               "      - 'cc'\n"
12974               "      - 'cpp'\n"
12975               "    EnclosingFunctions:\n"
12976               "      - 'C_CODEBLOCK'\n"
12977               "      - 'CPPEVAL'\n"
12978               "    CanonicalDelimiter: 'cc'",
12979               RawStringFormats, ExpectedRawStringFormats);
12980 }
12981 
TEST_F(FormatTest,ParsesConfigurationWithLanguages)12982 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
12983   FormatStyle Style = {};
12984   Style.Language = FormatStyle::LK_Cpp;
12985   CHECK_PARSE("Language: Cpp\n"
12986               "IndentWidth: 12",
12987               IndentWidth, 12u);
12988   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
12989                                "IndentWidth: 34",
12990                                &Style),
12991             ParseError::Unsuitable);
12992   EXPECT_EQ(12u, Style.IndentWidth);
12993   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
12994   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
12995 
12996   Style.Language = FormatStyle::LK_JavaScript;
12997   CHECK_PARSE("Language: JavaScript\n"
12998               "IndentWidth: 12",
12999               IndentWidth, 12u);
13000   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
13001   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
13002                                "IndentWidth: 34",
13003                                &Style),
13004             ParseError::Unsuitable);
13005   EXPECT_EQ(23u, Style.IndentWidth);
13006   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
13007   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
13008 
13009   CHECK_PARSE("BasedOnStyle: LLVM\n"
13010               "IndentWidth: 67",
13011               IndentWidth, 67u);
13012 
13013   CHECK_PARSE("---\n"
13014               "Language: JavaScript\n"
13015               "IndentWidth: 12\n"
13016               "---\n"
13017               "Language: Cpp\n"
13018               "IndentWidth: 34\n"
13019               "...\n",
13020               IndentWidth, 12u);
13021 
13022   Style.Language = FormatStyle::LK_Cpp;
13023   CHECK_PARSE("---\n"
13024               "Language: JavaScript\n"
13025               "IndentWidth: 12\n"
13026               "---\n"
13027               "Language: Cpp\n"
13028               "IndentWidth: 34\n"
13029               "...\n",
13030               IndentWidth, 34u);
13031   CHECK_PARSE("---\n"
13032               "IndentWidth: 78\n"
13033               "---\n"
13034               "Language: JavaScript\n"
13035               "IndentWidth: 56\n"
13036               "...\n",
13037               IndentWidth, 78u);
13038 
13039   Style.ColumnLimit = 123;
13040   Style.IndentWidth = 234;
13041   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
13042   Style.TabWidth = 345;
13043   EXPECT_FALSE(parseConfiguration("---\n"
13044                                   "IndentWidth: 456\n"
13045                                   "BreakBeforeBraces: Allman\n"
13046                                   "---\n"
13047                                   "Language: JavaScript\n"
13048                                   "IndentWidth: 111\n"
13049                                   "TabWidth: 111\n"
13050                                   "---\n"
13051                                   "Language: Cpp\n"
13052                                   "BreakBeforeBraces: Stroustrup\n"
13053                                   "TabWidth: 789\n"
13054                                   "...\n",
13055                                   &Style));
13056   EXPECT_EQ(123u, Style.ColumnLimit);
13057   EXPECT_EQ(456u, Style.IndentWidth);
13058   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
13059   EXPECT_EQ(789u, Style.TabWidth);
13060 
13061   EXPECT_EQ(parseConfiguration("---\n"
13062                                "Language: JavaScript\n"
13063                                "IndentWidth: 56\n"
13064                                "---\n"
13065                                "IndentWidth: 78\n"
13066                                "...\n",
13067                                &Style),
13068             ParseError::Error);
13069   EXPECT_EQ(parseConfiguration("---\n"
13070                                "Language: JavaScript\n"
13071                                "IndentWidth: 56\n"
13072                                "---\n"
13073                                "Language: JavaScript\n"
13074                                "IndentWidth: 78\n"
13075                                "...\n",
13076                                &Style),
13077             ParseError::Error);
13078 
13079   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
13080 }
13081 
13082 #undef CHECK_PARSE
13083 
TEST_F(FormatTest,UsesLanguageForBasedOnStyle)13084 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
13085   FormatStyle Style = {};
13086   Style.Language = FormatStyle::LK_JavaScript;
13087   Style.BreakBeforeTernaryOperators = true;
13088   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
13089   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
13090 
13091   Style.BreakBeforeTernaryOperators = true;
13092   EXPECT_EQ(0, parseConfiguration("---\n"
13093                                   "BasedOnStyle: Google\n"
13094                                   "---\n"
13095                                   "Language: JavaScript\n"
13096                                   "IndentWidth: 76\n"
13097                                   "...\n",
13098                                   &Style)
13099                    .value());
13100   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
13101   EXPECT_EQ(76u, Style.IndentWidth);
13102   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
13103 }
13104 
TEST_F(FormatTest,ConfigurationRoundTripTest)13105 TEST_F(FormatTest, ConfigurationRoundTripTest) {
13106   FormatStyle Style = getLLVMStyle();
13107   std::string YAML = configurationAsText(Style);
13108   FormatStyle ParsedStyle = {};
13109   ParsedStyle.Language = FormatStyle::LK_Cpp;
13110   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
13111   EXPECT_EQ(Style, ParsedStyle);
13112 }
13113 
TEST_F(FormatTest,WorksFor8bitEncodings)13114 TEST_F(FormatTest, WorksFor8bitEncodings) {
13115   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
13116             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
13117             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
13118             "\"\xef\xee\xf0\xf3...\"",
13119             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
13120                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
13121                    "\xef\xee\xf0\xf3...\"",
13122                    getLLVMStyleWithColumns(12)));
13123 }
13124 
TEST_F(FormatTest,HandlesUTF8BOM)13125 TEST_F(FormatTest, HandlesUTF8BOM) {
13126   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
13127   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
13128             format("\xef\xbb\xbf#include <iostream>"));
13129   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
13130             format("\xef\xbb\xbf\n#include <iostream>"));
13131 }
13132 
13133 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
13134 #if !defined(_MSC_VER)
13135 
TEST_F(FormatTest,CountsUTF8CharactersProperly)13136 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
13137   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
13138                getLLVMStyleWithColumns(35));
13139   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
13140                getLLVMStyleWithColumns(31));
13141   verifyFormat("// Однажды в студёную зимнюю пору...",
13142                getLLVMStyleWithColumns(36));
13143   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
13144   verifyFormat("/* Однажды в студёную зимнюю пору... */",
13145                getLLVMStyleWithColumns(39));
13146   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
13147                getLLVMStyleWithColumns(35));
13148 }
13149 
TEST_F(FormatTest,SplitsUTF8Strings)13150 TEST_F(FormatTest, SplitsUTF8Strings) {
13151   // Non-printable characters' width is currently considered to be the length in
13152   // bytes in UTF8. The characters can be displayed in very different manner
13153   // (zero-width, single width with a substitution glyph, expanded to their code
13154   // (e.g. "<8d>"), so there's no single correct way to handle them.
13155   EXPECT_EQ("\"aaaaÄ\"\n"
13156             "\"\xc2\x8d\";",
13157             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
13158   EXPECT_EQ("\"aaaaaaaÄ\"\n"
13159             "\"\xc2\x8d\";",
13160             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
13161   EXPECT_EQ("\"Однажды, в \"\n"
13162             "\"студёную \"\n"
13163             "\"зимнюю \"\n"
13164             "\"пору,\"",
13165             format("\"Однажды, в студёную зимнюю пору,\"",
13166                    getLLVMStyleWithColumns(13)));
13167   EXPECT_EQ(
13168       "\"一 二 三 \"\n"
13169       "\"四 五六 \"\n"
13170       "\"七 八 九 \"\n"
13171       "\"十\"",
13172       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
13173   EXPECT_EQ("\"一\t\"\n"
13174             "\"二 \t\"\n"
13175             "\"三 四 \"\n"
13176             "\"五\t\"\n"
13177             "\"六 \t\"\n"
13178             "\"七 \"\n"
13179             "\"八九十\tqq\"",
13180             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
13181                    getLLVMStyleWithColumns(11)));
13182 
13183   // UTF8 character in an escape sequence.
13184   EXPECT_EQ("\"aaaaaa\"\n"
13185             "\"\\\xC2\x8D\"",
13186             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
13187 }
13188 
TEST_F(FormatTest,HandlesDoubleWidthCharsInMultiLineStrings)13189 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
13190   EXPECT_EQ("const char *sssss =\n"
13191             "    \"一二三四五六七八\\\n"
13192             " 九 十\";",
13193             format("const char *sssss = \"一二三四五六七八\\\n"
13194                    " 九 十\";",
13195                    getLLVMStyleWithColumns(30)));
13196 }
13197 
TEST_F(FormatTest,SplitsUTF8LineComments)13198 TEST_F(FormatTest, SplitsUTF8LineComments) {
13199   EXPECT_EQ("// aaaaÄ\xc2\x8d",
13200             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
13201   EXPECT_EQ("// Я из лесу\n"
13202             "// вышел; был\n"
13203             "// сильный\n"
13204             "// мороз.",
13205             format("// Я из лесу вышел; был сильный мороз.",
13206                    getLLVMStyleWithColumns(13)));
13207   EXPECT_EQ("// 一二三\n"
13208             "// 四五六七\n"
13209             "// 八  九\n"
13210             "// 十",
13211             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
13212 }
13213 
TEST_F(FormatTest,SplitsUTF8BlockComments)13214 TEST_F(FormatTest, SplitsUTF8BlockComments) {
13215   EXPECT_EQ("/* Гляжу,\n"
13216             " * поднимается\n"
13217             " * медленно в\n"
13218             " * гору\n"
13219             " * Лошадка,\n"
13220             " * везущая\n"
13221             " * хворосту\n"
13222             " * воз. */",
13223             format("/* Гляжу, поднимается медленно в гору\n"
13224                    " * Лошадка, везущая хворосту воз. */",
13225                    getLLVMStyleWithColumns(13)));
13226   EXPECT_EQ(
13227       "/* 一二三\n"
13228       " * 四五六七\n"
13229       " * 八  九\n"
13230       " * 十  */",
13231       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
13232   EXPECT_EQ("/* �������� ��������\n"
13233             " * ��������\n"
13234             " * ������-�� */",
13235             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
13236 }
13237 
13238 #endif // _MSC_VER
13239 
TEST_F(FormatTest,ConstructorInitializerIndentWidth)13240 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
13241   FormatStyle Style = getLLVMStyle();
13242 
13243   Style.ConstructorInitializerIndentWidth = 4;
13244   verifyFormat(
13245       "SomeClass::Constructor()\n"
13246       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
13247       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
13248       Style);
13249 
13250   Style.ConstructorInitializerIndentWidth = 2;
13251   verifyFormat(
13252       "SomeClass::Constructor()\n"
13253       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
13254       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
13255       Style);
13256 
13257   Style.ConstructorInitializerIndentWidth = 0;
13258   verifyFormat(
13259       "SomeClass::Constructor()\n"
13260       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
13261       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
13262       Style);
13263   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13264   verifyFormat(
13265       "SomeLongTemplateVariableName<\n"
13266       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
13267       Style);
13268   verifyFormat("bool smaller = 1 < "
13269                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
13270                "                       "
13271                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
13272                Style);
13273 
13274   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
13275   verifyFormat("SomeClass::Constructor() :\n"
13276                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
13277                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
13278                Style);
13279 }
13280 
TEST_F(FormatTest,BreakConstructorInitializersBeforeComma)13281 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
13282   FormatStyle Style = getLLVMStyle();
13283   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
13284   Style.ConstructorInitializerIndentWidth = 4;
13285   verifyFormat("SomeClass::Constructor()\n"
13286                "    : a(a)\n"
13287                "    , b(b)\n"
13288                "    , c(c) {}",
13289                Style);
13290   verifyFormat("SomeClass::Constructor()\n"
13291                "    : a(a) {}",
13292                Style);
13293 
13294   Style.ColumnLimit = 0;
13295   verifyFormat("SomeClass::Constructor()\n"
13296                "    : a(a) {}",
13297                Style);
13298   verifyFormat("SomeClass::Constructor() noexcept\n"
13299                "    : a(a) {}",
13300                Style);
13301   verifyFormat("SomeClass::Constructor()\n"
13302                "    : a(a)\n"
13303                "    , b(b)\n"
13304                "    , c(c) {}",
13305                Style);
13306   verifyFormat("SomeClass::Constructor()\n"
13307                "    : a(a) {\n"
13308                "  foo();\n"
13309                "  bar();\n"
13310                "}",
13311                Style);
13312 
13313   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
13314   verifyFormat("SomeClass::Constructor()\n"
13315                "    : a(a)\n"
13316                "    , b(b)\n"
13317                "    , c(c) {\n}",
13318                Style);
13319   verifyFormat("SomeClass::Constructor()\n"
13320                "    : a(a) {\n}",
13321                Style);
13322 
13323   Style.ColumnLimit = 80;
13324   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
13325   Style.ConstructorInitializerIndentWidth = 2;
13326   verifyFormat("SomeClass::Constructor()\n"
13327                "  : a(a)\n"
13328                "  , b(b)\n"
13329                "  , c(c) {}",
13330                Style);
13331 
13332   Style.ConstructorInitializerIndentWidth = 0;
13333   verifyFormat("SomeClass::Constructor()\n"
13334                ": a(a)\n"
13335                ", b(b)\n"
13336                ", c(c) {}",
13337                Style);
13338 
13339   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
13340   Style.ConstructorInitializerIndentWidth = 4;
13341   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
13342   verifyFormat(
13343       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
13344       Style);
13345   verifyFormat(
13346       "SomeClass::Constructor()\n"
13347       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
13348       Style);
13349   Style.ConstructorInitializerIndentWidth = 4;
13350   Style.ColumnLimit = 60;
13351   verifyFormat("SomeClass::Constructor()\n"
13352                "    : aaaaaaaa(aaaaaaaa)\n"
13353                "    , aaaaaaaa(aaaaaaaa)\n"
13354                "    , aaaaaaaa(aaaaaaaa) {}",
13355                Style);
13356 }
13357 
TEST_F(FormatTest,Destructors)13358 TEST_F(FormatTest, Destructors) {
13359   verifyFormat("void F(int &i) { i.~int(); }");
13360   verifyFormat("void F(int &i) { i->~int(); }");
13361 }
13362 
TEST_F(FormatTest,FormatsWithWebKitStyle)13363 TEST_F(FormatTest, FormatsWithWebKitStyle) {
13364   FormatStyle Style = getWebKitStyle();
13365 
13366   // Don't indent in outer namespaces.
13367   verifyFormat("namespace outer {\n"
13368                "int i;\n"
13369                "namespace inner {\n"
13370                "    int i;\n"
13371                "} // namespace inner\n"
13372                "} // namespace outer\n"
13373                "namespace other_outer {\n"
13374                "int i;\n"
13375                "}",
13376                Style);
13377 
13378   // Don't indent case labels.
13379   verifyFormat("switch (variable) {\n"
13380                "case 1:\n"
13381                "case 2:\n"
13382                "    doSomething();\n"
13383                "    break;\n"
13384                "default:\n"
13385                "    ++variable;\n"
13386                "}",
13387                Style);
13388 
13389   // Wrap before binary operators.
13390   EXPECT_EQ("void f()\n"
13391             "{\n"
13392             "    if (aaaaaaaaaaaaaaaa\n"
13393             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
13394             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
13395             "        return;\n"
13396             "}",
13397             format("void f() {\n"
13398                    "if (aaaaaaaaaaaaaaaa\n"
13399                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
13400                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
13401                    "return;\n"
13402                    "}",
13403                    Style));
13404 
13405   // Allow functions on a single line.
13406   verifyFormat("void f() { return; }", Style);
13407 
13408   // Allow empty blocks on a single line and insert a space in empty blocks.
13409   EXPECT_EQ("void f() { }", format("void f() {}", Style));
13410   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
13411   // However, don't merge non-empty short loops.
13412   EXPECT_EQ("while (true) {\n"
13413             "    continue;\n"
13414             "}",
13415             format("while (true) { continue; }", Style));
13416 
13417   // Constructor initializers are formatted one per line with the "," on the
13418   // new line.
13419   verifyFormat("Constructor()\n"
13420                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
13421                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
13422                "          aaaaaaaaaaaaaa)\n"
13423                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
13424                "{\n"
13425                "}",
13426                Style);
13427   verifyFormat("SomeClass::Constructor()\n"
13428                "    : a(a)\n"
13429                "{\n"
13430                "}",
13431                Style);
13432   EXPECT_EQ("SomeClass::Constructor()\n"
13433             "    : a(a)\n"
13434             "{\n"
13435             "}",
13436             format("SomeClass::Constructor():a(a){}", Style));
13437   verifyFormat("SomeClass::Constructor()\n"
13438                "    : a(a)\n"
13439                "    , b(b)\n"
13440                "    , c(c)\n"
13441                "{\n"
13442                "}",
13443                Style);
13444   verifyFormat("SomeClass::Constructor()\n"
13445                "    : a(a)\n"
13446                "{\n"
13447                "    foo();\n"
13448                "    bar();\n"
13449                "}",
13450                Style);
13451 
13452   // Access specifiers should be aligned left.
13453   verifyFormat("class C {\n"
13454                "public:\n"
13455                "    int i;\n"
13456                "};",
13457                Style);
13458 
13459   // Do not align comments.
13460   verifyFormat("int a; // Do not\n"
13461                "double b; // align comments.",
13462                Style);
13463 
13464   // Do not align operands.
13465   EXPECT_EQ("ASSERT(aaaa\n"
13466             "    || bbbb);",
13467             format("ASSERT ( aaaa\n||bbbb);", Style));
13468 
13469   // Accept input's line breaks.
13470   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
13471             "    || bbbbbbbbbbbbbbb) {\n"
13472             "    i++;\n"
13473             "}",
13474             format("if (aaaaaaaaaaaaaaa\n"
13475                    "|| bbbbbbbbbbbbbbb) { i++; }",
13476                    Style));
13477   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
13478             "    i++;\n"
13479             "}",
13480             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
13481 
13482   // Don't automatically break all macro definitions (llvm.org/PR17842).
13483   verifyFormat("#define aNumber 10", Style);
13484   // However, generally keep the line breaks that the user authored.
13485   EXPECT_EQ("#define aNumber \\\n"
13486             "    10",
13487             format("#define aNumber \\\n"
13488                    " 10",
13489                    Style));
13490 
13491   // Keep empty and one-element array literals on a single line.
13492   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
13493             "                                  copyItems:YES];",
13494             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
13495                    "copyItems:YES];",
13496                    Style));
13497   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
13498             "                                  copyItems:YES];",
13499             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
13500                    "             copyItems:YES];",
13501                    Style));
13502   // FIXME: This does not seem right, there should be more indentation before
13503   // the array literal's entries. Nested blocks have the same problem.
13504   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
13505             "    @\"a\",\n"
13506             "    @\"a\"\n"
13507             "]\n"
13508             "                                  copyItems:YES];",
13509             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
13510                    "     @\"a\",\n"
13511                    "     @\"a\"\n"
13512                    "     ]\n"
13513                    "       copyItems:YES];",
13514                    Style));
13515   EXPECT_EQ(
13516       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
13517       "                                  copyItems:YES];",
13518       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
13519              "   copyItems:YES];",
13520              Style));
13521 
13522   verifyFormat("[self.a b:c c:d];", Style);
13523   EXPECT_EQ("[self.a b:c\n"
13524             "        c:d];",
13525             format("[self.a b:c\n"
13526                    "c:d];",
13527                    Style));
13528 }
13529 
TEST_F(FormatTest,FormatsLambdas)13530 TEST_F(FormatTest, FormatsLambdas) {
13531   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
13532   verifyFormat(
13533       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
13534   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
13535   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
13536   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
13537   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
13538   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
13539   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
13540   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
13541   verifyFormat("int x = f(*+[] {});");
13542   verifyFormat("void f() {\n"
13543                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
13544                "}\n");
13545   verifyFormat("void f() {\n"
13546                "  other(x.begin(), //\n"
13547                "        x.end(),   //\n"
13548                "        [&](int, int) { return 1; });\n"
13549                "}\n");
13550   verifyFormat("void f() {\n"
13551                "  other.other.other.other.other(\n"
13552                "      x.begin(), x.end(),\n"
13553                "      [something, rather](int, int, int, int, int, int, int) { "
13554                "return 1; });\n"
13555                "}\n");
13556   verifyFormat(
13557       "void f() {\n"
13558       "  other.other.other.other.other(\n"
13559       "      x.begin(), x.end(),\n"
13560       "      [something, rather](int, int, int, int, int, int, int) {\n"
13561       "        //\n"
13562       "      });\n"
13563       "}\n");
13564   verifyFormat("SomeFunction([]() { // A cool function...\n"
13565                "  return 43;\n"
13566                "});");
13567   EXPECT_EQ("SomeFunction([]() {\n"
13568             "#define A a\n"
13569             "  return 43;\n"
13570             "});",
13571             format("SomeFunction([](){\n"
13572                    "#define A a\n"
13573                    "return 43;\n"
13574                    "});"));
13575   verifyFormat("void f() {\n"
13576                "  SomeFunction([](decltype(x), A *a) {});\n"
13577                "}");
13578   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
13579                "    [](const aaaaaaaaaa &a) { return a; });");
13580   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
13581                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
13582                "});");
13583   verifyFormat("Constructor()\n"
13584                "    : Field([] { // comment\n"
13585                "        int i;\n"
13586                "      }) {}");
13587   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
13588                "  return some_parameter.size();\n"
13589                "};");
13590   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
13591                "    [](const string &s) { return s; };");
13592   verifyFormat("int i = aaaaaa ? 1 //\n"
13593                "               : [] {\n"
13594                "                   return 2; //\n"
13595                "                 }();");
13596   verifyFormat("llvm::errs() << \"number of twos is \"\n"
13597                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
13598                "                  return x == 2; // force break\n"
13599                "                });");
13600   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
13601                "    [=](int iiiiiiiiiiii) {\n"
13602                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
13603                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
13604                "    });",
13605                getLLVMStyleWithColumns(60));
13606   verifyFormat("SomeFunction({[&] {\n"
13607                "                // comment\n"
13608                "              },\n"
13609                "              [&] {\n"
13610                "                // comment\n"
13611                "              }});");
13612   verifyFormat("SomeFunction({[&] {\n"
13613                "  // comment\n"
13614                "}});");
13615   verifyFormat(
13616       "virtual aaaaaaaaaaaaaaaa(\n"
13617       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
13618       "    aaaaa aaaaaaaaa);");
13619 
13620   // Lambdas with return types.
13621   verifyFormat("int c = []() -> int { return 2; }();\n");
13622   verifyFormat("int c = []() -> int * { return 2; }();\n");
13623   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
13624   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
13625   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
13626   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
13627   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
13628   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
13629   verifyFormat("[a, a]() -> a<1> {};");
13630   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
13631   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
13632   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
13633   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
13634   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
13635   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
13636   verifyFormat("[]() -> foo<!5> { return {}; };");
13637   verifyFormat("[]() -> foo<~5> { return {}; };");
13638   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
13639   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
13640   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
13641   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
13642   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
13643   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
13644   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
13645   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
13646   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
13647   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
13648   verifyFormat("namespace bar {\n"
13649                "// broken:\n"
13650                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
13651                "} // namespace bar");
13652   verifyFormat("namespace bar {\n"
13653                "// broken:\n"
13654                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
13655                "} // namespace bar");
13656   verifyFormat("namespace bar {\n"
13657                "// broken:\n"
13658                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
13659                "} // namespace bar");
13660   verifyFormat("namespace bar {\n"
13661                "// broken:\n"
13662                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
13663                "} // namespace bar");
13664   verifyFormat("namespace bar {\n"
13665                "// broken:\n"
13666                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
13667                "} // namespace bar");
13668   verifyFormat("namespace bar {\n"
13669                "// broken:\n"
13670                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
13671                "} // namespace bar");
13672   verifyFormat("namespace bar {\n"
13673                "// broken:\n"
13674                "auto foo{[]() -> foo<!5> { return {}; }};\n"
13675                "} // namespace bar");
13676   verifyFormat("namespace bar {\n"
13677                "// broken:\n"
13678                "auto foo{[]() -> foo<~5> { return {}; }};\n"
13679                "} // namespace bar");
13680   verifyFormat("namespace bar {\n"
13681                "// broken:\n"
13682                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
13683                "} // namespace bar");
13684   verifyFormat("namespace bar {\n"
13685                "// broken:\n"
13686                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
13687                "} // namespace bar");
13688   verifyFormat("namespace bar {\n"
13689                "// broken:\n"
13690                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
13691                "} // namespace bar");
13692   verifyFormat("namespace bar {\n"
13693                "// broken:\n"
13694                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
13695                "} // namespace bar");
13696   verifyFormat("namespace bar {\n"
13697                "// broken:\n"
13698                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
13699                "} // namespace bar");
13700   verifyFormat("namespace bar {\n"
13701                "// broken:\n"
13702                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
13703                "} // namespace bar");
13704   verifyFormat("namespace bar {\n"
13705                "// broken:\n"
13706                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
13707                "} // namespace bar");
13708   verifyFormat("namespace bar {\n"
13709                "// broken:\n"
13710                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
13711                "} // namespace bar");
13712   verifyFormat("namespace bar {\n"
13713                "// broken:\n"
13714                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
13715                "} // namespace bar");
13716   verifyFormat("namespace bar {\n"
13717                "// broken:\n"
13718                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
13719                "} // namespace bar");
13720   verifyFormat("[]() -> a<1> {};");
13721   verifyFormat("[]() -> a<1> { ; };");
13722   verifyFormat("[]() -> a<1> { ; }();");
13723   verifyFormat("[a, a]() -> a<true> {};");
13724   verifyFormat("[]() -> a<true> {};");
13725   verifyFormat("[]() -> a<true> { ; };");
13726   verifyFormat("[]() -> a<true> { ; }();");
13727   verifyFormat("[a, a]() -> a<false> {};");
13728   verifyFormat("[]() -> a<false> {};");
13729   verifyFormat("[]() -> a<false> { ; };");
13730   verifyFormat("[]() -> a<false> { ; }();");
13731   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
13732   verifyFormat("namespace bar {\n"
13733                "auto foo{[]() -> foo<false> { ; }};\n"
13734                "} // namespace bar");
13735   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
13736                "                   int j) -> int {\n"
13737                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
13738                "};");
13739   verifyFormat(
13740       "aaaaaaaaaaaaaaaaaaaaaa(\n"
13741       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
13742       "      return aaaaaaaaaaaaaaaaa;\n"
13743       "    });",
13744       getLLVMStyleWithColumns(70));
13745   verifyFormat("[]() //\n"
13746                "    -> int {\n"
13747                "  return 1; //\n"
13748                "};");
13749 
13750   // Lambdas with explicit template argument lists.
13751   verifyFormat(
13752       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
13753 
13754   // Multiple lambdas in the same parentheses change indentation rules. These
13755   // lambdas are forced to start on new lines.
13756   verifyFormat("SomeFunction(\n"
13757                "    []() {\n"
13758                "      //\n"
13759                "    },\n"
13760                "    []() {\n"
13761                "      //\n"
13762                "    });");
13763 
13764   // A lambda passed as arg0 is always pushed to the next line.
13765   verifyFormat("SomeFunction(\n"
13766                "    [this] {\n"
13767                "      //\n"
13768                "    },\n"
13769                "    1);\n");
13770 
13771   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
13772   // the arg0 case above.
13773   auto Style = getGoogleStyle();
13774   Style.BinPackArguments = false;
13775   verifyFormat("SomeFunction(\n"
13776                "    a,\n"
13777                "    [this] {\n"
13778                "      //\n"
13779                "    },\n"
13780                "    b);\n",
13781                Style);
13782   verifyFormat("SomeFunction(\n"
13783                "    a,\n"
13784                "    [this] {\n"
13785                "      //\n"
13786                "    },\n"
13787                "    b);\n");
13788 
13789   // A lambda with a very long line forces arg0 to be pushed out irrespective of
13790   // the BinPackArguments value (as long as the code is wide enough).
13791   verifyFormat(
13792       "something->SomeFunction(\n"
13793       "    a,\n"
13794       "    [this] {\n"
13795       "      "
13796       "D0000000000000000000000000000000000000000000000000000000000001();\n"
13797       "    },\n"
13798       "    b);\n");
13799 
13800   // A multi-line lambda is pulled up as long as the introducer fits on the
13801   // previous line and there are no further args.
13802   verifyFormat("function(1, [this, that] {\n"
13803                "  //\n"
13804                "});\n");
13805   verifyFormat("function([this, that] {\n"
13806                "  //\n"
13807                "});\n");
13808   // FIXME: this format is not ideal and we should consider forcing the first
13809   // arg onto its own line.
13810   verifyFormat("function(a, b, c, //\n"
13811                "         d, [this, that] {\n"
13812                "           //\n"
13813                "         });\n");
13814 
13815   // Multiple lambdas are treated correctly even when there is a short arg0.
13816   verifyFormat("SomeFunction(\n"
13817                "    1,\n"
13818                "    [this] {\n"
13819                "      //\n"
13820                "    },\n"
13821                "    [this] {\n"
13822                "      //\n"
13823                "    },\n"
13824                "    1);\n");
13825 
13826   // More complex introducers.
13827   verifyFormat("return [i, args...] {};");
13828 
13829   // Not lambdas.
13830   verifyFormat("constexpr char hello[]{\"hello\"};");
13831   verifyFormat("double &operator[](int i) { return 0; }\n"
13832                "int i;");
13833   verifyFormat("std::unique_ptr<int[]> foo() {}");
13834   verifyFormat("int i = a[a][a]->f();");
13835   verifyFormat("int i = (*b)[a]->f();");
13836 
13837   // Other corner cases.
13838   verifyFormat("void f() {\n"
13839                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
13840                "  );\n"
13841                "}");
13842 
13843   // Lambdas created through weird macros.
13844   verifyFormat("void f() {\n"
13845                "  MACRO((const AA &a) { return 1; });\n"
13846                "  MACRO((AA &a) { return 1; });\n"
13847                "}");
13848 
13849   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
13850                "      doo_dah();\n"
13851                "      doo_dah();\n"
13852                "    })) {\n"
13853                "}");
13854   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
13855                "                doo_dah();\n"
13856                "                doo_dah();\n"
13857                "              })) {\n"
13858                "}");
13859   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
13860                "                doo_dah();\n"
13861                "                doo_dah();\n"
13862                "              })) {\n"
13863                "}");
13864   verifyFormat("auto lambda = []() {\n"
13865                "  int a = 2\n"
13866                "#if A\n"
13867                "          + 2\n"
13868                "#endif\n"
13869                "      ;\n"
13870                "};");
13871 
13872   // Lambdas with complex multiline introducers.
13873   verifyFormat(
13874       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
13875       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
13876       "        -> ::std::unordered_set<\n"
13877       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
13878       "      //\n"
13879       "    });");
13880 
13881   FormatStyle DoNotMerge = getLLVMStyle();
13882   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
13883   verifyFormat("auto c = []() {\n"
13884                "  return b;\n"
13885                "};",
13886                "auto c = []() { return b; };", DoNotMerge);
13887   verifyFormat("auto c = []() {\n"
13888                "};",
13889                " auto c = []() {};", DoNotMerge);
13890 
13891   FormatStyle MergeEmptyOnly = getLLVMStyle();
13892   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
13893   verifyFormat("auto c = []() {\n"
13894                "  return b;\n"
13895                "};",
13896                "auto c = []() {\n"
13897                "  return b;\n"
13898                " };",
13899                MergeEmptyOnly);
13900   verifyFormat("auto c = []() {};",
13901                "auto c = []() {\n"
13902                "};",
13903                MergeEmptyOnly);
13904 
13905   FormatStyle MergeInline = getLLVMStyle();
13906   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
13907   verifyFormat("auto c = []() {\n"
13908                "  return b;\n"
13909                "};",
13910                "auto c = []() { return b; };", MergeInline);
13911   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
13912                MergeInline);
13913   verifyFormat("function([]() { return b; }, a)",
13914                "function([]() { return b; }, a)", MergeInline);
13915   verifyFormat("function(a, []() { return b; })",
13916                "function(a, []() { return b; })", MergeInline);
13917 }
13918 
TEST_F(FormatTest,EmptyLinesInLambdas)13919 TEST_F(FormatTest, EmptyLinesInLambdas) {
13920   verifyFormat("auto lambda = []() {\n"
13921                "  x(); //\n"
13922                "};",
13923                "auto lambda = []() {\n"
13924                "\n"
13925                "  x(); //\n"
13926                "\n"
13927                "};");
13928 }
13929 
TEST_F(FormatTest,FormatsBlocks)13930 TEST_F(FormatTest, FormatsBlocks) {
13931   FormatStyle ShortBlocks = getLLVMStyle();
13932   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
13933   verifyFormat("int (^Block)(int, int);", ShortBlocks);
13934   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
13935   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
13936   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
13937   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
13938   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
13939 
13940   verifyFormat("foo(^{ bar(); });", ShortBlocks);
13941   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
13942   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
13943 
13944   verifyFormat("[operation setCompletionBlock:^{\n"
13945                "  [self onOperationDone];\n"
13946                "}];");
13947   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
13948                "  [self onOperationDone];\n"
13949                "}]};");
13950   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
13951                "  f();\n"
13952                "}];");
13953   verifyFormat("int a = [operation block:^int(int *i) {\n"
13954                "  return 1;\n"
13955                "}];");
13956   verifyFormat("[myObject doSomethingWith:arg1\n"
13957                "                      aaa:^int(int *a) {\n"
13958                "                        return 1;\n"
13959                "                      }\n"
13960                "                      bbb:f(a * bbbbbbbb)];");
13961 
13962   verifyFormat("[operation setCompletionBlock:^{\n"
13963                "  [self.delegate newDataAvailable];\n"
13964                "}];",
13965                getLLVMStyleWithColumns(60));
13966   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
13967                "  NSString *path = [self sessionFilePath];\n"
13968                "  if (path) {\n"
13969                "    // ...\n"
13970                "  }\n"
13971                "});");
13972   verifyFormat("[[SessionService sharedService]\n"
13973                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
13974                "      if (window) {\n"
13975                "        [self windowDidLoad:window];\n"
13976                "      } else {\n"
13977                "        [self errorLoadingWindow];\n"
13978                "      }\n"
13979                "    }];");
13980   verifyFormat("void (^largeBlock)(void) = ^{\n"
13981                "  // ...\n"
13982                "};\n",
13983                getLLVMStyleWithColumns(40));
13984   verifyFormat("[[SessionService sharedService]\n"
13985                "    loadWindowWithCompletionBlock: //\n"
13986                "        ^(SessionWindow *window) {\n"
13987                "          if (window) {\n"
13988                "            [self windowDidLoad:window];\n"
13989                "          } else {\n"
13990                "            [self errorLoadingWindow];\n"
13991                "          }\n"
13992                "        }];",
13993                getLLVMStyleWithColumns(60));
13994   verifyFormat("[myObject doSomethingWith:arg1\n"
13995                "    firstBlock:^(Foo *a) {\n"
13996                "      // ...\n"
13997                "      int i;\n"
13998                "    }\n"
13999                "    secondBlock:^(Bar *b) {\n"
14000                "      // ...\n"
14001                "      int i;\n"
14002                "    }\n"
14003                "    thirdBlock:^Foo(Bar *b) {\n"
14004                "      // ...\n"
14005                "      int i;\n"
14006                "    }];");
14007   verifyFormat("[myObject doSomethingWith:arg1\n"
14008                "               firstBlock:-1\n"
14009                "              secondBlock:^(Bar *b) {\n"
14010                "                // ...\n"
14011                "                int i;\n"
14012                "              }];");
14013 
14014   verifyFormat("f(^{\n"
14015                "  @autoreleasepool {\n"
14016                "    if (a) {\n"
14017                "      g();\n"
14018                "    }\n"
14019                "  }\n"
14020                "});");
14021   verifyFormat("Block b = ^int *(A *a, B *b) {}");
14022   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
14023                "};");
14024 
14025   FormatStyle FourIndent = getLLVMStyle();
14026   FourIndent.ObjCBlockIndentWidth = 4;
14027   verifyFormat("[operation setCompletionBlock:^{\n"
14028                "    [self onOperationDone];\n"
14029                "}];",
14030                FourIndent);
14031 }
14032 
TEST_F(FormatTest,FormatsBlocksWithZeroColumnWidth)14033 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
14034   FormatStyle ZeroColumn = getLLVMStyle();
14035   ZeroColumn.ColumnLimit = 0;
14036 
14037   verifyFormat("[[SessionService sharedService] "
14038                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
14039                "  if (window) {\n"
14040                "    [self windowDidLoad:window];\n"
14041                "  } else {\n"
14042                "    [self errorLoadingWindow];\n"
14043                "  }\n"
14044                "}];",
14045                ZeroColumn);
14046   EXPECT_EQ("[[SessionService sharedService]\n"
14047             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
14048             "      if (window) {\n"
14049             "        [self windowDidLoad:window];\n"
14050             "      } else {\n"
14051             "        [self errorLoadingWindow];\n"
14052             "      }\n"
14053             "    }];",
14054             format("[[SessionService sharedService]\n"
14055                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
14056                    "                if (window) {\n"
14057                    "    [self windowDidLoad:window];\n"
14058                    "  } else {\n"
14059                    "    [self errorLoadingWindow];\n"
14060                    "  }\n"
14061                    "}];",
14062                    ZeroColumn));
14063   verifyFormat("[myObject doSomethingWith:arg1\n"
14064                "    firstBlock:^(Foo *a) {\n"
14065                "      // ...\n"
14066                "      int i;\n"
14067                "    }\n"
14068                "    secondBlock:^(Bar *b) {\n"
14069                "      // ...\n"
14070                "      int i;\n"
14071                "    }\n"
14072                "    thirdBlock:^Foo(Bar *b) {\n"
14073                "      // ...\n"
14074                "      int i;\n"
14075                "    }];",
14076                ZeroColumn);
14077   verifyFormat("f(^{\n"
14078                "  @autoreleasepool {\n"
14079                "    if (a) {\n"
14080                "      g();\n"
14081                "    }\n"
14082                "  }\n"
14083                "});",
14084                ZeroColumn);
14085   verifyFormat("void (^largeBlock)(void) = ^{\n"
14086                "  // ...\n"
14087                "};",
14088                ZeroColumn);
14089 
14090   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
14091   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
14092             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
14093   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
14094   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
14095             "  int i;\n"
14096             "};",
14097             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
14098 }
14099 
TEST_F(FormatTest,SupportsCRLF)14100 TEST_F(FormatTest, SupportsCRLF) {
14101   EXPECT_EQ("int a;\r\n"
14102             "int b;\r\n"
14103             "int c;\r\n",
14104             format("int a;\r\n"
14105                    "  int b;\r\n"
14106                    "    int c;\r\n",
14107                    getLLVMStyle()));
14108   EXPECT_EQ("int a;\r\n"
14109             "int b;\r\n"
14110             "int c;\r\n",
14111             format("int a;\r\n"
14112                    "  int b;\n"
14113                    "    int c;\r\n",
14114                    getLLVMStyle()));
14115   EXPECT_EQ("int a;\n"
14116             "int b;\n"
14117             "int c;\n",
14118             format("int a;\r\n"
14119                    "  int b;\n"
14120                    "    int c;\n",
14121                    getLLVMStyle()));
14122   EXPECT_EQ("\"aaaaaaa \"\r\n"
14123             "\"bbbbbbb\";\r\n",
14124             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
14125   EXPECT_EQ("#define A \\\r\n"
14126             "  b;      \\\r\n"
14127             "  c;      \\\r\n"
14128             "  d;\r\n",
14129             format("#define A \\\r\n"
14130                    "  b; \\\r\n"
14131                    "  c; d; \r\n",
14132                    getGoogleStyle()));
14133 
14134   EXPECT_EQ("/*\r\n"
14135             "multi line block comments\r\n"
14136             "should not introduce\r\n"
14137             "an extra carriage return\r\n"
14138             "*/\r\n",
14139             format("/*\r\n"
14140                    "multi line block comments\r\n"
14141                    "should not introduce\r\n"
14142                    "an extra carriage return\r\n"
14143                    "*/\r\n"));
14144   EXPECT_EQ("/*\r\n"
14145             "\r\n"
14146             "*/",
14147             format("/*\r\n"
14148                    "    \r\r\r\n"
14149                    "*/"));
14150 
14151   FormatStyle style = getLLVMStyle();
14152 
14153   style.DeriveLineEnding = true;
14154   style.UseCRLF = false;
14155   EXPECT_EQ("union FooBarBazQux {\n"
14156             "  int foo;\n"
14157             "  int bar;\n"
14158             "  int baz;\n"
14159             "};",
14160             format("union FooBarBazQux {\r\n"
14161                    "  int foo;\n"
14162                    "  int bar;\r\n"
14163                    "  int baz;\n"
14164                    "};",
14165                    style));
14166   style.UseCRLF = true;
14167   EXPECT_EQ("union FooBarBazQux {\r\n"
14168             "  int foo;\r\n"
14169             "  int bar;\r\n"
14170             "  int baz;\r\n"
14171             "};",
14172             format("union FooBarBazQux {\r\n"
14173                    "  int foo;\n"
14174                    "  int bar;\r\n"
14175                    "  int baz;\n"
14176                    "};",
14177                    style));
14178 
14179   style.DeriveLineEnding = false;
14180   style.UseCRLF = false;
14181   EXPECT_EQ("union FooBarBazQux {\n"
14182             "  int foo;\n"
14183             "  int bar;\n"
14184             "  int baz;\n"
14185             "  int qux;\n"
14186             "};",
14187             format("union FooBarBazQux {\r\n"
14188                    "  int foo;\n"
14189                    "  int bar;\r\n"
14190                    "  int baz;\n"
14191                    "  int qux;\r\n"
14192                    "};",
14193                    style));
14194   style.UseCRLF = true;
14195   EXPECT_EQ("union FooBarBazQux {\r\n"
14196             "  int foo;\r\n"
14197             "  int bar;\r\n"
14198             "  int baz;\r\n"
14199             "  int qux;\r\n"
14200             "};",
14201             format("union FooBarBazQux {\r\n"
14202                    "  int foo;\n"
14203                    "  int bar;\r\n"
14204                    "  int baz;\n"
14205                    "  int qux;\n"
14206                    "};",
14207                    style));
14208 
14209   style.DeriveLineEnding = true;
14210   style.UseCRLF = false;
14211   EXPECT_EQ("union FooBarBazQux {\r\n"
14212             "  int foo;\r\n"
14213             "  int bar;\r\n"
14214             "  int baz;\r\n"
14215             "  int qux;\r\n"
14216             "};",
14217             format("union FooBarBazQux {\r\n"
14218                    "  int foo;\n"
14219                    "  int bar;\r\n"
14220                    "  int baz;\n"
14221                    "  int qux;\r\n"
14222                    "};",
14223                    style));
14224   style.UseCRLF = true;
14225   EXPECT_EQ("union FooBarBazQux {\n"
14226             "  int foo;\n"
14227             "  int bar;\n"
14228             "  int baz;\n"
14229             "  int qux;\n"
14230             "};",
14231             format("union FooBarBazQux {\r\n"
14232                    "  int foo;\n"
14233                    "  int bar;\r\n"
14234                    "  int baz;\n"
14235                    "  int qux;\n"
14236                    "};",
14237                    style));
14238 }
14239 
TEST_F(FormatTest,MunchSemicolonAfterBlocks)14240 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
14241   verifyFormat("MY_CLASS(C) {\n"
14242                "  int i;\n"
14243                "  int j;\n"
14244                "};");
14245 }
14246 
TEST_F(FormatTest,ConfigurableContinuationIndentWidth)14247 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
14248   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
14249   TwoIndent.ContinuationIndentWidth = 2;
14250 
14251   EXPECT_EQ("int i =\n"
14252             "  longFunction(\n"
14253             "    arg);",
14254             format("int i = longFunction(arg);", TwoIndent));
14255 
14256   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
14257   SixIndent.ContinuationIndentWidth = 6;
14258 
14259   EXPECT_EQ("int i =\n"
14260             "      longFunction(\n"
14261             "            arg);",
14262             format("int i = longFunction(arg);", SixIndent));
14263 }
14264 
TEST_F(FormatTest,WrappedClosingParenthesisIndent)14265 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
14266   FormatStyle Style = getLLVMStyle();
14267   verifyFormat("int Foo::getter(\n"
14268                "    //\n"
14269                ") const {\n"
14270                "  return foo;\n"
14271                "}",
14272                Style);
14273   verifyFormat("void Foo::setter(\n"
14274                "    //\n"
14275                ") {\n"
14276                "  foo = 1;\n"
14277                "}",
14278                Style);
14279 }
14280 
TEST_F(FormatTest,SpacesInAngles)14281 TEST_F(FormatTest, SpacesInAngles) {
14282   FormatStyle Spaces = getLLVMStyle();
14283   Spaces.SpacesInAngles = true;
14284 
14285   verifyFormat("static_cast< int >(arg);", Spaces);
14286   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
14287   verifyFormat("f< int, float >();", Spaces);
14288   verifyFormat("template <> g() {}", Spaces);
14289   verifyFormat("template < std::vector< int > > f() {}", Spaces);
14290   verifyFormat("std::function< void(int, int) > fct;", Spaces);
14291   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
14292                Spaces);
14293 
14294   Spaces.Standard = FormatStyle::LS_Cpp03;
14295   Spaces.SpacesInAngles = true;
14296   verifyFormat("A< A< int > >();", Spaces);
14297 
14298   Spaces.SpacesInAngles = false;
14299   verifyFormat("A<A<int> >();", Spaces);
14300 
14301   Spaces.Standard = FormatStyle::LS_Cpp11;
14302   Spaces.SpacesInAngles = true;
14303   verifyFormat("A< A< int > >();", Spaces);
14304 
14305   Spaces.SpacesInAngles = false;
14306   verifyFormat("A<A<int>>();", Spaces);
14307 }
14308 
TEST_F(FormatTest,SpaceAfterTemplateKeyword)14309 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
14310   FormatStyle Style = getLLVMStyle();
14311   Style.SpaceAfterTemplateKeyword = false;
14312   verifyFormat("template<int> void foo();", Style);
14313 }
14314 
TEST_F(FormatTest,TripleAngleBrackets)14315 TEST_F(FormatTest, TripleAngleBrackets) {
14316   verifyFormat("f<<<1, 1>>>();");
14317   verifyFormat("f<<<1, 1, 1, s>>>();");
14318   verifyFormat("f<<<a, b, c, d>>>();");
14319   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
14320   verifyFormat("f<param><<<1, 1>>>();");
14321   verifyFormat("f<1><<<1, 1>>>();");
14322   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
14323   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
14324                "aaaaaaaaaaa<<<\n    1, 1>>>();");
14325   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
14326                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
14327 }
14328 
TEST_F(FormatTest,MergeLessLessAtEnd)14329 TEST_F(FormatTest, MergeLessLessAtEnd) {
14330   verifyFormat("<<");
14331   EXPECT_EQ("< < <", format("\\\n<<<"));
14332   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
14333                "aaallvm::outs() <<");
14334   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
14335                "aaaallvm::outs()\n    <<");
14336 }
14337 
TEST_F(FormatTest,HandleUnbalancedImplicitBracesAcrossPPBranches)14338 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
14339   std::string code = "#if A\n"
14340                      "#if B\n"
14341                      "a.\n"
14342                      "#endif\n"
14343                      "    a = 1;\n"
14344                      "#else\n"
14345                      "#endif\n"
14346                      "#if C\n"
14347                      "#else\n"
14348                      "#endif\n";
14349   EXPECT_EQ(code, format(code));
14350 }
14351 
TEST_F(FormatTest,HandleConflictMarkers)14352 TEST_F(FormatTest, HandleConflictMarkers) {
14353   // Git/SVN conflict markers.
14354   EXPECT_EQ("int a;\n"
14355             "void f() {\n"
14356             "  callme(some(parameter1,\n"
14357             "<<<<<<< text by the vcs\n"
14358             "              parameter2),\n"
14359             "||||||| text by the vcs\n"
14360             "              parameter2),\n"
14361             "         parameter3,\n"
14362             "======= text by the vcs\n"
14363             "              parameter2, parameter3),\n"
14364             ">>>>>>> text by the vcs\n"
14365             "         otherparameter);\n",
14366             format("int a;\n"
14367                    "void f() {\n"
14368                    "  callme(some(parameter1,\n"
14369                    "<<<<<<< text by the vcs\n"
14370                    "  parameter2),\n"
14371                    "||||||| text by the vcs\n"
14372                    "  parameter2),\n"
14373                    "  parameter3,\n"
14374                    "======= text by the vcs\n"
14375                    "  parameter2,\n"
14376                    "  parameter3),\n"
14377                    ">>>>>>> text by the vcs\n"
14378                    "  otherparameter);\n"));
14379 
14380   // Perforce markers.
14381   EXPECT_EQ("void f() {\n"
14382             "  function(\n"
14383             ">>>> text by the vcs\n"
14384             "      parameter,\n"
14385             "==== text by the vcs\n"
14386             "      parameter,\n"
14387             "==== text by the vcs\n"
14388             "      parameter,\n"
14389             "<<<< text by the vcs\n"
14390             "      parameter);\n",
14391             format("void f() {\n"
14392                    "  function(\n"
14393                    ">>>> text by the vcs\n"
14394                    "  parameter,\n"
14395                    "==== text by the vcs\n"
14396                    "  parameter,\n"
14397                    "==== text by the vcs\n"
14398                    "  parameter,\n"
14399                    "<<<< text by the vcs\n"
14400                    "  parameter);\n"));
14401 
14402   EXPECT_EQ("<<<<<<<\n"
14403             "|||||||\n"
14404             "=======\n"
14405             ">>>>>>>",
14406             format("<<<<<<<\n"
14407                    "|||||||\n"
14408                    "=======\n"
14409                    ">>>>>>>"));
14410 
14411   EXPECT_EQ("<<<<<<<\n"
14412             "|||||||\n"
14413             "int i;\n"
14414             "=======\n"
14415             ">>>>>>>",
14416             format("<<<<<<<\n"
14417                    "|||||||\n"
14418                    "int i;\n"
14419                    "=======\n"
14420                    ">>>>>>>"));
14421 
14422   // FIXME: Handle parsing of macros around conflict markers correctly:
14423   EXPECT_EQ("#define Macro \\\n"
14424             "<<<<<<<\n"
14425             "Something \\\n"
14426             "|||||||\n"
14427             "Else \\\n"
14428             "=======\n"
14429             "Other \\\n"
14430             ">>>>>>>\n"
14431             "    End int i;\n",
14432             format("#define Macro \\\n"
14433                    "<<<<<<<\n"
14434                    "  Something \\\n"
14435                    "|||||||\n"
14436                    "  Else \\\n"
14437                    "=======\n"
14438                    "  Other \\\n"
14439                    ">>>>>>>\n"
14440                    "  End\n"
14441                    "int i;\n"));
14442 }
14443 
TEST_F(FormatTest,DisableRegions)14444 TEST_F(FormatTest, DisableRegions) {
14445   EXPECT_EQ("int i;\n"
14446             "// clang-format off\n"
14447             "  int j;\n"
14448             "// clang-format on\n"
14449             "int k;",
14450             format(" int  i;\n"
14451                    "   // clang-format off\n"
14452                    "  int j;\n"
14453                    " // clang-format on\n"
14454                    "   int   k;"));
14455   EXPECT_EQ("int i;\n"
14456             "/* clang-format off */\n"
14457             "  int j;\n"
14458             "/* clang-format on */\n"
14459             "int k;",
14460             format(" int  i;\n"
14461                    "   /* clang-format off */\n"
14462                    "  int j;\n"
14463                    " /* clang-format on */\n"
14464                    "   int   k;"));
14465 
14466   // Don't reflow comments within disabled regions.
14467   EXPECT_EQ("// clang-format off\n"
14468             "// long long long long long long line\n"
14469             "/* clang-format on */\n"
14470             "/* long long long\n"
14471             " * long long long\n"
14472             " * line */\n"
14473             "int i;\n"
14474             "/* clang-format off */\n"
14475             "/* long long long long long long line */\n",
14476             format("// clang-format off\n"
14477                    "// long long long long long long line\n"
14478                    "/* clang-format on */\n"
14479                    "/* long long long long long long line */\n"
14480                    "int i;\n"
14481                    "/* clang-format off */\n"
14482                    "/* long long long long long long line */\n",
14483                    getLLVMStyleWithColumns(20)));
14484 }
14485 
TEST_F(FormatTest,DoNotCrashOnInvalidInput)14486 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
14487   format("? ) =");
14488   verifyNoCrash("#define a\\\n /**/}");
14489 }
14490 
TEST_F(FormatTest,FormatsTableGenCode)14491 TEST_F(FormatTest, FormatsTableGenCode) {
14492   FormatStyle Style = getLLVMStyle();
14493   Style.Language = FormatStyle::LK_TableGen;
14494   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
14495 }
14496 
TEST_F(FormatTest,ArrayOfTemplates)14497 TEST_F(FormatTest, ArrayOfTemplates) {
14498   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
14499             format("auto a = new unique_ptr<int > [ 10];"));
14500 
14501   FormatStyle Spaces = getLLVMStyle();
14502   Spaces.SpacesInSquareBrackets = true;
14503   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
14504             format("auto a = new unique_ptr<int > [10];", Spaces));
14505 }
14506 
TEST_F(FormatTest,ArrayAsTemplateType)14507 TEST_F(FormatTest, ArrayAsTemplateType) {
14508   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
14509             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
14510 
14511   FormatStyle Spaces = getLLVMStyle();
14512   Spaces.SpacesInSquareBrackets = true;
14513   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
14514             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
14515 }
14516 
TEST_F(FormatTest,NoSpaceAfterSuper)14517 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
14518 
TEST(FormatStyle,GetStyleWithEmptyFileName)14519 TEST(FormatStyle, GetStyleWithEmptyFileName) {
14520   llvm::vfs::InMemoryFileSystem FS;
14521   auto Style1 = getStyle("file", "", "Google", "", &FS);
14522   ASSERT_TRUE((bool)Style1);
14523   ASSERT_EQ(*Style1, getGoogleStyle());
14524 }
14525 
TEST(FormatStyle,GetStyleOfFile)14526 TEST(FormatStyle, GetStyleOfFile) {
14527   llvm::vfs::InMemoryFileSystem FS;
14528   // Test 1: format file in the same directory.
14529   ASSERT_TRUE(
14530       FS.addFile("/a/.clang-format", 0,
14531                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
14532   ASSERT_TRUE(
14533       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
14534   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
14535   ASSERT_TRUE((bool)Style1);
14536   ASSERT_EQ(*Style1, getLLVMStyle());
14537 
14538   // Test 2.1: fallback to default.
14539   ASSERT_TRUE(
14540       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
14541   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
14542   ASSERT_TRUE((bool)Style2);
14543   ASSERT_EQ(*Style2, getMozillaStyle());
14544 
14545   // Test 2.2: no format on 'none' fallback style.
14546   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
14547   ASSERT_TRUE((bool)Style2);
14548   ASSERT_EQ(*Style2, getNoStyle());
14549 
14550   // Test 2.3: format if config is found with no based style while fallback is
14551   // 'none'.
14552   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
14553                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
14554   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
14555   ASSERT_TRUE((bool)Style2);
14556   ASSERT_EQ(*Style2, getLLVMStyle());
14557 
14558   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
14559   Style2 = getStyle("{}", "a.h", "none", "", &FS);
14560   ASSERT_TRUE((bool)Style2);
14561   ASSERT_EQ(*Style2, getLLVMStyle());
14562 
14563   // Test 3: format file in parent directory.
14564   ASSERT_TRUE(
14565       FS.addFile("/c/.clang-format", 0,
14566                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
14567   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
14568                          llvm::MemoryBuffer::getMemBuffer("int i;")));
14569   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
14570   ASSERT_TRUE((bool)Style3);
14571   ASSERT_EQ(*Style3, getGoogleStyle());
14572 
14573   // Test 4: error on invalid fallback style
14574   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
14575   ASSERT_FALSE((bool)Style4);
14576   llvm::consumeError(Style4.takeError());
14577 
14578   // Test 5: error on invalid yaml on command line
14579   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
14580   ASSERT_FALSE((bool)Style5);
14581   llvm::consumeError(Style5.takeError());
14582 
14583   // Test 6: error on invalid style
14584   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
14585   ASSERT_FALSE((bool)Style6);
14586   llvm::consumeError(Style6.takeError());
14587 
14588   // Test 7: found config file, error on parsing it
14589   ASSERT_TRUE(
14590       FS.addFile("/d/.clang-format", 0,
14591                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
14592                                                   "InvalidKey: InvalidValue")));
14593   ASSERT_TRUE(
14594       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
14595   auto Style7 = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
14596   ASSERT_FALSE((bool)Style7);
14597   llvm::consumeError(Style7.takeError());
14598 
14599   // Test 8: inferred per-language defaults apply.
14600   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
14601   ASSERT_TRUE((bool)StyleTd);
14602   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
14603 }
14604 
TEST_F(ReplacementTest,FormatCodeAfterReplacements)14605 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
14606   // Column limit is 20.
14607   std::string Code = "Type *a =\n"
14608                      "    new Type();\n"
14609                      "g(iiiii, 0, jjjjj,\n"
14610                      "  0, kkkkk, 0, mm);\n"
14611                      "int  bad     = format   ;";
14612   std::string Expected = "auto a = new Type();\n"
14613                          "g(iiiii, nullptr,\n"
14614                          "  jjjjj, nullptr,\n"
14615                          "  kkkkk, nullptr,\n"
14616                          "  mm);\n"
14617                          "int  bad     = format   ;";
14618   FileID ID = Context.createInMemoryFile("format.cpp", Code);
14619   tooling::Replacements Replaces = toReplacements(
14620       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
14621                             "auto "),
14622        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
14623                             "nullptr"),
14624        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
14625                             "nullptr"),
14626        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
14627                             "nullptr")});
14628 
14629   format::FormatStyle Style = format::getLLVMStyle();
14630   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
14631   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
14632   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
14633       << llvm::toString(FormattedReplaces.takeError()) << "\n";
14634   auto Result = applyAllReplacements(Code, *FormattedReplaces);
14635   EXPECT_TRUE(static_cast<bool>(Result));
14636   EXPECT_EQ(Expected, *Result);
14637 }
14638 
TEST_F(ReplacementTest,SortIncludesAfterReplacement)14639 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
14640   std::string Code = "#include \"a.h\"\n"
14641                      "#include \"c.h\"\n"
14642                      "\n"
14643                      "int main() {\n"
14644                      "  return 0;\n"
14645                      "}";
14646   std::string Expected = "#include \"a.h\"\n"
14647                          "#include \"b.h\"\n"
14648                          "#include \"c.h\"\n"
14649                          "\n"
14650                          "int main() {\n"
14651                          "  return 0;\n"
14652                          "}";
14653   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
14654   tooling::Replacements Replaces = toReplacements(
14655       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
14656                             "#include \"b.h\"\n")});
14657 
14658   format::FormatStyle Style = format::getLLVMStyle();
14659   Style.SortIncludes = true;
14660   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
14661   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
14662       << llvm::toString(FormattedReplaces.takeError()) << "\n";
14663   auto Result = applyAllReplacements(Code, *FormattedReplaces);
14664   EXPECT_TRUE(static_cast<bool>(Result));
14665   EXPECT_EQ(Expected, *Result);
14666 }
14667 
TEST_F(FormatTest,FormatSortsUsingDeclarations)14668 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
14669   EXPECT_EQ("using std::cin;\n"
14670             "using std::cout;",
14671             format("using std::cout;\n"
14672                    "using std::cin;",
14673                    getGoogleStyle()));
14674 }
14675 
TEST_F(FormatTest,UTF8CharacterLiteralCpp03)14676 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
14677   format::FormatStyle Style = format::getLLVMStyle();
14678   Style.Standard = FormatStyle::LS_Cpp03;
14679   // cpp03 recognize this string as identifier u8 and literal character 'a'
14680   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
14681 }
14682 
TEST_F(FormatTest,UTF8CharacterLiteralCpp11)14683 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
14684   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
14685   // all modes, including C++11, C++14 and C++17
14686   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
14687 }
14688 
TEST_F(FormatTest,DoNotFormatLikelyXml)14689 TEST_F(FormatTest, DoNotFormatLikelyXml) {
14690   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
14691   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
14692 }
14693 
TEST_F(FormatTest,StructuredBindings)14694 TEST_F(FormatTest, StructuredBindings) {
14695   // Structured bindings is a C++17 feature.
14696   // all modes, including C++11, C++14 and C++17
14697   verifyFormat("auto [a, b] = f();");
14698   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
14699   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
14700   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
14701   EXPECT_EQ("auto const volatile [a, b] = f();",
14702             format("auto  const   volatile[a, b] = f();"));
14703   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
14704   EXPECT_EQ("auto &[a, b, c] = f();",
14705             format("auto   &[  a  ,  b,c   ] = f();"));
14706   EXPECT_EQ("auto &&[a, b, c] = f();",
14707             format("auto   &&[  a  ,  b,c   ] = f();"));
14708   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
14709   EXPECT_EQ("auto const volatile &&[a, b] = f();",
14710             format("auto  const  volatile  &&[a, b] = f();"));
14711   EXPECT_EQ("auto const &&[a, b] = f();",
14712             format("auto  const   &&  [a, b] = f();"));
14713   EXPECT_EQ("const auto &[a, b] = f();",
14714             format("const  auto  &  [a, b] = f();"));
14715   EXPECT_EQ("const auto volatile &&[a, b] = f();",
14716             format("const  auto   volatile  &&[a, b] = f();"));
14717   EXPECT_EQ("volatile const auto &&[a, b] = f();",
14718             format("volatile  const  auto   &&[a, b] = f();"));
14719   EXPECT_EQ("const auto &&[a, b] = f();",
14720             format("const  auto  &&  [a, b] = f();"));
14721 
14722   // Make sure we don't mistake structured bindings for lambdas.
14723   FormatStyle PointerMiddle = getLLVMStyle();
14724   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
14725   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
14726   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
14727   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
14728   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
14729   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
14730   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
14731   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
14732   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
14733   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
14734   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
14735   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
14736   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
14737 
14738   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
14739             format("for (const auto   &&   [a, b] : some_range) {\n}"));
14740   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
14741             format("for (const auto   &   [a, b] : some_range) {\n}"));
14742   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
14743             format("for (const auto[a, b] : some_range) {\n}"));
14744   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
14745   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
14746   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
14747   EXPECT_EQ("auto const &[x, y](expr);",
14748             format("auto  const  &  [x,y]  (expr);"));
14749   EXPECT_EQ("auto const &&[x, y](expr);",
14750             format("auto  const  &&  [x,y]  (expr);"));
14751   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
14752   EXPECT_EQ("auto const &[x, y]{expr};",
14753             format("auto  const  &  [x,y]  {expr};"));
14754   EXPECT_EQ("auto const &&[x, y]{expr};",
14755             format("auto  const  &&  [x,y]  {expr};"));
14756 
14757   format::FormatStyle Spaces = format::getLLVMStyle();
14758   Spaces.SpacesInSquareBrackets = true;
14759   verifyFormat("auto [ a, b ] = f();", Spaces);
14760   verifyFormat("auto &&[ a, b ] = f();", Spaces);
14761   verifyFormat("auto &[ a, b ] = f();", Spaces);
14762   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
14763   verifyFormat("auto const &[ a, b ] = f();", Spaces);
14764 }
14765 
TEST_F(FormatTest,FileAndCode)14766 TEST_F(FormatTest, FileAndCode) {
14767   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
14768   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
14769   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
14770   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
14771   EXPECT_EQ(FormatStyle::LK_ObjC,
14772             guessLanguage("foo.h", "@interface Foo\n@end\n"));
14773   EXPECT_EQ(
14774       FormatStyle::LK_ObjC,
14775       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
14776   EXPECT_EQ(FormatStyle::LK_ObjC,
14777             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
14778   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
14779   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
14780   EXPECT_EQ(FormatStyle::LK_ObjC,
14781             guessLanguage("foo", "@interface Foo\n@end\n"));
14782   EXPECT_EQ(FormatStyle::LK_ObjC,
14783             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
14784   EXPECT_EQ(
14785       FormatStyle::LK_ObjC,
14786       guessLanguage("foo.h",
14787                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
14788   EXPECT_EQ(
14789       FormatStyle::LK_Cpp,
14790       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
14791 }
14792 
TEST_F(FormatTest,GuessLanguageWithCpp11AttributeSpecifiers)14793 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
14794   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
14795   EXPECT_EQ(FormatStyle::LK_ObjC,
14796             guessLanguage("foo.h", "array[[calculator getIndex]];"));
14797   EXPECT_EQ(FormatStyle::LK_Cpp,
14798             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
14799   EXPECT_EQ(
14800       FormatStyle::LK_Cpp,
14801       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
14802   EXPECT_EQ(FormatStyle::LK_ObjC,
14803             guessLanguage("foo.h", "[[noreturn foo] bar];"));
14804   EXPECT_EQ(FormatStyle::LK_Cpp,
14805             guessLanguage("foo.h", "[[clang::fallthrough]];"));
14806   EXPECT_EQ(FormatStyle::LK_ObjC,
14807             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
14808   EXPECT_EQ(FormatStyle::LK_Cpp,
14809             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
14810   EXPECT_EQ(FormatStyle::LK_Cpp,
14811             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
14812   EXPECT_EQ(FormatStyle::LK_ObjC,
14813             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
14814   EXPECT_EQ(FormatStyle::LK_Cpp,
14815             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
14816   EXPECT_EQ(
14817       FormatStyle::LK_Cpp,
14818       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
14819   EXPECT_EQ(
14820       FormatStyle::LK_Cpp,
14821       guessLanguage("foo.h",
14822                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
14823   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
14824 }
14825 
TEST_F(FormatTest,GuessLanguageWithCaret)14826 TEST_F(FormatTest, GuessLanguageWithCaret) {
14827   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
14828   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
14829   EXPECT_EQ(FormatStyle::LK_ObjC,
14830             guessLanguage("foo.h", "int(^)(char, float);"));
14831   EXPECT_EQ(FormatStyle::LK_ObjC,
14832             guessLanguage("foo.h", "int(^foo)(char, float);"));
14833   EXPECT_EQ(FormatStyle::LK_ObjC,
14834             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
14835   EXPECT_EQ(FormatStyle::LK_ObjC,
14836             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
14837   EXPECT_EQ(
14838       FormatStyle::LK_ObjC,
14839       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
14840 }
14841 
TEST_F(FormatTest,GuessedLanguageWithInlineAsmClobbers)14842 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
14843   EXPECT_EQ(FormatStyle::LK_Cpp,
14844             guessLanguage("foo.h", "void f() {\n"
14845                                    "  asm (\"mov %[e], %[d]\"\n"
14846                                    "     : [d] \"=rm\" (d)\n"
14847                                    "       [e] \"rm\" (*e));\n"
14848                                    "}"));
14849   EXPECT_EQ(FormatStyle::LK_Cpp,
14850             guessLanguage("foo.h", "void f() {\n"
14851                                    "  _asm (\"mov %[e], %[d]\"\n"
14852                                    "     : [d] \"=rm\" (d)\n"
14853                                    "       [e] \"rm\" (*e));\n"
14854                                    "}"));
14855   EXPECT_EQ(FormatStyle::LK_Cpp,
14856             guessLanguage("foo.h", "void f() {\n"
14857                                    "  __asm (\"mov %[e], %[d]\"\n"
14858                                    "     : [d] \"=rm\" (d)\n"
14859                                    "       [e] \"rm\" (*e));\n"
14860                                    "}"));
14861   EXPECT_EQ(FormatStyle::LK_Cpp,
14862             guessLanguage("foo.h", "void f() {\n"
14863                                    "  __asm__ (\"mov %[e], %[d]\"\n"
14864                                    "     : [d] \"=rm\" (d)\n"
14865                                    "       [e] \"rm\" (*e));\n"
14866                                    "}"));
14867   EXPECT_EQ(FormatStyle::LK_Cpp,
14868             guessLanguage("foo.h", "void f() {\n"
14869                                    "  asm (\"mov %[e], %[d]\"\n"
14870                                    "     : [d] \"=rm\" (d),\n"
14871                                    "       [e] \"rm\" (*e));\n"
14872                                    "}"));
14873   EXPECT_EQ(FormatStyle::LK_Cpp,
14874             guessLanguage("foo.h", "void f() {\n"
14875                                    "  asm volatile (\"mov %[e], %[d]\"\n"
14876                                    "     : [d] \"=rm\" (d)\n"
14877                                    "       [e] \"rm\" (*e));\n"
14878                                    "}"));
14879 }
14880 
TEST_F(FormatTest,GuessLanguageWithChildLines)14881 TEST_F(FormatTest, GuessLanguageWithChildLines) {
14882   EXPECT_EQ(FormatStyle::LK_Cpp,
14883             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
14884   EXPECT_EQ(FormatStyle::LK_ObjC,
14885             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
14886   EXPECT_EQ(
14887       FormatStyle::LK_Cpp,
14888       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
14889   EXPECT_EQ(
14890       FormatStyle::LK_ObjC,
14891       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
14892 }
14893 
TEST_F(FormatTest,TypenameMacros)14894 TEST_F(FormatTest, TypenameMacros) {
14895   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
14896 
14897   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
14898   FormatStyle Google = getGoogleStyleWithColumns(0);
14899   Google.TypenameMacros = TypenameMacros;
14900   verifyFormat("struct foo {\n"
14901                "  int bar;\n"
14902                "  TAILQ_ENTRY(a) bleh;\n"
14903                "};",
14904                Google);
14905 
14906   FormatStyle Macros = getLLVMStyle();
14907   Macros.TypenameMacros = TypenameMacros;
14908 
14909   verifyFormat("STACK_OF(int) a;", Macros);
14910   verifyFormat("STACK_OF(int) *a;", Macros);
14911   verifyFormat("STACK_OF(int const *) *a;", Macros);
14912   verifyFormat("STACK_OF(int *const) *a;", Macros);
14913   verifyFormat("STACK_OF(int, string) a;", Macros);
14914   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
14915   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
14916   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
14917   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
14918 
14919   Macros.PointerAlignment = FormatStyle::PAS_Left;
14920   verifyFormat("STACK_OF(int)* a;", Macros);
14921   verifyFormat("STACK_OF(int*)* a;", Macros);
14922 }
14923 
TEST_F(FormatTest,AmbersandInLamda)14924 TEST_F(FormatTest, AmbersandInLamda) {
14925   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
14926   FormatStyle AlignStyle = getLLVMStyle();
14927   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
14928   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
14929   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
14930   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
14931 }
14932 
TEST_F(FormatTest,SpacesInConditionalStatement)14933 TEST_F(FormatTest, SpacesInConditionalStatement) {
14934   FormatStyle Spaces = getLLVMStyle();
14935   Spaces.SpacesInConditionalStatement = true;
14936   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
14937   verifyFormat("if ( !a )\n  return;", Spaces);
14938   verifyFormat("if ( a )\n  return;", Spaces);
14939   verifyFormat("if constexpr ( a )\n  return;", Spaces);
14940   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
14941   verifyFormat("while ( a )\n  return;", Spaces);
14942   verifyFormat("while ( (a && b) )\n  return;", Spaces);
14943   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
14944   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
14945   // Check that space on the left of "::" is inserted as expected at beginning
14946   // of condition.
14947   verifyFormat("while ( ::func() )\n  return;", Spaces);
14948 }
14949 
TEST_F(FormatTest,AlternativeOperators)14950 TEST_F(FormatTest, AlternativeOperators) {
14951   // Test case for ensuring alternate operators are not
14952   // combined with their right most neighbour.
14953   verifyFormat("int a and b;");
14954   verifyFormat("int a and_eq b;");
14955   verifyFormat("int a bitand b;");
14956   verifyFormat("int a bitor b;");
14957   verifyFormat("int a compl b;");
14958   verifyFormat("int a not b;");
14959   verifyFormat("int a not_eq b;");
14960   verifyFormat("int a or b;");
14961   verifyFormat("int a xor b;");
14962   verifyFormat("int a xor_eq b;");
14963   verifyFormat("return this not_eq bitand other;");
14964   verifyFormat("bool operator not_eq(const X bitand other)");
14965 
14966   verifyFormat("int a and 5;");
14967   verifyFormat("int a and_eq 5;");
14968   verifyFormat("int a bitand 5;");
14969   verifyFormat("int a bitor 5;");
14970   verifyFormat("int a compl 5;");
14971   verifyFormat("int a not 5;");
14972   verifyFormat("int a not_eq 5;");
14973   verifyFormat("int a or 5;");
14974   verifyFormat("int a xor 5;");
14975   verifyFormat("int a xor_eq 5;");
14976 
14977   verifyFormat("int a compl(5);");
14978   verifyFormat("int a not(5);");
14979 
14980   /* FIXME handle alternate tokens
14981    * https://en.cppreference.com/w/cpp/language/operator_alternative
14982   // alternative tokens
14983   verifyFormat("compl foo();");     //  ~foo();
14984   verifyFormat("foo() <%%>;");      // foo();
14985   verifyFormat("void foo() <%%>;"); // void foo(){}
14986   verifyFormat("int a <:1:>;");     // int a[1];[
14987   verifyFormat("%:define ABC abc"); // #define ABC abc
14988   verifyFormat("%:%:");             // ##
14989   */
14990 }
14991 
TEST_F(FormatTest,STLWhileNotDefineChed)14992 TEST_F(FormatTest, STLWhileNotDefineChed) {
14993   verifyFormat("#if defined(while)\n"
14994                "#define while EMIT WARNING C4005\n"
14995                "#endif // while");
14996 }
14997 
TEST_F(FormatTest,OperatorSpacing)14998 TEST_F(FormatTest, OperatorSpacing) {
14999   FormatStyle Style = getLLVMStyle();
15000   Style.PointerAlignment = FormatStyle::PAS_Right;
15001   verifyFormat("Foo::operator*();", Style);
15002   verifyFormat("Foo::operator void *();", Style);
15003   verifyFormat("Foo::operator void **();", Style);
15004   verifyFormat("Foo::operator()(void *);", Style);
15005   verifyFormat("Foo::operator*(void *);", Style);
15006   verifyFormat("Foo::operator*();", Style);
15007   verifyFormat("Foo::operator**();", Style);
15008   verifyFormat("Foo::operator&();", Style);
15009   verifyFormat("Foo::operator<int> *();", Style);
15010   verifyFormat("Foo::operator<Foo> *();", Style);
15011   verifyFormat("Foo::operator<int> **();", Style);
15012   verifyFormat("Foo::operator<Foo> **();", Style);
15013   verifyFormat("Foo::operator<int> &();", Style);
15014   verifyFormat("Foo::operator<Foo> &();", Style);
15015   verifyFormat("Foo::operator<int> &&();", Style);
15016   verifyFormat("Foo::operator<Foo> &&();", Style);
15017   verifyFormat("operator*(int (*)(), class Foo);", Style);
15018 
15019   verifyFormat("Foo::operator&();", Style);
15020   verifyFormat("Foo::operator void &();", Style);
15021   verifyFormat("Foo::operator()(void &);", Style);
15022   verifyFormat("Foo::operator&(void &);", Style);
15023   verifyFormat("Foo::operator&();", Style);
15024   verifyFormat("operator&(int (&)(), class Foo);", Style);
15025 
15026   verifyFormat("Foo::operator&&();", Style);
15027   verifyFormat("Foo::operator**();", Style);
15028   verifyFormat("Foo::operator void &&();", Style);
15029   verifyFormat("Foo::operator()(void &&);", Style);
15030   verifyFormat("Foo::operator&&(void &&);", Style);
15031   verifyFormat("Foo::operator&&();", Style);
15032   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
15033   verifyFormat("operator const nsTArrayRight<E> &()", Style);
15034   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
15035                Style);
15036   verifyFormat("operator void **()", Style);
15037   verifyFormat("operator const FooRight<Object> &()", Style);
15038   verifyFormat("operator const FooRight<Object> *()", Style);
15039   verifyFormat("operator const FooRight<Object> **()", Style);
15040 
15041   Style.PointerAlignment = FormatStyle::PAS_Left;
15042   verifyFormat("Foo::operator*();", Style);
15043   verifyFormat("Foo::operator**();", Style);
15044   verifyFormat("Foo::operator void*();", Style);
15045   verifyFormat("Foo::operator void**();", Style);
15046   verifyFormat("Foo::operator/*comment*/ void*();", Style);
15047   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
15048   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
15049   verifyFormat("Foo::operator()(void*);", Style);
15050   verifyFormat("Foo::operator*(void*);", Style);
15051   verifyFormat("Foo::operator*();", Style);
15052   verifyFormat("Foo::operator<int>*();", Style);
15053   verifyFormat("Foo::operator<Foo>*();", Style);
15054   verifyFormat("Foo::operator<int>**();", Style);
15055   verifyFormat("Foo::operator<Foo>**();", Style);
15056   verifyFormat("Foo::operator<int>&();", Style);
15057   verifyFormat("Foo::operator<Foo>&();", Style);
15058   verifyFormat("Foo::operator<int>&&();", Style);
15059   verifyFormat("Foo::operator<Foo>&&();", Style);
15060   verifyFormat("operator*(int (*)(), class Foo);", Style);
15061 
15062   verifyFormat("Foo::operator&();", Style);
15063   verifyFormat("Foo::operator void&();", Style);
15064   verifyFormat("Foo::operator/*comment*/ void&();", Style);
15065   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
15066   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
15067   verifyFormat("Foo::operator()(void&);", Style);
15068   verifyFormat("Foo::operator&(void&);", Style);
15069   verifyFormat("Foo::operator&();", Style);
15070   verifyFormat("operator&(int (&)(), class Foo);", Style);
15071 
15072   verifyFormat("Foo::operator&&();", Style);
15073   verifyFormat("Foo::operator void&&();", Style);
15074   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
15075   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
15076   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
15077   verifyFormat("Foo::operator()(void&&);", Style);
15078   verifyFormat("Foo::operator&&(void&&);", Style);
15079   verifyFormat("Foo::operator&&();", Style);
15080   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
15081   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
15082   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
15083                Style);
15084   verifyFormat("operator void**()", Style);
15085   verifyFormat("operator const FooLeft<Object>&()", Style);
15086   verifyFormat("operator const FooLeft<Object>*()", Style);
15087   verifyFormat("operator const FooLeft<Object>**()", Style);
15088 
15089   // PR45107
15090   verifyFormat("operator Vector<String>&();", Style);
15091   verifyFormat("operator const Vector<String>&();", Style);
15092   verifyFormat("operator foo::Bar*();", Style);
15093   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
15094   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
15095                Style);
15096 
15097   Style.PointerAlignment = FormatStyle::PAS_Middle;
15098   verifyFormat("Foo::operator*();", Style);
15099   verifyFormat("Foo::operator void *();", Style);
15100   verifyFormat("Foo::operator()(void *);", Style);
15101   verifyFormat("Foo::operator*(void *);", Style);
15102   verifyFormat("Foo::operator*();", Style);
15103   verifyFormat("operator*(int (*)(), class Foo);", Style);
15104 
15105   verifyFormat("Foo::operator&();", Style);
15106   verifyFormat("Foo::operator void &();", Style);
15107   verifyFormat("Foo::operator()(void &);", Style);
15108   verifyFormat("Foo::operator&(void &);", Style);
15109   verifyFormat("Foo::operator&();", Style);
15110   verifyFormat("operator&(int (&)(), class Foo);", Style);
15111 
15112   verifyFormat("Foo::operator&&();", Style);
15113   verifyFormat("Foo::operator void &&();", Style);
15114   verifyFormat("Foo::operator()(void &&);", Style);
15115   verifyFormat("Foo::operator&&(void &&);", Style);
15116   verifyFormat("Foo::operator&&();", Style);
15117   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
15118 }
15119 
15120 } // namespace
15121 } // namespace format
15122 } // namespace clang
15123