• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Format/Format.h"
11 
12 #include "../Tooling/RewriterTestContext.h"
13 #include "FormatTestUtils.h"
14 
15 #include "clang/Frontend/TextDiagnosticPrinter.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "gtest/gtest.h"
19 
20 #define DEBUG_TYPE "format-test"
21 
22 namespace clang {
23 namespace format {
24 namespace {
25 
getGoogleStyle()26 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
27 
28 class FormatTest : public ::testing::Test {
29 protected:
30   enum IncompleteCheck {
31     IC_ExpectComplete,
32     IC_ExpectIncomplete,
33     IC_DoNotCheck
34   };
35 
format(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle (),IncompleteCheck CheckIncomplete=IC_ExpectComplete)36   std::string format(llvm::StringRef Code,
37                      const FormatStyle &Style = getLLVMStyle(),
38                      IncompleteCheck CheckIncomplete = IC_ExpectComplete) {
39     DEBUG(llvm::errs() << "---\n");
40     DEBUG(llvm::errs() << Code << "\n\n");
41     std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
42     bool IncompleteFormat = false;
43     tooling::Replacements Replaces =
44         reformat(Style, Code, Ranges, "<stdin>", &IncompleteFormat);
45     if (CheckIncomplete != IC_DoNotCheck) {
46       bool ExpectedIncompleteFormat = CheckIncomplete == IC_ExpectIncomplete;
47       EXPECT_EQ(ExpectedIncompleteFormat, IncompleteFormat) << Code << "\n\n";
48     }
49     ReplacementCount = Replaces.size();
50     auto Result = applyAllReplacements(Code, Replaces);
51     EXPECT_TRUE(static_cast<bool>(Result));
52     DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
53     return *Result;
54   }
55 
getLLVMStyleWithColumns(unsigned ColumnLimit)56   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
57     FormatStyle Style = getLLVMStyle();
58     Style.ColumnLimit = ColumnLimit;
59     return Style;
60   }
61 
getGoogleStyleWithColumns(unsigned ColumnLimit)62   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
63     FormatStyle Style = getGoogleStyle();
64     Style.ColumnLimit = ColumnLimit;
65     return Style;
66   }
67 
verifyFormat(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())68   void verifyFormat(llvm::StringRef Code,
69                     const FormatStyle &Style = getLLVMStyle()) {
70     EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
71   }
72 
verifyIncompleteFormat(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())73   void verifyIncompleteFormat(llvm::StringRef Code,
74                               const FormatStyle &Style = getLLVMStyle()) {
75     EXPECT_EQ(Code.str(),
76               format(test::messUp(Code), Style, IC_ExpectIncomplete));
77   }
78 
verifyGoogleFormat(llvm::StringRef Code)79   void verifyGoogleFormat(llvm::StringRef Code) {
80     verifyFormat(Code, getGoogleStyle());
81   }
82 
verifyIndependentOfContext(llvm::StringRef text)83   void verifyIndependentOfContext(llvm::StringRef text) {
84     verifyFormat(text);
85     verifyFormat(llvm::Twine("void f() { " + text + " }").str());
86   }
87 
88   /// \brief Verify that clang-format does not crash on the given input.
verifyNoCrash(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())89   void verifyNoCrash(llvm::StringRef Code,
90                      const FormatStyle &Style = getLLVMStyle()) {
91     format(Code, Style, IC_DoNotCheck);
92   }
93 
94   int ReplacementCount;
95 };
96 
TEST_F(FormatTest,MessUp)97 TEST_F(FormatTest, MessUp) {
98   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
99   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
100   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
101   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
102   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
103 }
104 
105 //===----------------------------------------------------------------------===//
106 // Basic function tests.
107 //===----------------------------------------------------------------------===//
108 
TEST_F(FormatTest,DoesNotChangeCorrectlyFormattedCode)109 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
110   EXPECT_EQ(";", format(";"));
111 }
112 
TEST_F(FormatTest,FormatsGlobalStatementsAt0)113 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
114   EXPECT_EQ("int i;", format("  int i;"));
115   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
116   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
117   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
118 }
119 
TEST_F(FormatTest,FormatsUnwrappedLinesAtFirstFormat)120 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
121   EXPECT_EQ("int i;", format("int\ni;"));
122 }
123 
TEST_F(FormatTest,FormatsNestedBlockStatements)124 TEST_F(FormatTest, FormatsNestedBlockStatements) {
125   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
126 }
127 
TEST_F(FormatTest,FormatsNestedCall)128 TEST_F(FormatTest, FormatsNestedCall) {
129   verifyFormat("Method(f1, f2(f3));");
130   verifyFormat("Method(f1(f2, f3()));");
131   verifyFormat("Method(f1(f2, (f3())));");
132 }
133 
TEST_F(FormatTest,NestedNameSpecifiers)134 TEST_F(FormatTest, NestedNameSpecifiers) {
135   verifyFormat("vector<::Type> v;");
136   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
137   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
138   verifyFormat("bool a = 2 < ::SomeFunction();");
139 }
140 
TEST_F(FormatTest,OnlyGeneratesNecessaryReplacements)141 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
142   EXPECT_EQ("if (a) {\n"
143             "  f();\n"
144             "}",
145             format("if(a){f();}"));
146   EXPECT_EQ(4, ReplacementCount);
147   EXPECT_EQ("if (a) {\n"
148             "  f();\n"
149             "}",
150             format("if (a) {\n"
151                    "  f();\n"
152                    "}"));
153   EXPECT_EQ(0, ReplacementCount);
154   EXPECT_EQ("/*\r\n"
155             "\r\n"
156             "*/\r\n",
157             format("/*\r\n"
158                    "\r\n"
159                    "*/\r\n"));
160   EXPECT_EQ(0, ReplacementCount);
161 }
162 
TEST_F(FormatTest,RemovesEmptyLines)163 TEST_F(FormatTest, RemovesEmptyLines) {
164   EXPECT_EQ("class C {\n"
165             "  int i;\n"
166             "};",
167             format("class C {\n"
168                    " int i;\n"
169                    "\n"
170                    "};"));
171 
172   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
173   EXPECT_EQ("namespace N {\n"
174             "\n"
175             "int i;\n"
176             "}",
177             format("namespace N {\n"
178                    "\n"
179                    "int    i;\n"
180                    "}",
181                    getGoogleStyle()));
182   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
183             "\n"
184             "int i;\n"
185             "}",
186             format("extern /**/ \"C\" /**/ {\n"
187                    "\n"
188                    "int    i;\n"
189                    "}",
190                    getGoogleStyle()));
191 
192   // ...but do keep inlining and removing empty lines for non-block extern "C"
193   // functions.
194   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
195   EXPECT_EQ("extern \"C\" int f() {\n"
196             "  int i = 42;\n"
197             "  return i;\n"
198             "}",
199             format("extern \"C\" int f() {\n"
200                    "\n"
201                    "  int i = 42;\n"
202                    "  return i;\n"
203                    "}",
204                    getGoogleStyle()));
205 
206   // Remove empty lines at the beginning and end of blocks.
207   EXPECT_EQ("void f() {\n"
208             "\n"
209             "  if (a) {\n"
210             "\n"
211             "    f();\n"
212             "  }\n"
213             "}",
214             format("void f() {\n"
215                    "\n"
216                    "  if (a) {\n"
217                    "\n"
218                    "    f();\n"
219                    "\n"
220                    "  }\n"
221                    "\n"
222                    "}",
223                    getLLVMStyle()));
224   EXPECT_EQ("void f() {\n"
225             "  if (a) {\n"
226             "    f();\n"
227             "  }\n"
228             "}",
229             format("void f() {\n"
230                    "\n"
231                    "  if (a) {\n"
232                    "\n"
233                    "    f();\n"
234                    "\n"
235                    "  }\n"
236                    "\n"
237                    "}",
238                    getGoogleStyle()));
239 
240   // Don't remove empty lines in more complex control statements.
241   EXPECT_EQ("void f() {\n"
242             "  if (a) {\n"
243             "    f();\n"
244             "\n"
245             "  } else if (b) {\n"
246             "    f();\n"
247             "  }\n"
248             "}",
249             format("void f() {\n"
250                    "  if (a) {\n"
251                    "    f();\n"
252                    "\n"
253                    "  } else if (b) {\n"
254                    "    f();\n"
255                    "\n"
256                    "  }\n"
257                    "\n"
258                    "}"));
259 
260   // FIXME: This is slightly inconsistent.
261   EXPECT_EQ("namespace {\n"
262             "int i;\n"
263             "}",
264             format("namespace {\n"
265                    "int i;\n"
266                    "\n"
267                    "}"));
268   EXPECT_EQ("namespace {\n"
269             "int i;\n"
270             "\n"
271             "} // namespace",
272             format("namespace {\n"
273                    "int i;\n"
274                    "\n"
275                    "}  // namespace"));
276 }
277 
TEST_F(FormatTest,RecognizesBinaryOperatorKeywords)278 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
279   verifyFormat("x = (a) and (b);");
280   verifyFormat("x = (a) or (b);");
281   verifyFormat("x = (a) bitand (b);");
282   verifyFormat("x = (a) bitor (b);");
283   verifyFormat("x = (a) not_eq (b);");
284   verifyFormat("x = (a) and_eq (b);");
285   verifyFormat("x = (a) or_eq (b);");
286   verifyFormat("x = (a) xor (b);");
287 }
288 
289 //===----------------------------------------------------------------------===//
290 // Tests for control statements.
291 //===----------------------------------------------------------------------===//
292 
TEST_F(FormatTest,FormatIfWithoutCompoundStatement)293 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
294   verifyFormat("if (true)\n  f();\ng();");
295   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
296   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
297 
298   FormatStyle AllowsMergedIf = getLLVMStyle();
299   AllowsMergedIf.AlignEscapedNewlinesLeft = true;
300   AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
301   verifyFormat("if (a)\n"
302                "  // comment\n"
303                "  f();",
304                AllowsMergedIf);
305   verifyFormat("{\n"
306                "  if (a)\n"
307                "  label:\n"
308                "    f();\n"
309                "}",
310                AllowsMergedIf);
311   verifyFormat("#define A \\\n"
312                "  if (a)  \\\n"
313                "  label:  \\\n"
314                "    f()",
315                AllowsMergedIf);
316   verifyFormat("if (a)\n"
317                "  ;",
318                AllowsMergedIf);
319   verifyFormat("if (a)\n"
320                "  if (b) return;",
321                AllowsMergedIf);
322 
323   verifyFormat("if (a) // Can't merge this\n"
324                "  f();\n",
325                AllowsMergedIf);
326   verifyFormat("if (a) /* still don't merge */\n"
327                "  f();",
328                AllowsMergedIf);
329   verifyFormat("if (a) { // Never merge this\n"
330                "  f();\n"
331                "}",
332                AllowsMergedIf);
333   verifyFormat("if (a) { /* Never merge this */\n"
334                "  f();\n"
335                "}",
336                AllowsMergedIf);
337 
338   AllowsMergedIf.ColumnLimit = 14;
339   verifyFormat("if (a) return;", AllowsMergedIf);
340   verifyFormat("if (aaaaaaaaa)\n"
341                "  return;",
342                AllowsMergedIf);
343 
344   AllowsMergedIf.ColumnLimit = 13;
345   verifyFormat("if (a)\n  return;", AllowsMergedIf);
346 }
347 
TEST_F(FormatTest,FormatLoopsWithoutCompoundStatement)348 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
349   FormatStyle AllowsMergedLoops = getLLVMStyle();
350   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
351   verifyFormat("while (true) continue;", AllowsMergedLoops);
352   verifyFormat("for (;;) continue;", AllowsMergedLoops);
353   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
354   verifyFormat("while (true)\n"
355                "  ;",
356                AllowsMergedLoops);
357   verifyFormat("for (;;)\n"
358                "  ;",
359                AllowsMergedLoops);
360   verifyFormat("for (;;)\n"
361                "  for (;;) continue;",
362                AllowsMergedLoops);
363   verifyFormat("for (;;) // Can't merge this\n"
364                "  continue;",
365                AllowsMergedLoops);
366   verifyFormat("for (;;) /* still don't merge */\n"
367                "  continue;",
368                AllowsMergedLoops);
369 }
370 
TEST_F(FormatTest,FormatShortBracedStatements)371 TEST_F(FormatTest, FormatShortBracedStatements) {
372   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
373   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = true;
374 
375   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = true;
376   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
377 
378   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
379   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
380   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
381   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
382   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
383   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
384   verifyFormat("if (true) { //\n"
385                "  f();\n"
386                "}",
387                AllowSimpleBracedStatements);
388   verifyFormat("if (true) {\n"
389                "  f();\n"
390                "  f();\n"
391                "}",
392                AllowSimpleBracedStatements);
393   verifyFormat("if (true) {\n"
394                "  f();\n"
395                "} else {\n"
396                "  f();\n"
397                "}",
398                AllowSimpleBracedStatements);
399 
400   verifyFormat("template <int> struct A2 {\n"
401                "  struct B {};\n"
402                "};",
403                AllowSimpleBracedStatements);
404 
405   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = false;
406   verifyFormat("if (true) {\n"
407                "  f();\n"
408                "}",
409                AllowSimpleBracedStatements);
410   verifyFormat("if (true) {\n"
411                "  f();\n"
412                "} else {\n"
413                "  f();\n"
414                "}",
415                AllowSimpleBracedStatements);
416 
417   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
418   verifyFormat("while (true) {\n"
419                "  f();\n"
420                "}",
421                AllowSimpleBracedStatements);
422   verifyFormat("for (;;) {\n"
423                "  f();\n"
424                "}",
425                AllowSimpleBracedStatements);
426 }
427 
TEST_F(FormatTest,ParseIfElse)428 TEST_F(FormatTest, ParseIfElse) {
429   verifyFormat("if (true)\n"
430                "  if (true)\n"
431                "    if (true)\n"
432                "      f();\n"
433                "    else\n"
434                "      g();\n"
435                "  else\n"
436                "    h();\n"
437                "else\n"
438                "  i();");
439   verifyFormat("if (true)\n"
440                "  if (true)\n"
441                "    if (true) {\n"
442                "      if (true)\n"
443                "        f();\n"
444                "    } else {\n"
445                "      g();\n"
446                "    }\n"
447                "  else\n"
448                "    h();\n"
449                "else {\n"
450                "  i();\n"
451                "}");
452   verifyFormat("void f() {\n"
453                "  if (a) {\n"
454                "  } else {\n"
455                "  }\n"
456                "}");
457 }
458 
TEST_F(FormatTest,ElseIf)459 TEST_F(FormatTest, ElseIf) {
460   verifyFormat("if (a) {\n} else if (b) {\n}");
461   verifyFormat("if (a)\n"
462                "  f();\n"
463                "else if (b)\n"
464                "  g();\n"
465                "else\n"
466                "  h();");
467   verifyFormat("if (a) {\n"
468                "  f();\n"
469                "}\n"
470                "// or else ..\n"
471                "else {\n"
472                "  g()\n"
473                "}");
474 
475   verifyFormat("if (a) {\n"
476                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
477                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
478                "}");
479   verifyFormat("if (a) {\n"
480                "} else if (\n"
481                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
482                "}",
483                getLLVMStyleWithColumns(62));
484 }
485 
TEST_F(FormatTest,FormatsForLoop)486 TEST_F(FormatTest, FormatsForLoop) {
487   verifyFormat(
488       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
489       "     ++VeryVeryLongLoopVariable)\n"
490       "  ;");
491   verifyFormat("for (;;)\n"
492                "  f();");
493   verifyFormat("for (;;) {\n}");
494   verifyFormat("for (;;) {\n"
495                "  f();\n"
496                "}");
497   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
498 
499   verifyFormat(
500       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
501       "                                          E = UnwrappedLines.end();\n"
502       "     I != E; ++I) {\n}");
503 
504   verifyFormat(
505       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
506       "     ++IIIII) {\n}");
507   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
508                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
509                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
510   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
511                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
512                "         E = FD->getDeclsInPrototypeScope().end();\n"
513                "     I != E; ++I) {\n}");
514   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
515                "         I = Container.begin(),\n"
516                "         E = Container.end();\n"
517                "     I != E; ++I) {\n}",
518                getLLVMStyleWithColumns(76));
519 
520   verifyFormat(
521       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
522       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
523       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
524       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
525       "     ++aaaaaaaaaaa) {\n}");
526   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
527                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
528                "     ++i) {\n}");
529   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
530                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
531                "}");
532   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
533                "         aaaaaaaaaa);\n"
534                "     iter; ++iter) {\n"
535                "}");
536   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
537                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
538                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
539                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
540 
541   FormatStyle NoBinPacking = getLLVMStyle();
542   NoBinPacking.BinPackParameters = false;
543   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
544                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
545                "                                           aaaaaaaaaaaaaaaa,\n"
546                "                                           aaaaaaaaaaaaaaaa,\n"
547                "                                           aaaaaaaaaaaaaaaa);\n"
548                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
549                "}",
550                NoBinPacking);
551   verifyFormat(
552       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
553       "                                          E = UnwrappedLines.end();\n"
554       "     I != E;\n"
555       "     ++I) {\n}",
556       NoBinPacking);
557 }
558 
TEST_F(FormatTest,RangeBasedForLoops)559 TEST_F(FormatTest, RangeBasedForLoops) {
560   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
561                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
562   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
563                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
564   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
565                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
566   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
567                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
568 }
569 
TEST_F(FormatTest,ForEachLoops)570 TEST_F(FormatTest, ForEachLoops) {
571   verifyFormat("void f() {\n"
572                "  foreach (Item *item, itemlist) {}\n"
573                "  Q_FOREACH (Item *item, itemlist) {}\n"
574                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
575                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
576                "}");
577 
578   // As function-like macros.
579   verifyFormat("#define foreach(x, y)\n"
580                "#define Q_FOREACH(x, y)\n"
581                "#define BOOST_FOREACH(x, y)\n"
582                "#define UNKNOWN_FOREACH(x, y)\n");
583 
584   // Not as function-like macros.
585   verifyFormat("#define foreach (x, y)\n"
586                "#define Q_FOREACH (x, y)\n"
587                "#define BOOST_FOREACH (x, y)\n"
588                "#define UNKNOWN_FOREACH (x, y)\n");
589 }
590 
TEST_F(FormatTest,FormatsWhileLoop)591 TEST_F(FormatTest, FormatsWhileLoop) {
592   verifyFormat("while (true) {\n}");
593   verifyFormat("while (true)\n"
594                "  f();");
595   verifyFormat("while () {\n}");
596   verifyFormat("while () {\n"
597                "  f();\n"
598                "}");
599 }
600 
TEST_F(FormatTest,FormatsDoWhile)601 TEST_F(FormatTest, FormatsDoWhile) {
602   verifyFormat("do {\n"
603                "  do_something();\n"
604                "} while (something());");
605   verifyFormat("do\n"
606                "  do_something();\n"
607                "while (something());");
608 }
609 
TEST_F(FormatTest,FormatsSwitchStatement)610 TEST_F(FormatTest, FormatsSwitchStatement) {
611   verifyFormat("switch (x) {\n"
612                "case 1:\n"
613                "  f();\n"
614                "  break;\n"
615                "case kFoo:\n"
616                "case ns::kBar:\n"
617                "case kBaz:\n"
618                "  break;\n"
619                "default:\n"
620                "  g();\n"
621                "  break;\n"
622                "}");
623   verifyFormat("switch (x) {\n"
624                "case 1: {\n"
625                "  f();\n"
626                "  break;\n"
627                "}\n"
628                "case 2: {\n"
629                "  break;\n"
630                "}\n"
631                "}");
632   verifyFormat("switch (x) {\n"
633                "case 1: {\n"
634                "  f();\n"
635                "  {\n"
636                "    g();\n"
637                "    h();\n"
638                "  }\n"
639                "  break;\n"
640                "}\n"
641                "}");
642   verifyFormat("switch (x) {\n"
643                "case 1: {\n"
644                "  f();\n"
645                "  if (foo) {\n"
646                "    g();\n"
647                "    h();\n"
648                "  }\n"
649                "  break;\n"
650                "}\n"
651                "}");
652   verifyFormat("switch (x) {\n"
653                "case 1: {\n"
654                "  f();\n"
655                "  g();\n"
656                "} break;\n"
657                "}");
658   verifyFormat("switch (test)\n"
659                "  ;");
660   verifyFormat("switch (x) {\n"
661                "default: {\n"
662                "  // Do nothing.\n"
663                "}\n"
664                "}");
665   verifyFormat("switch (x) {\n"
666                "// comment\n"
667                "// if 1, do f()\n"
668                "case 1:\n"
669                "  f();\n"
670                "}");
671   verifyFormat("switch (x) {\n"
672                "case 1:\n"
673                "  // Do amazing stuff\n"
674                "  {\n"
675                "    f();\n"
676                "    g();\n"
677                "  }\n"
678                "  break;\n"
679                "}");
680   verifyFormat("#define A          \\\n"
681                "  switch (x) {     \\\n"
682                "  case a:          \\\n"
683                "    foo = b;       \\\n"
684                "  }",
685                getLLVMStyleWithColumns(20));
686   verifyFormat("#define OPERATION_CASE(name)           \\\n"
687                "  case OP_name:                        \\\n"
688                "    return operations::Operation##name\n",
689                getLLVMStyleWithColumns(40));
690   verifyFormat("switch (x) {\n"
691                "case 1:;\n"
692                "default:;\n"
693                "  int i;\n"
694                "}");
695 
696   verifyGoogleFormat("switch (x) {\n"
697                      "  case 1:\n"
698                      "    f();\n"
699                      "    break;\n"
700                      "  case kFoo:\n"
701                      "  case ns::kBar:\n"
702                      "  case kBaz:\n"
703                      "    break;\n"
704                      "  default:\n"
705                      "    g();\n"
706                      "    break;\n"
707                      "}");
708   verifyGoogleFormat("switch (x) {\n"
709                      "  case 1: {\n"
710                      "    f();\n"
711                      "    break;\n"
712                      "  }\n"
713                      "}");
714   verifyGoogleFormat("switch (test)\n"
715                      "  ;");
716 
717   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
718                      "  case OP_name:              \\\n"
719                      "    return operations::Operation##name\n");
720   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
721                      "  // Get the correction operation class.\n"
722                      "  switch (OpCode) {\n"
723                      "    CASE(Add);\n"
724                      "    CASE(Subtract);\n"
725                      "    default:\n"
726                      "      return operations::Unknown;\n"
727                      "  }\n"
728                      "#undef OPERATION_CASE\n"
729                      "}");
730   verifyFormat("DEBUG({\n"
731                "  switch (x) {\n"
732                "  case A:\n"
733                "    f();\n"
734                "    break;\n"
735                "  // On B:\n"
736                "  case B:\n"
737                "    g();\n"
738                "    break;\n"
739                "  }\n"
740                "});");
741   verifyFormat("switch (a) {\n"
742                "case (b):\n"
743                "  return;\n"
744                "}");
745 
746   verifyFormat("switch (a) {\n"
747                "case some_namespace::\n"
748                "    some_constant:\n"
749                "  return;\n"
750                "}",
751                getLLVMStyleWithColumns(34));
752 }
753 
TEST_F(FormatTest,CaseRanges)754 TEST_F(FormatTest, CaseRanges) {
755   verifyFormat("switch (x) {\n"
756                "case 'A' ... 'Z':\n"
757                "case 1 ... 5:\n"
758                "case a ... b:\n"
759                "  break;\n"
760                "}");
761 }
762 
TEST_F(FormatTest,ShortCaseLabels)763 TEST_F(FormatTest, ShortCaseLabels) {
764   FormatStyle Style = getLLVMStyle();
765   Style.AllowShortCaseLabelsOnASingleLine = true;
766   verifyFormat("switch (a) {\n"
767                "case 1: x = 1; break;\n"
768                "case 2: return;\n"
769                "case 3:\n"
770                "case 4:\n"
771                "case 5: return;\n"
772                "case 6: // comment\n"
773                "  return;\n"
774                "case 7:\n"
775                "  // comment\n"
776                "  return;\n"
777                "case 8:\n"
778                "  x = 8; // comment\n"
779                "  break;\n"
780                "default: y = 1; break;\n"
781                "}",
782                Style);
783   verifyFormat("switch (a) {\n"
784                "#if FOO\n"
785                "case 0: return 0;\n"
786                "#endif\n"
787                "}",
788                Style);
789   verifyFormat("switch (a) {\n"
790                "case 1: {\n"
791                "}\n"
792                "case 2: {\n"
793                "  return;\n"
794                "}\n"
795                "case 3: {\n"
796                "  x = 1;\n"
797                "  return;\n"
798                "}\n"
799                "case 4:\n"
800                "  if (x)\n"
801                "    return;\n"
802                "}",
803                Style);
804   Style.ColumnLimit = 21;
805   verifyFormat("switch (a) {\n"
806                "case 1: x = 1; break;\n"
807                "case 2: return;\n"
808                "case 3:\n"
809                "case 4:\n"
810                "case 5: return;\n"
811                "default:\n"
812                "  y = 1;\n"
813                "  break;\n"
814                "}",
815                Style);
816 }
817 
TEST_F(FormatTest,FormatsLabels)818 TEST_F(FormatTest, FormatsLabels) {
819   verifyFormat("void f() {\n"
820                "  some_code();\n"
821                "test_label:\n"
822                "  some_other_code();\n"
823                "  {\n"
824                "    some_more_code();\n"
825                "  another_label:\n"
826                "    some_more_code();\n"
827                "  }\n"
828                "}");
829   verifyFormat("{\n"
830                "  some_code();\n"
831                "test_label:\n"
832                "  some_other_code();\n"
833                "}");
834   verifyFormat("{\n"
835                "  some_code();\n"
836                "test_label:;\n"
837                "  int i = 0;\n"
838                "}");
839 }
840 
841 //===----------------------------------------------------------------------===//
842 // Tests for comments.
843 //===----------------------------------------------------------------------===//
844 
TEST_F(FormatTest,UnderstandsSingleLineComments)845 TEST_F(FormatTest, UnderstandsSingleLineComments) {
846   verifyFormat("//* */");
847   verifyFormat("// line 1\n"
848                "// line 2\n"
849                "void f() {}\n");
850 
851   verifyFormat("void f() {\n"
852                "  // Doesn't do anything\n"
853                "}");
854   verifyFormat("SomeObject\n"
855                "    // Calling someFunction on SomeObject\n"
856                "    .someFunction();");
857   verifyFormat("auto result = SomeObject\n"
858                "                  // Calling someFunction on SomeObject\n"
859                "                  .someFunction();");
860   verifyFormat("void f(int i,  // some comment (probably for i)\n"
861                "       int j,  // some comment (probably for j)\n"
862                "       int k); // some comment (probably for k)");
863   verifyFormat("void f(int i,\n"
864                "       // some comment (probably for j)\n"
865                "       int j,\n"
866                "       // some comment (probably for k)\n"
867                "       int k);");
868 
869   verifyFormat("int i    // This is a fancy variable\n"
870                "    = 5; // with nicely aligned comment.");
871 
872   verifyFormat("// Leading comment.\n"
873                "int a; // Trailing comment.");
874   verifyFormat("int a; // Trailing comment\n"
875                "       // on 2\n"
876                "       // or 3 lines.\n"
877                "int b;");
878   verifyFormat("int a; // Trailing comment\n"
879                "\n"
880                "// Leading comment.\n"
881                "int b;");
882   verifyFormat("int a;    // Comment.\n"
883                "          // More details.\n"
884                "int bbbb; // Another comment.");
885   verifyFormat(
886       "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
887       "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   // comment\n"
888       "int cccccccccccccccccccccccccccccc;       // comment\n"
889       "int ddd;                     // looooooooooooooooooooooooong comment\n"
890       "int aaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
891       "int bbbbbbbbbbbbbbbbbbbbb;   // comment\n"
892       "int ccccccccccccccccccc;     // comment");
893 
894   verifyFormat("#include \"a\"     // comment\n"
895                "#include \"a/b/c\" // comment");
896   verifyFormat("#include <a>     // comment\n"
897                "#include <a/b/c> // comment");
898   EXPECT_EQ("#include \"a\"     // comment\n"
899             "#include \"a/b/c\" // comment",
900             format("#include \\\n"
901                    "  \"a\" // comment\n"
902                    "#include \"a/b/c\" // comment"));
903 
904   verifyFormat("enum E {\n"
905                "  // comment\n"
906                "  VAL_A, // comment\n"
907                "  VAL_B\n"
908                "};");
909 
910   verifyFormat(
911       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
912       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // Trailing comment");
913   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
914                "    // Comment inside a statement.\n"
915                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
916   verifyFormat("SomeFunction(a,\n"
917                "             // comment\n"
918                "             b + x);");
919   verifyFormat("SomeFunction(a, a,\n"
920                "             // comment\n"
921                "             b + x);");
922   verifyFormat(
923       "bool aaaaaaaaaaaaa = // comment\n"
924       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
925       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
926 
927   verifyFormat("int aaaa; // aaaaa\n"
928                "int aa;   // aaaaaaa",
929                getLLVMStyleWithColumns(20));
930 
931   EXPECT_EQ("void f() { // This does something ..\n"
932             "}\n"
933             "int a; // This is unrelated",
934             format("void f()    {     // This does something ..\n"
935                    "  }\n"
936                    "int   a;     // This is unrelated"));
937   EXPECT_EQ("class C {\n"
938             "  void f() { // This does something ..\n"
939             "  }          // awesome..\n"
940             "\n"
941             "  int a; // This is unrelated\n"
942             "};",
943             format("class C{void f()    { // This does something ..\n"
944                    "      } // awesome..\n"
945                    " \n"
946                    "int a;    // This is unrelated\n"
947                    "};"));
948 
949   EXPECT_EQ("int i; // single line trailing comment",
950             format("int i;\\\n// single line trailing comment"));
951 
952   verifyGoogleFormat("int a;  // Trailing comment.");
953 
954   verifyFormat("someFunction(anotherFunction( // Force break.\n"
955                "    parameter));");
956 
957   verifyGoogleFormat("#endif  // HEADER_GUARD");
958 
959   verifyFormat("const char *test[] = {\n"
960                "    // A\n"
961                "    \"aaaa\",\n"
962                "    // B\n"
963                "    \"aaaaa\"};");
964   verifyGoogleFormat(
965       "aaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
966       "    aaaaaaaaaaaaaaaaaaaaaa);  // 81_cols_with_this_comment");
967   EXPECT_EQ("D(a, {\n"
968             "  // test\n"
969             "  int a;\n"
970             "});",
971             format("D(a, {\n"
972                    "// test\n"
973                    "int a;\n"
974                    "});"));
975 
976   EXPECT_EQ("lineWith(); // comment\n"
977             "// at start\n"
978             "otherLine();",
979             format("lineWith();   // comment\n"
980                    "// at start\n"
981                    "otherLine();"));
982   EXPECT_EQ("lineWith(); // comment\n"
983             "/*\n"
984             " * at start */\n"
985             "otherLine();",
986             format("lineWith();   // comment\n"
987                    "/*\n"
988                    " * at start */\n"
989                    "otherLine();"));
990   EXPECT_EQ("lineWith(); // comment\n"
991             "            // at start\n"
992             "otherLine();",
993             format("lineWith();   // comment\n"
994                    " // at start\n"
995                    "otherLine();"));
996 
997   EXPECT_EQ("lineWith(); // comment\n"
998             "// at start\n"
999             "otherLine(); // comment",
1000             format("lineWith();   // comment\n"
1001                    "// at start\n"
1002                    "otherLine();   // comment"));
1003   EXPECT_EQ("lineWith();\n"
1004             "// at start\n"
1005             "otherLine(); // comment",
1006             format("lineWith();\n"
1007                    " // at start\n"
1008                    "otherLine();   // comment"));
1009   EXPECT_EQ("// first\n"
1010             "// at start\n"
1011             "otherLine(); // comment",
1012             format("// first\n"
1013                    " // at start\n"
1014                    "otherLine();   // comment"));
1015   EXPECT_EQ("f();\n"
1016             "// first\n"
1017             "// at start\n"
1018             "otherLine(); // comment",
1019             format("f();\n"
1020                    "// first\n"
1021                    " // at start\n"
1022                    "otherLine();   // comment"));
1023   verifyFormat("f(); // comment\n"
1024                "// first\n"
1025                "// at start\n"
1026                "otherLine();");
1027   EXPECT_EQ("f(); // comment\n"
1028             "// first\n"
1029             "// at start\n"
1030             "otherLine();",
1031             format("f();   // comment\n"
1032                    "// first\n"
1033                    " // at start\n"
1034                    "otherLine();"));
1035   EXPECT_EQ("f(); // comment\n"
1036             "     // first\n"
1037             "// at start\n"
1038             "otherLine();",
1039             format("f();   // comment\n"
1040                    " // first\n"
1041                    "// at start\n"
1042                    "otherLine();"));
1043   EXPECT_EQ("void f() {\n"
1044             "  lineWith(); // comment\n"
1045             "  // at start\n"
1046             "}",
1047             format("void              f() {\n"
1048                    "  lineWith(); // comment\n"
1049                    "  // at start\n"
1050                    "}"));
1051   EXPECT_EQ("int xy; // a\n"
1052             "int z;  // b",
1053             format("int xy;    // a\n"
1054                    "int z;    //b"));
1055   EXPECT_EQ("int xy; // a\n"
1056             "int z; // bb",
1057             format("int xy;    // a\n"
1058                    "int z;    //bb",
1059                    getLLVMStyleWithColumns(12)));
1060 
1061   verifyFormat("#define A                                                  \\\n"
1062                "  int i; /* iiiiiiiiiiiiiiiiiiiii */                       \\\n"
1063                "  int jjjjjjjjjjjjjjjjjjjjjjjj; /* */",
1064                getLLVMStyleWithColumns(60));
1065   verifyFormat(
1066       "#define A                                                   \\\n"
1067       "  int i;                        /* iiiiiiiiiiiiiiiiiiiii */ \\\n"
1068       "  int jjjjjjjjjjjjjjjjjjjjjjjj; /* */",
1069       getLLVMStyleWithColumns(61));
1070 
1071   verifyFormat("if ( // This is some comment\n"
1072                "    x + 3) {\n"
1073                "}");
1074   EXPECT_EQ("if ( // This is some comment\n"
1075             "     // spanning two lines\n"
1076             "    x + 3) {\n"
1077             "}",
1078             format("if( // This is some comment\n"
1079                    "     // spanning two lines\n"
1080                    " x + 3) {\n"
1081                    "}"));
1082 
1083   verifyNoCrash("/\\\n/");
1084   verifyNoCrash("/\\\n* */");
1085   // The 0-character somehow makes the lexer return a proper comment.
1086   verifyNoCrash(StringRef("/*\\\0\n/", 6));
1087 }
1088 
TEST_F(FormatTest,KeepsParameterWithTrailingCommentsOnTheirOwnLine)1089 TEST_F(FormatTest, KeepsParameterWithTrailingCommentsOnTheirOwnLine) {
1090   EXPECT_EQ("SomeFunction(a,\n"
1091             "             b, // comment\n"
1092             "             c);",
1093             format("SomeFunction(a,\n"
1094                    "          b, // comment\n"
1095                    "      c);"));
1096   EXPECT_EQ("SomeFunction(a, b,\n"
1097             "             // comment\n"
1098             "             c);",
1099             format("SomeFunction(a,\n"
1100                    "          b,\n"
1101                    "  // comment\n"
1102                    "      c);"));
1103   EXPECT_EQ("SomeFunction(a, b, // comment (unclear relation)\n"
1104             "             c);",
1105             format("SomeFunction(a, b, // comment (unclear relation)\n"
1106                    "      c);"));
1107   EXPECT_EQ("SomeFunction(a, // comment\n"
1108             "             b,\n"
1109             "             c); // comment",
1110             format("SomeFunction(a,     // comment\n"
1111                    "          b,\n"
1112                    "      c); // comment"));
1113 }
1114 
TEST_F(FormatTest,RemovesTrailingWhitespaceOfComments)1115 TEST_F(FormatTest, RemovesTrailingWhitespaceOfComments) {
1116   EXPECT_EQ("// comment", format("// comment  "));
1117   EXPECT_EQ("int aaaaaaa, bbbbbbb; // comment",
1118             format("int aaaaaaa, bbbbbbb; // comment                   ",
1119                    getLLVMStyleWithColumns(33)));
1120   EXPECT_EQ("// comment\\\n", format("// comment\\\n  \t \v   \f   "));
1121   EXPECT_EQ("// comment    \\\n", format("// comment    \\\n  \t \v   \f   "));
1122 }
1123 
TEST_F(FormatTest,UnderstandsBlockComments)1124 TEST_F(FormatTest, UnderstandsBlockComments) {
1125   verifyFormat("f(/*noSpaceAfterParameterNamingComment=*/true);");
1126   verifyFormat("void f() { g(/*aaa=*/x, /*bbb=*/!y, /*c=*/::c); }");
1127   EXPECT_EQ("f(aaaaaaaaaaaaaaaaaaaaaaaaa, /* Trailing comment for aa... */\n"
1128             "  bbbbbbbbbbbbbbbbbbbbbbbbb);",
1129             format("f(aaaaaaaaaaaaaaaaaaaaaaaaa ,   \\\n"
1130                    "/* Trailing comment for aa... */\n"
1131                    "  bbbbbbbbbbbbbbbbbbbbbbbbb);"));
1132   EXPECT_EQ(
1133       "f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1134       "  /* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);",
1135       format("f(aaaaaaaaaaaaaaaaaaaaaaaaa    ,   \n"
1136              "/* Leading comment for bb... */   bbbbbbbbbbbbbbbbbbbbbbbbb);"));
1137   EXPECT_EQ(
1138       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1139       "    aaaaaaaaaaaaaaaaaa,\n"
1140       "    aaaaaaaaaaaaaaaaaa) { /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
1141       "}",
1142       format("void      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1143              "                      aaaaaaaaaaaaaaaaaa  ,\n"
1144              "    aaaaaaaaaaaaaaaaaa) {   /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
1145              "}"));
1146   verifyFormat("f(/* aaaaaaaaaaaaaaaaaa = */\n"
1147                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1148 
1149   FormatStyle NoBinPacking = getLLVMStyle();
1150   NoBinPacking.BinPackParameters = false;
1151   verifyFormat("aaaaaaaa(/* parameter 1 */ aaaaaa,\n"
1152                "         /* parameter 2 */ aaaaaa,\n"
1153                "         /* parameter 3 */ aaaaaa,\n"
1154                "         /* parameter 4 */ aaaaaa);",
1155                NoBinPacking);
1156 
1157   // Aligning block comments in macros.
1158   verifyGoogleFormat("#define A        \\\n"
1159                      "  int i;   /*a*/ \\\n"
1160                      "  int jjj; /*b*/");
1161 }
1162 
TEST_F(FormatTest,AlignsBlockComments)1163 TEST_F(FormatTest, AlignsBlockComments) {
1164   EXPECT_EQ("/*\n"
1165             " * Really multi-line\n"
1166             " * comment.\n"
1167             " */\n"
1168             "void f() {}",
1169             format("  /*\n"
1170                    "   * Really multi-line\n"
1171                    "   * comment.\n"
1172                    "   */\n"
1173                    "  void f() {}"));
1174   EXPECT_EQ("class C {\n"
1175             "  /*\n"
1176             "   * Another multi-line\n"
1177             "   * comment.\n"
1178             "   */\n"
1179             "  void f() {}\n"
1180             "};",
1181             format("class C {\n"
1182                    "/*\n"
1183                    " * Another multi-line\n"
1184                    " * comment.\n"
1185                    " */\n"
1186                    "void f() {}\n"
1187                    "};"));
1188   EXPECT_EQ("/*\n"
1189             "  1. This is a comment with non-trivial formatting.\n"
1190             "     1.1. We have to indent/outdent all lines equally\n"
1191             "         1.1.1. to keep the formatting.\n"
1192             " */",
1193             format("  /*\n"
1194                    "    1. This is a comment with non-trivial formatting.\n"
1195                    "       1.1. We have to indent/outdent all lines equally\n"
1196                    "           1.1.1. to keep the formatting.\n"
1197                    "   */"));
1198   EXPECT_EQ("/*\n"
1199             "Don't try to outdent if there's not enough indentation.\n"
1200             "*/",
1201             format("  /*\n"
1202                    " Don't try to outdent if there's not enough indentation.\n"
1203                    " */"));
1204 
1205   EXPECT_EQ("int i; /* Comment with empty...\n"
1206             "        *\n"
1207             "        * line. */",
1208             format("int i; /* Comment with empty...\n"
1209                    "        *\n"
1210                    "        * line. */"));
1211   EXPECT_EQ("int foobar = 0; /* comment */\n"
1212             "int bar = 0;    /* multiline\n"
1213             "                   comment 1 */\n"
1214             "int baz = 0;    /* multiline\n"
1215             "                   comment 2 */\n"
1216             "int bzz = 0;    /* multiline\n"
1217             "                   comment 3 */",
1218             format("int foobar = 0; /* comment */\n"
1219                    "int bar = 0;    /* multiline\n"
1220                    "                   comment 1 */\n"
1221                    "int baz = 0; /* multiline\n"
1222                    "                comment 2 */\n"
1223                    "int bzz = 0;         /* multiline\n"
1224                    "                        comment 3 */"));
1225   EXPECT_EQ("int foobar = 0; /* comment */\n"
1226             "int bar = 0;    /* multiline\n"
1227             "   comment */\n"
1228             "int baz = 0;    /* multiline\n"
1229             "comment */",
1230             format("int foobar = 0; /* comment */\n"
1231                    "int bar = 0; /* multiline\n"
1232                    "comment */\n"
1233                    "int baz = 0;        /* multiline\n"
1234                    "comment */"));
1235 }
1236 
TEST_F(FormatTest,CommentReflowingCanBeTurnedOff)1237 TEST_F(FormatTest, CommentReflowingCanBeTurnedOff) {
1238   FormatStyle Style = getLLVMStyleWithColumns(20);
1239   Style.ReflowComments = false;
1240   verifyFormat("// aaaaaaaaa aaaaaaaaaa aaaaaaaaaa", Style);
1241   verifyFormat("/* aaaaaaaaa aaaaaaaaaa aaaaaaaaaa */", Style);
1242 }
1243 
TEST_F(FormatTest,CorrectlyHandlesLengthOfBlockComments)1244 TEST_F(FormatTest, CorrectlyHandlesLengthOfBlockComments) {
1245   EXPECT_EQ("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1246             "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */",
1247             format("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1248                    "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */"));
1249   EXPECT_EQ(
1250       "void ffffffffffff(\n"
1251       "    int aaaaaaaa, int bbbbbbbb,\n"
1252       "    int cccccccccccc) { /*\n"
1253       "                           aaaaaaaaaa\n"
1254       "                           aaaaaaaaaaaaa\n"
1255       "                           bbbbbbbbbbbbbb\n"
1256       "                           bbbbbbbbbb\n"
1257       "                         */\n"
1258       "}",
1259       format("void ffffffffffff(int aaaaaaaa, int bbbbbbbb, int cccccccccccc)\n"
1260              "{ /*\n"
1261              "     aaaaaaaaaa aaaaaaaaaaaaa\n"
1262              "     bbbbbbbbbbbbbb bbbbbbbbbb\n"
1263              "   */\n"
1264              "}",
1265              getLLVMStyleWithColumns(40)));
1266 }
1267 
TEST_F(FormatTest,DontBreakNonTrailingBlockComments)1268 TEST_F(FormatTest, DontBreakNonTrailingBlockComments) {
1269   EXPECT_EQ("void ffffffffff(\n"
1270             "    int aaaaa /* test */);",
1271             format("void ffffffffff(int aaaaa /* test */);",
1272                    getLLVMStyleWithColumns(35)));
1273 }
1274 
TEST_F(FormatTest,SplitsLongCxxComments)1275 TEST_F(FormatTest, SplitsLongCxxComments) {
1276   EXPECT_EQ("// A comment that\n"
1277             "// doesn't fit on\n"
1278             "// one line",
1279             format("// A comment that doesn't fit on one line",
1280                    getLLVMStyleWithColumns(20)));
1281   EXPECT_EQ("/// A comment that\n"
1282             "/// doesn't fit on\n"
1283             "/// one line",
1284             format("/// A comment that doesn't fit on one line",
1285                    getLLVMStyleWithColumns(20)));
1286   EXPECT_EQ("//! A comment that\n"
1287             "//! doesn't fit on\n"
1288             "//! one line",
1289             format("//! A comment that doesn't fit on one line",
1290                    getLLVMStyleWithColumns(20)));
1291   EXPECT_EQ("// a b c d\n"
1292             "// e f  g\n"
1293             "// h i j k",
1294             format("// a b c d e f  g h i j k", getLLVMStyleWithColumns(10)));
1295   EXPECT_EQ(
1296       "// a b c d\n"
1297       "// e f  g\n"
1298       "// h i j k",
1299       format("\\\n// a b c d e f  g h i j k", getLLVMStyleWithColumns(10)));
1300   EXPECT_EQ("if (true) // A comment that\n"
1301             "          // doesn't fit on\n"
1302             "          // one line",
1303             format("if (true) // A comment that doesn't fit on one line   ",
1304                    getLLVMStyleWithColumns(30)));
1305   EXPECT_EQ("//    Don't_touch_leading_whitespace",
1306             format("//    Don't_touch_leading_whitespace",
1307                    getLLVMStyleWithColumns(20)));
1308   EXPECT_EQ("// Add leading\n"
1309             "// whitespace",
1310             format("//Add leading whitespace", getLLVMStyleWithColumns(20)));
1311   EXPECT_EQ("/// Add leading\n"
1312             "/// whitespace",
1313             format("///Add leading whitespace", getLLVMStyleWithColumns(20)));
1314   EXPECT_EQ("//! Add leading\n"
1315             "//! whitespace",
1316             format("//!Add leading whitespace", getLLVMStyleWithColumns(20)));
1317   EXPECT_EQ("// whitespace", format("//whitespace", getLLVMStyle()));
1318   EXPECT_EQ("// Even if it makes the line exceed the column\n"
1319             "// limit",
1320             format("//Even if it makes the line exceed the column limit",
1321                    getLLVMStyleWithColumns(51)));
1322   EXPECT_EQ("//--But not here", format("//--But not here", getLLVMStyle()));
1323 
1324   EXPECT_EQ("// aa bb cc dd",
1325             format("// aa bb             cc dd                   ",
1326                    getLLVMStyleWithColumns(15)));
1327 
1328   EXPECT_EQ("// A comment before\n"
1329             "// a macro\n"
1330             "// definition\n"
1331             "#define a b",
1332             format("// A comment before a macro definition\n"
1333                    "#define a b",
1334                    getLLVMStyleWithColumns(20)));
1335   EXPECT_EQ("void ffffff(\n"
1336             "    int aaaaaaaaa,  // wwww\n"
1337             "    int bbbbbbbbbb, // xxxxxxx\n"
1338             "                    // yyyyyyyyyy\n"
1339             "    int c, int d, int e) {}",
1340             format("void ffffff(\n"
1341                    "    int aaaaaaaaa, // wwww\n"
1342                    "    int bbbbbbbbbb, // xxxxxxx yyyyyyyyyy\n"
1343                    "    int c, int d, int e) {}",
1344                    getLLVMStyleWithColumns(40)));
1345   EXPECT_EQ("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1346             format("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1347                    getLLVMStyleWithColumns(20)));
1348   EXPECT_EQ(
1349       "#define XXX // a b c d\n"
1350       "            // e f g h",
1351       format("#define XXX // a b c d e f g h", getLLVMStyleWithColumns(22)));
1352   EXPECT_EQ(
1353       "#define XXX // q w e r\n"
1354       "            // t y u i",
1355       format("#define XXX //q w e r t y u i", getLLVMStyleWithColumns(22)));
1356 }
1357 
TEST_F(FormatTest,PreservesHangingIndentInCxxComments)1358 TEST_F(FormatTest, PreservesHangingIndentInCxxComments) {
1359   EXPECT_EQ("//     A comment\n"
1360             "//     that doesn't\n"
1361             "//     fit on one\n"
1362             "//     line",
1363             format("//     A comment that doesn't fit on one line",
1364                    getLLVMStyleWithColumns(20)));
1365   EXPECT_EQ("///     A comment\n"
1366             "///     that doesn't\n"
1367             "///     fit on one\n"
1368             "///     line",
1369             format("///     A comment that doesn't fit on one line",
1370                    getLLVMStyleWithColumns(20)));
1371 }
1372 
TEST_F(FormatTest,DontSplitLineCommentsWithEscapedNewlines)1373 TEST_F(FormatTest, DontSplitLineCommentsWithEscapedNewlines) {
1374   EXPECT_EQ("// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1375             "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1376             "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1377             format("// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1378                    "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1379                    "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
1380   EXPECT_EQ("int a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1381             "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1382             "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1383             format("int a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1384                    "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1385                    "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1386                    getLLVMStyleWithColumns(50)));
1387   // FIXME: One day we might want to implement adjustment of leading whitespace
1388   // of the consecutive lines in this kind of comment:
1389   EXPECT_EQ("double\n"
1390             "    a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1391             "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1392             "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1393             format("double a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1394                    "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1395                    "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1396                    getLLVMStyleWithColumns(49)));
1397 }
1398 
TEST_F(FormatTest,DontSplitLineCommentsWithPragmas)1399 TEST_F(FormatTest, DontSplitLineCommentsWithPragmas) {
1400   FormatStyle Pragmas = getLLVMStyleWithColumns(30);
1401   Pragmas.CommentPragmas = "^ IWYU pragma:";
1402   EXPECT_EQ(
1403       "// IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb",
1404       format("// IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb", Pragmas));
1405   EXPECT_EQ(
1406       "/* IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb */",
1407       format("/* IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb */", Pragmas));
1408 }
1409 
TEST_F(FormatTest,PriorityOfCommentBreaking)1410 TEST_F(FormatTest, PriorityOfCommentBreaking) {
1411   EXPECT_EQ("if (xxx ==\n"
1412             "        yyy && // aaaaaaaaaaaa bbbbbbbbb\n"
1413             "    zzz)\n"
1414             "  q();",
1415             format("if (xxx == yyy && // aaaaaaaaaaaa bbbbbbbbb\n"
1416                    "    zzz) q();",
1417                    getLLVMStyleWithColumns(40)));
1418   EXPECT_EQ("if (xxxxxxxxxx ==\n"
1419             "        yyy && // aaaaaa bbbbbbbb cccc\n"
1420             "    zzz)\n"
1421             "  q();",
1422             format("if (xxxxxxxxxx == yyy && // aaaaaa bbbbbbbb cccc\n"
1423                    "    zzz) q();",
1424                    getLLVMStyleWithColumns(40)));
1425   EXPECT_EQ("if (xxxxxxxxxx &&\n"
1426             "        yyy || // aaaaaa bbbbbbbb cccc\n"
1427             "    zzz)\n"
1428             "  q();",
1429             format("if (xxxxxxxxxx && yyy || // aaaaaa bbbbbbbb cccc\n"
1430                    "    zzz) q();",
1431                    getLLVMStyleWithColumns(40)));
1432   EXPECT_EQ("fffffffff(\n"
1433             "    &xxx, // aaaaaaaaaaaa bbbbbbbbbbb\n"
1434             "    zzz);",
1435             format("fffffffff(&xxx, // aaaaaaaaaaaa bbbbbbbbbbb\n"
1436                    " zzz);",
1437                    getLLVMStyleWithColumns(40)));
1438 }
1439 
TEST_F(FormatTest,MultiLineCommentsInDefines)1440 TEST_F(FormatTest, MultiLineCommentsInDefines) {
1441   EXPECT_EQ("#define A(x) /* \\\n"
1442             "  a comment     \\\n"
1443             "  inside */     \\\n"
1444             "  f();",
1445             format("#define A(x) /* \\\n"
1446                    "  a comment     \\\n"
1447                    "  inside */     \\\n"
1448                    "  f();",
1449                    getLLVMStyleWithColumns(17)));
1450   EXPECT_EQ("#define A(      \\\n"
1451             "    x) /*       \\\n"
1452             "  a comment     \\\n"
1453             "  inside */     \\\n"
1454             "  f();",
1455             format("#define A(      \\\n"
1456                    "    x) /*       \\\n"
1457                    "  a comment     \\\n"
1458                    "  inside */     \\\n"
1459                    "  f();",
1460                    getLLVMStyleWithColumns(17)));
1461 }
1462 
TEST_F(FormatTest,ParsesCommentsAdjacentToPPDirectives)1463 TEST_F(FormatTest, ParsesCommentsAdjacentToPPDirectives) {
1464   EXPECT_EQ("namespace {}\n// Test\n#define A",
1465             format("namespace {}\n   // Test\n#define A"));
1466   EXPECT_EQ("namespace {}\n/* Test */\n#define A",
1467             format("namespace {}\n   /* Test */\n#define A"));
1468   EXPECT_EQ("namespace {}\n/* Test */ #define A",
1469             format("namespace {}\n   /* Test */    #define A"));
1470 }
1471 
TEST_F(FormatTest,SplitsLongLinesInComments)1472 TEST_F(FormatTest, SplitsLongLinesInComments) {
1473   EXPECT_EQ("/* This is a long\n"
1474             " * comment that\n"
1475             " * doesn't\n"
1476             " * fit on one line.\n"
1477             " */",
1478             format("/* "
1479                    "This is a long                                         "
1480                    "comment that "
1481                    "doesn't                                    "
1482                    "fit on one line.  */",
1483                    getLLVMStyleWithColumns(20)));
1484   EXPECT_EQ(
1485       "/* a b c d\n"
1486       " * e f  g\n"
1487       " * h i j k\n"
1488       " */",
1489       format("/* a b c d e f  g h i j k */", getLLVMStyleWithColumns(10)));
1490   EXPECT_EQ(
1491       "/* a b c d\n"
1492       " * e f  g\n"
1493       " * h i j k\n"
1494       " */",
1495       format("\\\n/* a b c d e f  g h i j k */", getLLVMStyleWithColumns(10)));
1496   EXPECT_EQ("/*\n"
1497             "This is a long\n"
1498             "comment that doesn't\n"
1499             "fit on one line.\n"
1500             "*/",
1501             format("/*\n"
1502                    "This is a long                                         "
1503                    "comment that doesn't                                    "
1504                    "fit on one line.                                      \n"
1505                    "*/",
1506                    getLLVMStyleWithColumns(20)));
1507   EXPECT_EQ("/*\n"
1508             " * This is a long\n"
1509             " * comment that\n"
1510             " * doesn't fit on\n"
1511             " * one line.\n"
1512             " */",
1513             format("/*      \n"
1514                    " * This is a long "
1515                    "   comment that     "
1516                    "   doesn't fit on   "
1517                    "   one line.                                            \n"
1518                    " */",
1519                    getLLVMStyleWithColumns(20)));
1520   EXPECT_EQ("/*\n"
1521             " * This_is_a_comment_with_words_that_dont_fit_on_one_line\n"
1522             " * so_it_should_be_broken\n"
1523             " * wherever_a_space_occurs\n"
1524             " */",
1525             format("/*\n"
1526                    " * This_is_a_comment_with_words_that_dont_fit_on_one_line "
1527                    "   so_it_should_be_broken "
1528                    "   wherever_a_space_occurs                             \n"
1529                    " */",
1530                    getLLVMStyleWithColumns(20)));
1531   EXPECT_EQ("/*\n"
1532             " *    This_comment_can_not_be_broken_into_lines\n"
1533             " */",
1534             format("/*\n"
1535                    " *    This_comment_can_not_be_broken_into_lines\n"
1536                    " */",
1537                    getLLVMStyleWithColumns(20)));
1538   EXPECT_EQ("{\n"
1539             "  /*\n"
1540             "  This is another\n"
1541             "  long comment that\n"
1542             "  doesn't fit on one\n"
1543             "  line    1234567890\n"
1544             "  */\n"
1545             "}",
1546             format("{\n"
1547                    "/*\n"
1548                    "This is another     "
1549                    "  long comment that "
1550                    "  doesn't fit on one"
1551                    "  line    1234567890\n"
1552                    "*/\n"
1553                    "}",
1554                    getLLVMStyleWithColumns(20)));
1555   EXPECT_EQ("{\n"
1556             "  /*\n"
1557             "   * This        i s\n"
1558             "   * another comment\n"
1559             "   * t hat  doesn' t\n"
1560             "   * fit on one l i\n"
1561             "   * n e\n"
1562             "   */\n"
1563             "}",
1564             format("{\n"
1565                    "/*\n"
1566                    " * This        i s"
1567                    "   another comment"
1568                    "   t hat  doesn' t"
1569                    "   fit on one l i"
1570                    "   n e\n"
1571                    " */\n"
1572                    "}",
1573                    getLLVMStyleWithColumns(20)));
1574   EXPECT_EQ("/*\n"
1575             " * This is a long\n"
1576             " * comment that\n"
1577             " * doesn't fit on\n"
1578             " * one line\n"
1579             " */",
1580             format("   /*\n"
1581                    "    * This is a long comment that doesn't fit on one line\n"
1582                    "    */",
1583                    getLLVMStyleWithColumns(20)));
1584   EXPECT_EQ("{\n"
1585             "  if (something) /* This is a\n"
1586             "                    long\n"
1587             "                    comment */\n"
1588             "    ;\n"
1589             "}",
1590             format("{\n"
1591                    "  if (something) /* This is a long comment */\n"
1592                    "    ;\n"
1593                    "}",
1594                    getLLVMStyleWithColumns(30)));
1595 
1596   EXPECT_EQ("/* A comment before\n"
1597             " * a macro\n"
1598             " * definition */\n"
1599             "#define a b",
1600             format("/* A comment before a macro definition */\n"
1601                    "#define a b",
1602                    getLLVMStyleWithColumns(20)));
1603 
1604   EXPECT_EQ("/* some comment\n"
1605             "     *   a comment\n"
1606             "* that we break\n"
1607             " * another comment\n"
1608             "* we have to break\n"
1609             "* a left comment\n"
1610             " */",
1611             format("  /* some comment\n"
1612                    "       *   a comment that we break\n"
1613                    "   * another comment we have to break\n"
1614                    "* a left comment\n"
1615                    "   */",
1616                    getLLVMStyleWithColumns(20)));
1617 
1618   EXPECT_EQ("/**\n"
1619             " * multiline block\n"
1620             " * comment\n"
1621             " *\n"
1622             " */",
1623             format("/**\n"
1624                    " * multiline block comment\n"
1625                    " *\n"
1626                    " */",
1627                    getLLVMStyleWithColumns(20)));
1628 
1629   EXPECT_EQ("/*\n"
1630             "\n"
1631             "\n"
1632             "    */\n",
1633             format("  /*       \n"
1634                    "      \n"
1635                    "               \n"
1636                    "      */\n"));
1637 
1638   EXPECT_EQ("/* a a */",
1639             format("/* a a            */", getLLVMStyleWithColumns(15)));
1640   EXPECT_EQ("/* a a bc  */",
1641             format("/* a a            bc  */", getLLVMStyleWithColumns(15)));
1642   EXPECT_EQ("/* aaa aaa\n"
1643             " * aaaaa */",
1644             format("/* aaa aaa aaaaa       */", getLLVMStyleWithColumns(15)));
1645   EXPECT_EQ("/* aaa aaa\n"
1646             " * aaaaa     */",
1647             format("/* aaa aaa aaaaa     */", getLLVMStyleWithColumns(15)));
1648 }
1649 
TEST_F(FormatTest,SplitsLongLinesInCommentsInPreprocessor)1650 TEST_F(FormatTest, SplitsLongLinesInCommentsInPreprocessor) {
1651   EXPECT_EQ("#define X          \\\n"
1652             "  /*               \\\n"
1653             "   Test            \\\n"
1654             "   Macro comment   \\\n"
1655             "   with a long     \\\n"
1656             "   line            \\\n"
1657             "   */              \\\n"
1658             "  A + B",
1659             format("#define X \\\n"
1660                    "  /*\n"
1661                    "   Test\n"
1662                    "   Macro comment with a long  line\n"
1663                    "   */ \\\n"
1664                    "  A + B",
1665                    getLLVMStyleWithColumns(20)));
1666   EXPECT_EQ("#define X          \\\n"
1667             "  /* Macro comment \\\n"
1668             "     with a long   \\\n"
1669             "     line */       \\\n"
1670             "  A + B",
1671             format("#define X \\\n"
1672                    "  /* Macro comment with a long\n"
1673                    "     line */ \\\n"
1674                    "  A + B",
1675                    getLLVMStyleWithColumns(20)));
1676   EXPECT_EQ("#define X          \\\n"
1677             "  /* Macro comment \\\n"
1678             "   * with a long   \\\n"
1679             "   * line */       \\\n"
1680             "  A + B",
1681             format("#define X \\\n"
1682                    "  /* Macro comment with a long  line */ \\\n"
1683                    "  A + B",
1684                    getLLVMStyleWithColumns(20)));
1685 }
1686 
TEST_F(FormatTest,CommentsInStaticInitializers)1687 TEST_F(FormatTest, CommentsInStaticInitializers) {
1688   EXPECT_EQ(
1689       "static SomeType type = {aaaaaaaaaaaaaaaaaaaa, /* comment */\n"
1690       "                        aaaaaaaaaaaaaaaaaaaa /* comment */,\n"
1691       "                        /* comment */ aaaaaaaaaaaaaaaaaaaa,\n"
1692       "                        aaaaaaaaaaaaaaaaaaaa, // comment\n"
1693       "                        aaaaaaaaaaaaaaaaaaaa};",
1694       format("static SomeType type = { aaaaaaaaaaaaaaaaaaaa  ,  /* comment */\n"
1695              "                   aaaaaaaaaaaaaaaaaaaa   /* comment */ ,\n"
1696              "                     /* comment */   aaaaaaaaaaaaaaaaaaaa ,\n"
1697              "              aaaaaaaaaaaaaaaaaaaa ,   // comment\n"
1698              "                  aaaaaaaaaaaaaaaaaaaa };"));
1699   verifyFormat("static SomeType type = {aaaaaaaaaaa, // comment for aa...\n"
1700                "                        bbbbbbbbbbb, ccccccccccc};");
1701   verifyFormat("static SomeType type = {aaaaaaaaaaa,\n"
1702                "                        // comment for bb....\n"
1703                "                        bbbbbbbbbbb, ccccccccccc};");
1704   verifyGoogleFormat(
1705       "static SomeType type = {aaaaaaaaaaa,  // comment for aa...\n"
1706       "                        bbbbbbbbbbb, ccccccccccc};");
1707   verifyGoogleFormat("static SomeType type = {aaaaaaaaaaa,\n"
1708                      "                        // comment for bb....\n"
1709                      "                        bbbbbbbbbbb, ccccccccccc};");
1710 
1711   verifyFormat("S s = {{a, b, c},  // Group #1\n"
1712                "       {d, e, f},  // Group #2\n"
1713                "       {g, h, i}}; // Group #3");
1714   verifyFormat("S s = {{// Group #1\n"
1715                "        a, b, c},\n"
1716                "       {// Group #2\n"
1717                "        d, e, f},\n"
1718                "       {// Group #3\n"
1719                "        g, h, i}};");
1720 
1721   EXPECT_EQ("S s = {\n"
1722             "    // Some comment\n"
1723             "    a,\n"
1724             "\n"
1725             "    // Comment after empty line\n"
1726             "    b}",
1727             format("S s =    {\n"
1728                    "      // Some comment\n"
1729                    "  a,\n"
1730                    "  \n"
1731                    "     // Comment after empty line\n"
1732                    "      b\n"
1733                    "}"));
1734   EXPECT_EQ("S s = {\n"
1735             "    /* Some comment */\n"
1736             "    a,\n"
1737             "\n"
1738             "    /* Comment after empty line */\n"
1739             "    b}",
1740             format("S s =    {\n"
1741                    "      /* Some comment */\n"
1742                    "  a,\n"
1743                    "  \n"
1744                    "     /* Comment after empty line */\n"
1745                    "      b\n"
1746                    "}"));
1747   verifyFormat("const uint8_t aaaaaaaaaaaaaaaaaaaaaa[0] = {\n"
1748                "    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1749                "    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1750                "    0x00, 0x00, 0x00, 0x00};            // comment\n");
1751 }
1752 
TEST_F(FormatTest,IgnoresIf0Contents)1753 TEST_F(FormatTest, IgnoresIf0Contents) {
1754   EXPECT_EQ("#if 0\n"
1755             "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1756             "#endif\n"
1757             "void f() {}",
1758             format("#if 0\n"
1759                    "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1760                    "#endif\n"
1761                    "void f(  ) {  }"));
1762   EXPECT_EQ("#if false\n"
1763             "void f(  ) {  }\n"
1764             "#endif\n"
1765             "void g() {}\n",
1766             format("#if false\n"
1767                    "void f(  ) {  }\n"
1768                    "#endif\n"
1769                    "void g(  ) {  }\n"));
1770   EXPECT_EQ("enum E {\n"
1771             "  One,\n"
1772             "  Two,\n"
1773             "#if 0\n"
1774             "Three,\n"
1775             "      Four,\n"
1776             "#endif\n"
1777             "  Five\n"
1778             "};",
1779             format("enum E {\n"
1780                    "  One,Two,\n"
1781                    "#if 0\n"
1782                    "Three,\n"
1783                    "      Four,\n"
1784                    "#endif\n"
1785                    "  Five};"));
1786   EXPECT_EQ("enum F {\n"
1787             "  One,\n"
1788             "#if 1\n"
1789             "  Two,\n"
1790             "#if 0\n"
1791             "Three,\n"
1792             "      Four,\n"
1793             "#endif\n"
1794             "  Five\n"
1795             "#endif\n"
1796             "};",
1797             format("enum F {\n"
1798                    "One,\n"
1799                    "#if 1\n"
1800                    "Two,\n"
1801                    "#if 0\n"
1802                    "Three,\n"
1803                    "      Four,\n"
1804                    "#endif\n"
1805                    "Five\n"
1806                    "#endif\n"
1807                    "};"));
1808   EXPECT_EQ("enum G {\n"
1809             "  One,\n"
1810             "#if 0\n"
1811             "Two,\n"
1812             "#else\n"
1813             "  Three,\n"
1814             "#endif\n"
1815             "  Four\n"
1816             "};",
1817             format("enum G {\n"
1818                    "One,\n"
1819                    "#if 0\n"
1820                    "Two,\n"
1821                    "#else\n"
1822                    "Three,\n"
1823                    "#endif\n"
1824                    "Four\n"
1825                    "};"));
1826   EXPECT_EQ("enum H {\n"
1827             "  One,\n"
1828             "#if 0\n"
1829             "#ifdef Q\n"
1830             "Two,\n"
1831             "#else\n"
1832             "Three,\n"
1833             "#endif\n"
1834             "#endif\n"
1835             "  Four\n"
1836             "};",
1837             format("enum H {\n"
1838                    "One,\n"
1839                    "#if 0\n"
1840                    "#ifdef Q\n"
1841                    "Two,\n"
1842                    "#else\n"
1843                    "Three,\n"
1844                    "#endif\n"
1845                    "#endif\n"
1846                    "Four\n"
1847                    "};"));
1848   EXPECT_EQ("enum I {\n"
1849             "  One,\n"
1850             "#if /* test */ 0 || 1\n"
1851             "Two,\n"
1852             "Three,\n"
1853             "#endif\n"
1854             "  Four\n"
1855             "};",
1856             format("enum I {\n"
1857                    "One,\n"
1858                    "#if /* test */ 0 || 1\n"
1859                    "Two,\n"
1860                    "Three,\n"
1861                    "#endif\n"
1862                    "Four\n"
1863                    "};"));
1864   EXPECT_EQ("enum J {\n"
1865             "  One,\n"
1866             "#if 0\n"
1867             "#if 0\n"
1868             "Two,\n"
1869             "#else\n"
1870             "Three,\n"
1871             "#endif\n"
1872             "Four,\n"
1873             "#endif\n"
1874             "  Five\n"
1875             "};",
1876             format("enum J {\n"
1877                    "One,\n"
1878                    "#if 0\n"
1879                    "#if 0\n"
1880                    "Two,\n"
1881                    "#else\n"
1882                    "Three,\n"
1883                    "#endif\n"
1884                    "Four,\n"
1885                    "#endif\n"
1886                    "Five\n"
1887                    "};"));
1888 }
1889 
1890 //===----------------------------------------------------------------------===//
1891 // Tests for classes, namespaces, etc.
1892 //===----------------------------------------------------------------------===//
1893 
TEST_F(FormatTest,DoesNotBreakSemiAfterClassDecl)1894 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1895   verifyFormat("class A {};");
1896 }
1897 
TEST_F(FormatTest,UnderstandsAccessSpecifiers)1898 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1899   verifyFormat("class A {\n"
1900                "public:\n"
1901                "public: // comment\n"
1902                "protected:\n"
1903                "private:\n"
1904                "  void f() {}\n"
1905                "};");
1906   verifyGoogleFormat("class A {\n"
1907                      " public:\n"
1908                      " protected:\n"
1909                      " private:\n"
1910                      "  void f() {}\n"
1911                      "};");
1912   verifyFormat("class A {\n"
1913                "public slots:\n"
1914                "  void f1() {}\n"
1915                "public Q_SLOTS:\n"
1916                "  void f2() {}\n"
1917                "protected slots:\n"
1918                "  void f3() {}\n"
1919                "protected Q_SLOTS:\n"
1920                "  void f4() {}\n"
1921                "private slots:\n"
1922                "  void f5() {}\n"
1923                "private Q_SLOTS:\n"
1924                "  void f6() {}\n"
1925                "signals:\n"
1926                "  void g1();\n"
1927                "Q_SIGNALS:\n"
1928                "  void g2();\n"
1929                "};");
1930 
1931   // Don't interpret 'signals' the wrong way.
1932   verifyFormat("signals.set();");
1933   verifyFormat("for (Signals signals : f()) {\n}");
1934   verifyFormat("{\n"
1935                "  signals.set(); // This needs indentation.\n"
1936                "}");
1937 }
1938 
TEST_F(FormatTest,SeparatesLogicalBlocks)1939 TEST_F(FormatTest, SeparatesLogicalBlocks) {
1940   EXPECT_EQ("class A {\n"
1941             "public:\n"
1942             "  void f();\n"
1943             "\n"
1944             "private:\n"
1945             "  void g() {}\n"
1946             "  // test\n"
1947             "protected:\n"
1948             "  int h;\n"
1949             "};",
1950             format("class A {\n"
1951                    "public:\n"
1952                    "void f();\n"
1953                    "private:\n"
1954                    "void g() {}\n"
1955                    "// test\n"
1956                    "protected:\n"
1957                    "int h;\n"
1958                    "};"));
1959   EXPECT_EQ("class A {\n"
1960             "protected:\n"
1961             "public:\n"
1962             "  void f();\n"
1963             "};",
1964             format("class A {\n"
1965                    "protected:\n"
1966                    "\n"
1967                    "public:\n"
1968                    "\n"
1969                    "  void f();\n"
1970                    "};"));
1971 
1972   // Even ensure proper spacing inside macros.
1973   EXPECT_EQ("#define B     \\\n"
1974             "  class A {   \\\n"
1975             "   protected: \\\n"
1976             "   public:    \\\n"
1977             "    void f(); \\\n"
1978             "  };",
1979             format("#define B     \\\n"
1980                    "  class A {   \\\n"
1981                    "   protected: \\\n"
1982                    "              \\\n"
1983                    "   public:    \\\n"
1984                    "              \\\n"
1985                    "    void f(); \\\n"
1986                    "  };",
1987                    getGoogleStyle()));
1988   // But don't remove empty lines after macros ending in access specifiers.
1989   EXPECT_EQ("#define A private:\n"
1990             "\n"
1991             "int i;",
1992             format("#define A         private:\n"
1993                    "\n"
1994                    "int              i;"));
1995 }
1996 
TEST_F(FormatTest,FormatsClasses)1997 TEST_F(FormatTest, FormatsClasses) {
1998   verifyFormat("class A : public B {};");
1999   verifyFormat("class A : public ::B {};");
2000 
2001   verifyFormat(
2002       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
2003       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
2004   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
2005                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
2006                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
2007   verifyFormat(
2008       "class A : public B, public C, public D, public E, public F {};");
2009   verifyFormat("class AAAAAAAAAAAA : public B,\n"
2010                "                     public C,\n"
2011                "                     public D,\n"
2012                "                     public E,\n"
2013                "                     public F,\n"
2014                "                     public G {};");
2015 
2016   verifyFormat("class\n"
2017                "    ReallyReallyLongClassName {\n"
2018                "  int i;\n"
2019                "};",
2020                getLLVMStyleWithColumns(32));
2021   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
2022                "                           aaaaaaaaaaaaaaaa> {};");
2023   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
2024                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
2025                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
2026   verifyFormat("template <class R, class C>\n"
2027                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
2028                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
2029   verifyFormat("class ::A::B {};");
2030 }
2031 
TEST_F(FormatTest,FormatsVariableDeclarationsAfterStructOrClass)2032 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
2033   verifyFormat("class A {\n} a, b;");
2034   verifyFormat("struct A {\n} a, b;");
2035   verifyFormat("union A {\n} a;");
2036 }
2037 
TEST_F(FormatTest,FormatsEnum)2038 TEST_F(FormatTest, FormatsEnum) {
2039   verifyFormat("enum {\n"
2040                "  Zero,\n"
2041                "  One = 1,\n"
2042                "  Two = One + 1,\n"
2043                "  Three = (One + Two),\n"
2044                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2045                "  Five = (One, Two, Three, Four, 5)\n"
2046                "};");
2047   verifyGoogleFormat("enum {\n"
2048                      "  Zero,\n"
2049                      "  One = 1,\n"
2050                      "  Two = One + 1,\n"
2051                      "  Three = (One + Two),\n"
2052                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2053                      "  Five = (One, Two, Three, Four, 5)\n"
2054                      "};");
2055   verifyFormat("enum Enum {};");
2056   verifyFormat("enum {};");
2057   verifyFormat("enum X E {} d;");
2058   verifyFormat("enum __attribute__((...)) E {} d;");
2059   verifyFormat("enum __declspec__((...)) E {} d;");
2060   verifyFormat("enum {\n"
2061                "  Bar = Foo<int, int>::value\n"
2062                "};",
2063                getLLVMStyleWithColumns(30));
2064 
2065   verifyFormat("enum ShortEnum { A, B, C };");
2066   verifyGoogleFormat("enum ShortEnum { A, B, C };");
2067 
2068   EXPECT_EQ("enum KeepEmptyLines {\n"
2069             "  ONE,\n"
2070             "\n"
2071             "  TWO,\n"
2072             "\n"
2073             "  THREE\n"
2074             "}",
2075             format("enum KeepEmptyLines {\n"
2076                    "  ONE,\n"
2077                    "\n"
2078                    "  TWO,\n"
2079                    "\n"
2080                    "\n"
2081                    "  THREE\n"
2082                    "}"));
2083   verifyFormat("enum E { // comment\n"
2084                "  ONE,\n"
2085                "  TWO\n"
2086                "};\n"
2087                "int i;");
2088   // Not enums.
2089   verifyFormat("enum X f() {\n"
2090                "  a();\n"
2091                "  return 42;\n"
2092                "}");
2093   verifyFormat("enum X Type::f() {\n"
2094                "  a();\n"
2095                "  return 42;\n"
2096                "}");
2097   verifyFormat("enum ::X f() {\n"
2098                "  a();\n"
2099                "  return 42;\n"
2100                "}");
2101   verifyFormat("enum ns::X f() {\n"
2102                "  a();\n"
2103                "  return 42;\n"
2104                "}");
2105 }
2106 
TEST_F(FormatTest,FormatsEnumsWithErrors)2107 TEST_F(FormatTest, FormatsEnumsWithErrors) {
2108   verifyFormat("enum Type {\n"
2109                "  One = 0; // These semicolons should be commas.\n"
2110                "  Two = 1;\n"
2111                "};");
2112   verifyFormat("namespace n {\n"
2113                "enum Type {\n"
2114                "  One,\n"
2115                "  Two, // missing };\n"
2116                "  int i;\n"
2117                "}\n"
2118                "void g() {}");
2119 }
2120 
TEST_F(FormatTest,FormatsEnumStruct)2121 TEST_F(FormatTest, FormatsEnumStruct) {
2122   verifyFormat("enum struct {\n"
2123                "  Zero,\n"
2124                "  One = 1,\n"
2125                "  Two = One + 1,\n"
2126                "  Three = (One + Two),\n"
2127                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2128                "  Five = (One, Two, Three, Four, 5)\n"
2129                "};");
2130   verifyFormat("enum struct Enum {};");
2131   verifyFormat("enum struct {};");
2132   verifyFormat("enum struct X E {} d;");
2133   verifyFormat("enum struct __attribute__((...)) E {} d;");
2134   verifyFormat("enum struct __declspec__((...)) E {} d;");
2135   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
2136 }
2137 
TEST_F(FormatTest,FormatsEnumClass)2138 TEST_F(FormatTest, FormatsEnumClass) {
2139   verifyFormat("enum class {\n"
2140                "  Zero,\n"
2141                "  One = 1,\n"
2142                "  Two = One + 1,\n"
2143                "  Three = (One + Two),\n"
2144                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2145                "  Five = (One, Two, Three, Four, 5)\n"
2146                "};");
2147   verifyFormat("enum class Enum {};");
2148   verifyFormat("enum class {};");
2149   verifyFormat("enum class X E {} d;");
2150   verifyFormat("enum class __attribute__((...)) E {} d;");
2151   verifyFormat("enum class __declspec__((...)) E {} d;");
2152   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
2153 }
2154 
TEST_F(FormatTest,FormatsEnumTypes)2155 TEST_F(FormatTest, FormatsEnumTypes) {
2156   verifyFormat("enum X : int {\n"
2157                "  A, // Force multiple lines.\n"
2158                "  B\n"
2159                "};");
2160   verifyFormat("enum X : int { A, B };");
2161   verifyFormat("enum X : std::uint32_t { A, B };");
2162 }
2163 
TEST_F(FormatTest,FormatsNSEnums)2164 TEST_F(FormatTest, FormatsNSEnums) {
2165   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
2166   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
2167                      "  // Information about someDecentlyLongValue.\n"
2168                      "  someDecentlyLongValue,\n"
2169                      "  // Information about anotherDecentlyLongValue.\n"
2170                      "  anotherDecentlyLongValue,\n"
2171                      "  // Information about aThirdDecentlyLongValue.\n"
2172                      "  aThirdDecentlyLongValue\n"
2173                      "};");
2174   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
2175                      "  a = 1,\n"
2176                      "  b = 2,\n"
2177                      "  c = 3,\n"
2178                      "};");
2179   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
2180                      "  a = 1,\n"
2181                      "  b = 2,\n"
2182                      "  c = 3,\n"
2183                      "};");
2184   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
2185                      "  a = 1,\n"
2186                      "  b = 2,\n"
2187                      "  c = 3,\n"
2188                      "};");
2189 }
2190 
TEST_F(FormatTest,FormatsBitfields)2191 TEST_F(FormatTest, FormatsBitfields) {
2192   verifyFormat("struct Bitfields {\n"
2193                "  unsigned sClass : 8;\n"
2194                "  unsigned ValueKind : 2;\n"
2195                "};");
2196   verifyFormat("struct A {\n"
2197                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
2198                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
2199                "};");
2200   verifyFormat("struct MyStruct {\n"
2201                "  uchar data;\n"
2202                "  uchar : 8;\n"
2203                "  uchar : 8;\n"
2204                "  uchar other;\n"
2205                "};");
2206 }
2207 
TEST_F(FormatTest,FormatsNamespaces)2208 TEST_F(FormatTest, FormatsNamespaces) {
2209   verifyFormat("namespace some_namespace {\n"
2210                "class A {};\n"
2211                "void f() { f(); }\n"
2212                "}");
2213   verifyFormat("namespace {\n"
2214                "class A {};\n"
2215                "void f() { f(); }\n"
2216                "}");
2217   verifyFormat("inline namespace X {\n"
2218                "class A {};\n"
2219                "void f() { f(); }\n"
2220                "}");
2221   verifyFormat("using namespace some_namespace;\n"
2222                "class A {};\n"
2223                "void f() { f(); }");
2224 
2225   // This code is more common than we thought; if we
2226   // layout this correctly the semicolon will go into
2227   // its own line, which is undesirable.
2228   verifyFormat("namespace {};");
2229   verifyFormat("namespace {\n"
2230                "class A {};\n"
2231                "};");
2232 
2233   verifyFormat("namespace {\n"
2234                "int SomeVariable = 0; // comment\n"
2235                "} // namespace");
2236   EXPECT_EQ("#ifndef HEADER_GUARD\n"
2237             "#define HEADER_GUARD\n"
2238             "namespace my_namespace {\n"
2239             "int i;\n"
2240             "} // my_namespace\n"
2241             "#endif // HEADER_GUARD",
2242             format("#ifndef HEADER_GUARD\n"
2243                    " #define HEADER_GUARD\n"
2244                    "   namespace my_namespace {\n"
2245                    "int i;\n"
2246                    "}    // my_namespace\n"
2247                    "#endif    // HEADER_GUARD"));
2248 
2249   EXPECT_EQ("namespace A::B {\n"
2250             "class C {};\n"
2251             "}",
2252             format("namespace A::B {\n"
2253                    "class C {};\n"
2254                    "}"));
2255 
2256   FormatStyle Style = getLLVMStyle();
2257   Style.NamespaceIndentation = FormatStyle::NI_All;
2258   EXPECT_EQ("namespace out {\n"
2259             "  int i;\n"
2260             "  namespace in {\n"
2261             "    int i;\n"
2262             "  } // namespace\n"
2263             "} // namespace",
2264             format("namespace out {\n"
2265                    "int i;\n"
2266                    "namespace in {\n"
2267                    "int i;\n"
2268                    "} // namespace\n"
2269                    "} // namespace",
2270                    Style));
2271 
2272   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2273   EXPECT_EQ("namespace out {\n"
2274             "int i;\n"
2275             "namespace in {\n"
2276             "  int i;\n"
2277             "} // namespace\n"
2278             "} // namespace",
2279             format("namespace out {\n"
2280                    "int i;\n"
2281                    "namespace in {\n"
2282                    "int i;\n"
2283                    "} // namespace\n"
2284                    "} // namespace",
2285                    Style));
2286 }
2287 
TEST_F(FormatTest,FormatsExternC)2288 TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
2289 
TEST_F(FormatTest,FormatsInlineASM)2290 TEST_F(FormatTest, FormatsInlineASM) {
2291   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
2292   verifyFormat("asm(\"nop\" ::: \"memory\");");
2293   verifyFormat(
2294       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
2295       "    \"cpuid\\n\\t\"\n"
2296       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
2297       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
2298       "    : \"a\"(value));");
2299   EXPECT_EQ(
2300       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
2301       "  __asm {\n"
2302       "        mov     edx,[that] // vtable in edx\n"
2303       "        mov     eax,methodIndex\n"
2304       "        call    [edx][eax*4] // stdcall\n"
2305       "  }\n"
2306       "}",
2307       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
2308              "    __asm {\n"
2309              "        mov     edx,[that] // vtable in edx\n"
2310              "        mov     eax,methodIndex\n"
2311              "        call    [edx][eax*4] // stdcall\n"
2312              "    }\n"
2313              "}"));
2314   EXPECT_EQ("_asm {\n"
2315             "  xor eax, eax;\n"
2316             "  cpuid;\n"
2317             "}",
2318             format("_asm {\n"
2319                    "  xor eax, eax;\n"
2320                    "  cpuid;\n"
2321                    "}"));
2322   verifyFormat("void function() {\n"
2323                "  // comment\n"
2324                "  asm(\"\");\n"
2325                "}");
2326   EXPECT_EQ("__asm {\n"
2327             "}\n"
2328             "int i;",
2329             format("__asm   {\n"
2330                    "}\n"
2331                    "int   i;"));
2332 }
2333 
TEST_F(FormatTest,FormatTryCatch)2334 TEST_F(FormatTest, FormatTryCatch) {
2335   verifyFormat("try {\n"
2336                "  throw a * b;\n"
2337                "} catch (int a) {\n"
2338                "  // Do nothing.\n"
2339                "} catch (...) {\n"
2340                "  exit(42);\n"
2341                "}");
2342 
2343   // Function-level try statements.
2344   verifyFormat("int f() try { return 4; } catch (...) {\n"
2345                "  return 5;\n"
2346                "}");
2347   verifyFormat("class A {\n"
2348                "  int a;\n"
2349                "  A() try : a(0) {\n"
2350                "  } catch (...) {\n"
2351                "    throw;\n"
2352                "  }\n"
2353                "};\n");
2354 
2355   // Incomplete try-catch blocks.
2356   verifyIncompleteFormat("try {} catch (");
2357 }
2358 
TEST_F(FormatTest,FormatSEHTryCatch)2359 TEST_F(FormatTest, FormatSEHTryCatch) {
2360   verifyFormat("__try {\n"
2361                "  int a = b * c;\n"
2362                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
2363                "  // Do nothing.\n"
2364                "}");
2365 
2366   verifyFormat("__try {\n"
2367                "  int a = b * c;\n"
2368                "} __finally {\n"
2369                "  // Do nothing.\n"
2370                "}");
2371 
2372   verifyFormat("DEBUG({\n"
2373                "  __try {\n"
2374                "  } __finally {\n"
2375                "  }\n"
2376                "});\n");
2377 }
2378 
TEST_F(FormatTest,IncompleteTryCatchBlocks)2379 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
2380   verifyFormat("try {\n"
2381                "  f();\n"
2382                "} catch {\n"
2383                "  g();\n"
2384                "}");
2385   verifyFormat("try {\n"
2386                "  f();\n"
2387                "} catch (A a) MACRO(x) {\n"
2388                "  g();\n"
2389                "} catch (B b) MACRO(x) {\n"
2390                "  g();\n"
2391                "}");
2392 }
2393 
TEST_F(FormatTest,FormatTryCatchBraceStyles)2394 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
2395   FormatStyle Style = getLLVMStyle();
2396   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
2397                           FormatStyle::BS_WebKit}) {
2398     Style.BreakBeforeBraces = BraceStyle;
2399     verifyFormat("try {\n"
2400                  "  // something\n"
2401                  "} catch (...) {\n"
2402                  "  // something\n"
2403                  "}",
2404                  Style);
2405   }
2406   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
2407   verifyFormat("try {\n"
2408                "  // something\n"
2409                "}\n"
2410                "catch (...) {\n"
2411                "  // something\n"
2412                "}",
2413                Style);
2414   verifyFormat("__try {\n"
2415                "  // something\n"
2416                "}\n"
2417                "__finally {\n"
2418                "  // something\n"
2419                "}",
2420                Style);
2421   verifyFormat("@try {\n"
2422                "  // something\n"
2423                "}\n"
2424                "@finally {\n"
2425                "  // something\n"
2426                "}",
2427                Style);
2428   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
2429   verifyFormat("try\n"
2430                "{\n"
2431                "  // something\n"
2432                "}\n"
2433                "catch (...)\n"
2434                "{\n"
2435                "  // something\n"
2436                "}",
2437                Style);
2438   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2439   verifyFormat("try\n"
2440                "  {\n"
2441                "    // something\n"
2442                "  }\n"
2443                "catch (...)\n"
2444                "  {\n"
2445                "    // something\n"
2446                "  }",
2447                Style);
2448   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2449   Style.BraceWrapping.BeforeCatch = true;
2450   verifyFormat("try {\n"
2451                "  // something\n"
2452                "}\n"
2453                "catch (...) {\n"
2454                "  // something\n"
2455                "}",
2456                Style);
2457 }
2458 
TEST_F(FormatTest,FormatObjCTryCatch)2459 TEST_F(FormatTest, FormatObjCTryCatch) {
2460   verifyFormat("@try {\n"
2461                "  f();\n"
2462                "} @catch (NSException e) {\n"
2463                "  @throw;\n"
2464                "} @finally {\n"
2465                "  exit(42);\n"
2466                "}");
2467   verifyFormat("DEBUG({\n"
2468                "  @try {\n"
2469                "  } @finally {\n"
2470                "  }\n"
2471                "});\n");
2472 }
2473 
TEST_F(FormatTest,FormatObjCAutoreleasepool)2474 TEST_F(FormatTest, FormatObjCAutoreleasepool) {
2475   FormatStyle Style = getLLVMStyle();
2476   verifyFormat("@autoreleasepool {\n"
2477                "  f();\n"
2478                "}\n"
2479                "@autoreleasepool {\n"
2480                "  f();\n"
2481                "}\n",
2482                Style);
2483   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
2484   verifyFormat("@autoreleasepool\n"
2485                "{\n"
2486                "  f();\n"
2487                "}\n"
2488                "@autoreleasepool\n"
2489                "{\n"
2490                "  f();\n"
2491                "}\n",
2492                Style);
2493 }
2494 
TEST_F(FormatTest,StaticInitializers)2495 TEST_F(FormatTest, StaticInitializers) {
2496   verifyFormat("static SomeClass SC = {1, 'a'};");
2497 
2498   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
2499                "    100000000, "
2500                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
2501 
2502   // Here, everything other than the "}" would fit on a line.
2503   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
2504                "    10000000000000000000000000};");
2505   EXPECT_EQ("S s = {a,\n"
2506             "\n"
2507             "       b};",
2508             format("S s = {\n"
2509                    "  a,\n"
2510                    "\n"
2511                    "  b\n"
2512                    "};"));
2513 
2514   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
2515   // line. However, the formatting looks a bit off and this probably doesn't
2516   // happen often in practice.
2517   verifyFormat("static int Variable[1] = {\n"
2518                "    {1000000000000000000000000000000000000}};",
2519                getLLVMStyleWithColumns(40));
2520 }
2521 
TEST_F(FormatTest,DesignatedInitializers)2522 TEST_F(FormatTest, DesignatedInitializers) {
2523   verifyFormat("const struct A a = {.a = 1, .b = 2};");
2524   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
2525                "                    .bbbbbbbbbb = 2,\n"
2526                "                    .cccccccccc = 3,\n"
2527                "                    .dddddddddd = 4,\n"
2528                "                    .eeeeeeeeee = 5};");
2529   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2530                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
2531                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
2532                "    .ccccccccccccccccccccccccccc = 3,\n"
2533                "    .ddddddddddddddddddddddddddd = 4,\n"
2534                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
2535 
2536   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
2537 }
2538 
TEST_F(FormatTest,NestedStaticInitializers)2539 TEST_F(FormatTest, NestedStaticInitializers) {
2540   verifyFormat("static A x = {{{}}};\n");
2541   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
2542                "               {init1, init2, init3, init4}}};",
2543                getLLVMStyleWithColumns(50));
2544 
2545   verifyFormat("somes Status::global_reps[3] = {\n"
2546                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2547                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2548                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
2549                getLLVMStyleWithColumns(60));
2550   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
2551                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2552                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2553                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
2554   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
2555                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
2556                "rect.fTop}};");
2557 
2558   verifyFormat(
2559       "SomeArrayOfSomeType a = {\n"
2560       "    {{1, 2, 3},\n"
2561       "     {1, 2, 3},\n"
2562       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
2563       "      333333333333333333333333333333},\n"
2564       "     {1, 2, 3},\n"
2565       "     {1, 2, 3}}};");
2566   verifyFormat(
2567       "SomeArrayOfSomeType a = {\n"
2568       "    {{1, 2, 3}},\n"
2569       "    {{1, 2, 3}},\n"
2570       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
2571       "      333333333333333333333333333333}},\n"
2572       "    {{1, 2, 3}},\n"
2573       "    {{1, 2, 3}}};");
2574 
2575   verifyFormat("struct {\n"
2576                "  unsigned bit;\n"
2577                "  const char *const name;\n"
2578                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
2579                "                 {kOsWin, \"Windows\"},\n"
2580                "                 {kOsLinux, \"Linux\"},\n"
2581                "                 {kOsCrOS, \"Chrome OS\"}};");
2582   verifyFormat("struct {\n"
2583                "  unsigned bit;\n"
2584                "  const char *const name;\n"
2585                "} kBitsToOs[] = {\n"
2586                "    {kOsMac, \"Mac\"},\n"
2587                "    {kOsWin, \"Windows\"},\n"
2588                "    {kOsLinux, \"Linux\"},\n"
2589                "    {kOsCrOS, \"Chrome OS\"},\n"
2590                "};");
2591 }
2592 
TEST_F(FormatTest,FormatsSmallMacroDefinitionsInSingleLine)2593 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
2594   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
2595                "                      \\\n"
2596                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
2597 }
2598 
TEST_F(FormatTest,DoesNotBreakPureVirtualFunctionDefinition)2599 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
2600   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
2601                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
2602 
2603   // Do break defaulted and deleted functions.
2604   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
2605                "    default;",
2606                getLLVMStyleWithColumns(40));
2607   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
2608                "    delete;",
2609                getLLVMStyleWithColumns(40));
2610 }
2611 
TEST_F(FormatTest,BreaksStringLiteralsOnlyInDefine)2612 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
2613   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
2614                getLLVMStyleWithColumns(40));
2615   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
2616                getLLVMStyleWithColumns(40));
2617   EXPECT_EQ("#define Q                              \\\n"
2618             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
2619             "  \"aaaaaaaa.cpp\"",
2620             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
2621                    getLLVMStyleWithColumns(40)));
2622 }
2623 
TEST_F(FormatTest,UnderstandsLinePPDirective)2624 TEST_F(FormatTest, UnderstandsLinePPDirective) {
2625   EXPECT_EQ("# 123 \"A string literal\"",
2626             format("   #     123    \"A string literal\""));
2627 }
2628 
TEST_F(FormatTest,LayoutUnknownPPDirective)2629 TEST_F(FormatTest, LayoutUnknownPPDirective) {
2630   EXPECT_EQ("#;", format("#;"));
2631   verifyFormat("#\n;\n;\n;");
2632 }
2633 
TEST_F(FormatTest,UnescapedEndOfLineEndsPPDirective)2634 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
2635   EXPECT_EQ("#line 42 \"test\"\n",
2636             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
2637   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
2638                                     getLLVMStyleWithColumns(12)));
2639 }
2640 
TEST_F(FormatTest,EndOfFileEndsPPDirective)2641 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
2642   EXPECT_EQ("#line 42 \"test\"",
2643             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
2644   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
2645 }
2646 
TEST_F(FormatTest,DoesntRemoveUnknownTokens)2647 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
2648   verifyFormat("#define A \\x20");
2649   verifyFormat("#define A \\ x20");
2650   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
2651   verifyFormat("#define A ''");
2652   verifyFormat("#define A ''qqq");
2653   verifyFormat("#define A `qqq");
2654   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
2655   EXPECT_EQ("const char *c = STRINGIFY(\n"
2656             "\\na : b);",
2657             format("const char * c = STRINGIFY(\n"
2658                    "\\na : b);"));
2659 
2660   verifyFormat("a\r\\");
2661   verifyFormat("a\v\\");
2662   verifyFormat("a\f\\");
2663 }
2664 
TEST_F(FormatTest,IndentsPPDirectiveInReducedSpace)2665 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
2666   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
2667   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
2668   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
2669   // FIXME: We never break before the macro name.
2670   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
2671 
2672   verifyFormat("#define A A\n#define A A");
2673   verifyFormat("#define A(X) A\n#define A A");
2674 
2675   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
2676   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
2677 }
2678 
TEST_F(FormatTest,HandlePreprocessorDirectiveContext)2679 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
2680   EXPECT_EQ("// somecomment\n"
2681             "#include \"a.h\"\n"
2682             "#define A(  \\\n"
2683             "    A, B)\n"
2684             "#include \"b.h\"\n"
2685             "// somecomment\n",
2686             format("  // somecomment\n"
2687                    "  #include \"a.h\"\n"
2688                    "#define A(A,\\\n"
2689                    "    B)\n"
2690                    "    #include \"b.h\"\n"
2691                    " // somecomment\n",
2692                    getLLVMStyleWithColumns(13)));
2693 }
2694 
TEST_F(FormatTest,LayoutSingleHash)2695 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
2696 
TEST_F(FormatTest,LayoutCodeInMacroDefinitions)2697 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
2698   EXPECT_EQ("#define A    \\\n"
2699             "  c;         \\\n"
2700             "  e;\n"
2701             "f;",
2702             format("#define A c; e;\n"
2703                    "f;",
2704                    getLLVMStyleWithColumns(14)));
2705 }
2706 
TEST_F(FormatTest,LayoutRemainingTokens)2707 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
2708 
TEST_F(FormatTest,MacroDefinitionInsideStatement)2709 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
2710   EXPECT_EQ("int x,\n"
2711             "#define A\n"
2712             "    y;",
2713             format("int x,\n#define A\ny;"));
2714 }
2715 
TEST_F(FormatTest,HashInMacroDefinition)2716 TEST_F(FormatTest, HashInMacroDefinition) {
2717   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
2718   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
2719   verifyFormat("#define A  \\\n"
2720                "  {        \\\n"
2721                "    f(#c); \\\n"
2722                "  }",
2723                getLLVMStyleWithColumns(11));
2724 
2725   verifyFormat("#define A(X)         \\\n"
2726                "  void function##X()",
2727                getLLVMStyleWithColumns(22));
2728 
2729   verifyFormat("#define A(a, b, c)   \\\n"
2730                "  void a##b##c()",
2731                getLLVMStyleWithColumns(22));
2732 
2733   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
2734 }
2735 
TEST_F(FormatTest,RespectWhitespaceInMacroDefinitions)2736 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
2737   EXPECT_EQ("#define A (x)", format("#define A (x)"));
2738   EXPECT_EQ("#define A(x)", format("#define A(x)"));
2739 }
2740 
TEST_F(FormatTest,EmptyLinesInMacroDefinitions)2741 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
2742   EXPECT_EQ("#define A b;", format("#define A \\\n"
2743                                    "          \\\n"
2744                                    "  b;",
2745                                    getLLVMStyleWithColumns(25)));
2746   EXPECT_EQ("#define A \\\n"
2747             "          \\\n"
2748             "  a;      \\\n"
2749             "  b;",
2750             format("#define A \\\n"
2751                    "          \\\n"
2752                    "  a;      \\\n"
2753                    "  b;",
2754                    getLLVMStyleWithColumns(11)));
2755   EXPECT_EQ("#define A \\\n"
2756             "  a;      \\\n"
2757             "          \\\n"
2758             "  b;",
2759             format("#define A \\\n"
2760                    "  a;      \\\n"
2761                    "          \\\n"
2762                    "  b;",
2763                    getLLVMStyleWithColumns(11)));
2764 }
2765 
TEST_F(FormatTest,MacroDefinitionsWithIncompleteCode)2766 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
2767   verifyIncompleteFormat("#define A :");
2768   verifyFormat("#define SOMECASES  \\\n"
2769                "  case 1:          \\\n"
2770                "  case 2\n",
2771                getLLVMStyleWithColumns(20));
2772   verifyFormat("#define MACRO(a) \\\n"
2773                "  if (a)         \\\n"
2774                "    f();         \\\n"
2775                "  else           \\\n"
2776                "    g()",
2777                getLLVMStyleWithColumns(18));
2778   verifyFormat("#define A template <typename T>");
2779   verifyIncompleteFormat("#define STR(x) #x\n"
2780                          "f(STR(this_is_a_string_literal{));");
2781   verifyFormat("#pragma omp threadprivate( \\\n"
2782                "    y)), // expected-warning",
2783                getLLVMStyleWithColumns(28));
2784   verifyFormat("#d, = };");
2785   verifyFormat("#if \"a");
2786   verifyIncompleteFormat("({\n"
2787                          "#define b     \\\n"
2788                          "  }           \\\n"
2789                          "  a\n"
2790                          "a",
2791                          getLLVMStyleWithColumns(15));
2792   verifyFormat("#define A     \\\n"
2793                "  {           \\\n"
2794                "    {\n"
2795                "#define B     \\\n"
2796                "  }           \\\n"
2797                "  }",
2798                getLLVMStyleWithColumns(15));
2799   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
2800   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
2801   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
2802   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
2803 }
2804 
TEST_F(FormatTest,MacrosWithoutTrailingSemicolon)2805 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
2806   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
2807   EXPECT_EQ("class A : public QObject {\n"
2808             "  Q_OBJECT\n"
2809             "\n"
2810             "  A() {}\n"
2811             "};",
2812             format("class A  :  public QObject {\n"
2813                    "     Q_OBJECT\n"
2814                    "\n"
2815                    "  A() {\n}\n"
2816                    "}  ;"));
2817   EXPECT_EQ("MACRO\n"
2818             "/*static*/ int i;",
2819             format("MACRO\n"
2820                    " /*static*/ int   i;"));
2821   EXPECT_EQ("SOME_MACRO\n"
2822             "namespace {\n"
2823             "void f();\n"
2824             "}",
2825             format("SOME_MACRO\n"
2826                    "  namespace    {\n"
2827                    "void   f(  );\n"
2828                    "}"));
2829   // Only if the identifier contains at least 5 characters.
2830   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
2831   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
2832   // Only if everything is upper case.
2833   EXPECT_EQ("class A : public QObject {\n"
2834             "  Q_Object A() {}\n"
2835             "};",
2836             format("class A  :  public QObject {\n"
2837                    "     Q_Object\n"
2838                    "  A() {\n}\n"
2839                    "}  ;"));
2840 
2841   // Only if the next line can actually start an unwrapped line.
2842   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
2843             format("SOME_WEIRD_LOG_MACRO\n"
2844                    "<< SomeThing;"));
2845 
2846   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
2847                "(n, buffers))\n",
2848                getChromiumStyle(FormatStyle::LK_Cpp));
2849 }
2850 
TEST_F(FormatTest,MacroCallsWithoutTrailingSemicolon)2851 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
2852   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
2853             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
2854             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
2855             "class X {};\n"
2856             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
2857             "int *createScopDetectionPass() { return 0; }",
2858             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
2859                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
2860                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
2861                    "  class X {};\n"
2862                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
2863                    "  int *createScopDetectionPass() { return 0; }"));
2864   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
2865   // braces, so that inner block is indented one level more.
2866   EXPECT_EQ("int q() {\n"
2867             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
2868             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
2869             "  IPC_END_MESSAGE_MAP()\n"
2870             "}",
2871             format("int q() {\n"
2872                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
2873                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
2874                    "  IPC_END_MESSAGE_MAP()\n"
2875                    "}"));
2876 
2877   // Same inside macros.
2878   EXPECT_EQ("#define LIST(L) \\\n"
2879             "  L(A)          \\\n"
2880             "  L(B)          \\\n"
2881             "  L(C)",
2882             format("#define LIST(L) \\\n"
2883                    "  L(A) \\\n"
2884                    "  L(B) \\\n"
2885                    "  L(C)",
2886                    getGoogleStyle()));
2887 
2888   // These must not be recognized as macros.
2889   EXPECT_EQ("int q() {\n"
2890             "  f(x);\n"
2891             "  f(x) {}\n"
2892             "  f(x)->g();\n"
2893             "  f(x)->*g();\n"
2894             "  f(x).g();\n"
2895             "  f(x) = x;\n"
2896             "  f(x) += x;\n"
2897             "  f(x) -= x;\n"
2898             "  f(x) *= x;\n"
2899             "  f(x) /= x;\n"
2900             "  f(x) %= x;\n"
2901             "  f(x) &= x;\n"
2902             "  f(x) |= x;\n"
2903             "  f(x) ^= x;\n"
2904             "  f(x) >>= x;\n"
2905             "  f(x) <<= x;\n"
2906             "  f(x)[y].z();\n"
2907             "  LOG(INFO) << x;\n"
2908             "  ifstream(x) >> x;\n"
2909             "}\n",
2910             format("int q() {\n"
2911                    "  f(x)\n;\n"
2912                    "  f(x)\n {}\n"
2913                    "  f(x)\n->g();\n"
2914                    "  f(x)\n->*g();\n"
2915                    "  f(x)\n.g();\n"
2916                    "  f(x)\n = x;\n"
2917                    "  f(x)\n += x;\n"
2918                    "  f(x)\n -= x;\n"
2919                    "  f(x)\n *= x;\n"
2920                    "  f(x)\n /= x;\n"
2921                    "  f(x)\n %= x;\n"
2922                    "  f(x)\n &= x;\n"
2923                    "  f(x)\n |= x;\n"
2924                    "  f(x)\n ^= x;\n"
2925                    "  f(x)\n >>= x;\n"
2926                    "  f(x)\n <<= x;\n"
2927                    "  f(x)\n[y].z();\n"
2928                    "  LOG(INFO)\n << x;\n"
2929                    "  ifstream(x)\n >> x;\n"
2930                    "}\n"));
2931   EXPECT_EQ("int q() {\n"
2932             "  F(x)\n"
2933             "  if (1) {\n"
2934             "  }\n"
2935             "  F(x)\n"
2936             "  while (1) {\n"
2937             "  }\n"
2938             "  F(x)\n"
2939             "  G(x);\n"
2940             "  F(x)\n"
2941             "  try {\n"
2942             "    Q();\n"
2943             "  } catch (...) {\n"
2944             "  }\n"
2945             "}\n",
2946             format("int q() {\n"
2947                    "F(x)\n"
2948                    "if (1) {}\n"
2949                    "F(x)\n"
2950                    "while (1) {}\n"
2951                    "F(x)\n"
2952                    "G(x);\n"
2953                    "F(x)\n"
2954                    "try { Q(); } catch (...) {}\n"
2955                    "}\n"));
2956   EXPECT_EQ("class A {\n"
2957             "  A() : t(0) {}\n"
2958             "  A(int i) noexcept() : {}\n"
2959             "  A(X x)\n" // FIXME: function-level try blocks are broken.
2960             "  try : t(0) {\n"
2961             "  } catch (...) {\n"
2962             "  }\n"
2963             "};",
2964             format("class A {\n"
2965                    "  A()\n : t(0) {}\n"
2966                    "  A(int i)\n noexcept() : {}\n"
2967                    "  A(X x)\n"
2968                    "  try : t(0) {} catch (...) {}\n"
2969                    "};"));
2970   EXPECT_EQ("class SomeClass {\n"
2971             "public:\n"
2972             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2973             "};",
2974             format("class SomeClass {\n"
2975                    "public:\n"
2976                    "  SomeClass()\n"
2977                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2978                    "};"));
2979   EXPECT_EQ("class SomeClass {\n"
2980             "public:\n"
2981             "  SomeClass()\n"
2982             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2983             "};",
2984             format("class SomeClass {\n"
2985                    "public:\n"
2986                    "  SomeClass()\n"
2987                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2988                    "};",
2989                    getLLVMStyleWithColumns(40)));
2990 
2991   verifyFormat("MACRO(>)");
2992 }
2993 
TEST_F(FormatTest,LayoutMacroDefinitionsStatementsSpanningBlocks)2994 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
2995   verifyFormat("#define A \\\n"
2996                "  f({     \\\n"
2997                "    g();  \\\n"
2998                "  });",
2999                getLLVMStyleWithColumns(11));
3000 }
3001 
TEST_F(FormatTest,IndentPreprocessorDirectivesAtZero)3002 TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
3003   EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
3004 }
3005 
TEST_F(FormatTest,FormatHashIfNotAtStartOfLine)3006 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
3007   verifyFormat("{\n  { a #c; }\n}");
3008 }
3009 
TEST_F(FormatTest,FormatUnbalancedStructuralElements)3010 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
3011   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
3012             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
3013   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
3014             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
3015 }
3016 
TEST_F(FormatTest,EscapedNewlines)3017 TEST_F(FormatTest, EscapedNewlines) {
3018   EXPECT_EQ(
3019       "#define A \\\n  int i;  \\\n  int j;",
3020       format("#define A \\\nint i;\\\n  int j;", getLLVMStyleWithColumns(11)));
3021   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
3022   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3023   EXPECT_EQ("/* \\  \\  \\\n*/", format("\\\n/* \\  \\  \\\n*/"));
3024   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
3025 }
3026 
TEST_F(FormatTest,DontCrashOnBlockComments)3027 TEST_F(FormatTest, DontCrashOnBlockComments) {
3028   EXPECT_EQ(
3029       "int xxxxxxxxx; /* "
3030       "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\n"
3031       "zzzzzz\n"
3032       "0*/",
3033       format("int xxxxxxxxx;                          /* "
3034              "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy zzzzzz\n"
3035              "0*/"));
3036 }
3037 
TEST_F(FormatTest,CalculateSpaceOnConsecutiveLinesInMacro)3038 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
3039   verifyFormat("#define A \\\n"
3040                "  int v(  \\\n"
3041                "      a); \\\n"
3042                "  int i;",
3043                getLLVMStyleWithColumns(11));
3044 }
3045 
TEST_F(FormatTest,MixingPreprocessorDirectivesAndNormalCode)3046 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
3047   EXPECT_EQ(
3048       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3049       "                      \\\n"
3050       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3051       "\n"
3052       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3053       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
3054       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
3055              "\\\n"
3056              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3057              "  \n"
3058              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3059              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
3060 }
3061 
TEST_F(FormatTest,LayoutStatementsAroundPreprocessorDirectives)3062 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
3063   EXPECT_EQ("int\n"
3064             "#define A\n"
3065             "    a;",
3066             format("int\n#define A\na;"));
3067   verifyFormat("functionCallTo(\n"
3068                "    someOtherFunction(\n"
3069                "        withSomeParameters, whichInSequence,\n"
3070                "        areLongerThanALine(andAnotherCall,\n"
3071                "#define A B\n"
3072                "                           withMoreParamters,\n"
3073                "                           whichStronglyInfluenceTheLayout),\n"
3074                "        andMoreParameters),\n"
3075                "    trailing);",
3076                getLLVMStyleWithColumns(69));
3077   verifyFormat("Foo::Foo()\n"
3078                "#ifdef BAR\n"
3079                "    : baz(0)\n"
3080                "#endif\n"
3081                "{\n"
3082                "}");
3083   verifyFormat("void f() {\n"
3084                "  if (true)\n"
3085                "#ifdef A\n"
3086                "    f(42);\n"
3087                "  x();\n"
3088                "#else\n"
3089                "    g();\n"
3090                "  x();\n"
3091                "#endif\n"
3092                "}");
3093   verifyFormat("void f(param1, param2,\n"
3094                "       param3,\n"
3095                "#ifdef A\n"
3096                "       param4(param5,\n"
3097                "#ifdef A1\n"
3098                "              param6,\n"
3099                "#ifdef A2\n"
3100                "              param7),\n"
3101                "#else\n"
3102                "              param8),\n"
3103                "       param9,\n"
3104                "#endif\n"
3105                "       param10,\n"
3106                "#endif\n"
3107                "       param11)\n"
3108                "#else\n"
3109                "       param12)\n"
3110                "#endif\n"
3111                "{\n"
3112                "  x();\n"
3113                "}",
3114                getLLVMStyleWithColumns(28));
3115   verifyFormat("#if 1\n"
3116                "int i;");
3117   verifyFormat("#if 1\n"
3118                "#endif\n"
3119                "#if 1\n"
3120                "#else\n"
3121                "#endif\n");
3122   verifyFormat("DEBUG({\n"
3123                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3124                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
3125                "});\n"
3126                "#if a\n"
3127                "#else\n"
3128                "#endif");
3129 
3130   verifyIncompleteFormat("void f(\n"
3131                          "#if A\n"
3132                          "    );\n"
3133                          "#else\n"
3134                          "#endif");
3135 }
3136 
TEST_F(FormatTest,GraciouslyHandleIncorrectPreprocessorConditions)3137 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
3138   verifyFormat("#endif\n"
3139                "#if B");
3140 }
3141 
TEST_F(FormatTest,FormatsJoinedLinesOnSubsequentRuns)3142 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
3143   FormatStyle SingleLine = getLLVMStyle();
3144   SingleLine.AllowShortIfStatementsOnASingleLine = true;
3145   verifyFormat("#if 0\n"
3146                "#elif 1\n"
3147                "#endif\n"
3148                "void foo() {\n"
3149                "  if (test) foo2();\n"
3150                "}",
3151                SingleLine);
3152 }
3153 
TEST_F(FormatTest,LayoutBlockInsideParens)3154 TEST_F(FormatTest, LayoutBlockInsideParens) {
3155   verifyFormat("functionCall({ int i; });");
3156   verifyFormat("functionCall({\n"
3157                "  int i;\n"
3158                "  int j;\n"
3159                "});");
3160   verifyFormat("functionCall(\n"
3161                "    {\n"
3162                "      int i;\n"
3163                "      int j;\n"
3164                "    },\n"
3165                "    aaaa, bbbb, cccc);");
3166   verifyFormat("functionA(functionB({\n"
3167                "            int i;\n"
3168                "            int j;\n"
3169                "          }),\n"
3170                "          aaaa, bbbb, cccc);");
3171   verifyFormat("functionCall(\n"
3172                "    {\n"
3173                "      int i;\n"
3174                "      int j;\n"
3175                "    },\n"
3176                "    aaaa, bbbb, // comment\n"
3177                "    cccc);");
3178   verifyFormat("functionA(functionB({\n"
3179                "            int i;\n"
3180                "            int j;\n"
3181                "          }),\n"
3182                "          aaaa, bbbb, // comment\n"
3183                "          cccc);");
3184   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
3185   verifyFormat("functionCall(aaaa, bbbb, {\n"
3186                "  int i;\n"
3187                "  int j;\n"
3188                "});");
3189   verifyFormat(
3190       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
3191       "    {\n"
3192       "      int i; // break\n"
3193       "    },\n"
3194       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
3195       "                                     ccccccccccccccccc));");
3196   verifyFormat("DEBUG({\n"
3197                "  if (a)\n"
3198                "    f();\n"
3199                "});");
3200 }
3201 
TEST_F(FormatTest,LayoutBlockInsideStatement)3202 TEST_F(FormatTest, LayoutBlockInsideStatement) {
3203   EXPECT_EQ("SOME_MACRO { int i; }\n"
3204             "int i;",
3205             format("  SOME_MACRO  {int i;}  int i;"));
3206 }
3207 
TEST_F(FormatTest,LayoutNestedBlocks)3208 TEST_F(FormatTest, LayoutNestedBlocks) {
3209   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
3210                "  struct s {\n"
3211                "    int i;\n"
3212                "  };\n"
3213                "  s kBitsToOs[] = {{10}};\n"
3214                "  for (int i = 0; i < 10; ++i)\n"
3215                "    return;\n"
3216                "}");
3217   verifyFormat("call(parameter, {\n"
3218                "  something();\n"
3219                "  // Comment using all columns.\n"
3220                "  somethingelse();\n"
3221                "});",
3222                getLLVMStyleWithColumns(40));
3223   verifyFormat("DEBUG( //\n"
3224                "    { f(); }, a);");
3225   verifyFormat("DEBUG( //\n"
3226                "    {\n"
3227                "      f(); //\n"
3228                "    },\n"
3229                "    a);");
3230 
3231   EXPECT_EQ("call(parameter, {\n"
3232             "  something();\n"
3233             "  // Comment too\n"
3234             "  // looooooooooong.\n"
3235             "  somethingElse();\n"
3236             "});",
3237             format("call(parameter, {\n"
3238                    "  something();\n"
3239                    "  // Comment too looooooooooong.\n"
3240                    "  somethingElse();\n"
3241                    "});",
3242                    getLLVMStyleWithColumns(29)));
3243   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
3244   EXPECT_EQ("DEBUG({ // comment\n"
3245             "  int i;\n"
3246             "});",
3247             format("DEBUG({ // comment\n"
3248                    "int  i;\n"
3249                    "});"));
3250   EXPECT_EQ("DEBUG({\n"
3251             "  int i;\n"
3252             "\n"
3253             "  // comment\n"
3254             "  int j;\n"
3255             "});",
3256             format("DEBUG({\n"
3257                    "  int  i;\n"
3258                    "\n"
3259                    "  // comment\n"
3260                    "  int  j;\n"
3261                    "});"));
3262 
3263   verifyFormat("DEBUG({\n"
3264                "  if (a)\n"
3265                "    return;\n"
3266                "});");
3267   verifyGoogleFormat("DEBUG({\n"
3268                      "  if (a) return;\n"
3269                      "});");
3270   FormatStyle Style = getGoogleStyle();
3271   Style.ColumnLimit = 45;
3272   verifyFormat("Debug(aaaaa,\n"
3273                "      {\n"
3274                "        if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
3275                "      },\n"
3276                "      a);",
3277                Style);
3278 
3279   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
3280 
3281   verifyNoCrash("^{v^{a}}");
3282 }
3283 
TEST_F(FormatTest,FormatNestedBlocksInMacros)3284 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
3285   EXPECT_EQ("#define MACRO()                     \\\n"
3286             "  Debug(aaa, /* force line break */ \\\n"
3287             "        {                           \\\n"
3288             "          int i;                    \\\n"
3289             "          int j;                    \\\n"
3290             "        })",
3291             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
3292                    "          {  int   i;  int  j;   })",
3293                    getGoogleStyle()));
3294 
3295   EXPECT_EQ("#define A                                       \\\n"
3296             "  [] {                                          \\\n"
3297             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
3298             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
3299             "  }",
3300             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
3301                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
3302                    getGoogleStyle()));
3303 }
3304 
TEST_F(FormatTest,PutEmptyBlocksIntoOneLine)3305 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
3306   EXPECT_EQ("{}", format("{}"));
3307   verifyFormat("enum E {};");
3308   verifyFormat("enum E {}");
3309 }
3310 
TEST_F(FormatTest,FormatBeginBlockEndMacros)3311 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
3312   FormatStyle Style = getLLVMStyle();
3313   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
3314   Style.MacroBlockEnd = "^[A-Z_]+_END$";
3315   verifyFormat("FOO_BEGIN\n"
3316                "  FOO_ENTRY\n"
3317                "FOO_END", Style);
3318   verifyFormat("FOO_BEGIN\n"
3319                "  NESTED_FOO_BEGIN\n"
3320                "    NESTED_FOO_ENTRY\n"
3321                "  NESTED_FOO_END\n"
3322                "FOO_END", Style);
3323   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
3324                "  int x;\n"
3325                "  x = 1;\n"
3326                "FOO_END(Baz)", Style);
3327 }
3328 
3329 //===----------------------------------------------------------------------===//
3330 // Line break tests.
3331 //===----------------------------------------------------------------------===//
3332 
TEST_F(FormatTest,PreventConfusingIndents)3333 TEST_F(FormatTest, PreventConfusingIndents) {
3334   verifyFormat(
3335       "void f() {\n"
3336       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
3337       "                         parameter, parameter, parameter)),\n"
3338       "                     SecondLongCall(parameter));\n"
3339       "}");
3340   verifyFormat(
3341       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3342       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
3343       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3344       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
3345   verifyFormat(
3346       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3347       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
3348       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3349       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
3350   verifyFormat(
3351       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
3352       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
3353       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
3354       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
3355   verifyFormat("int a = bbbb && ccc && fffff(\n"
3356                "#define A Just forcing a new line\n"
3357                "                           ddd);");
3358 }
3359 
TEST_F(FormatTest,LineBreakingInBinaryExpressions)3360 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
3361   verifyFormat(
3362       "bool aaaaaaa =\n"
3363       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
3364       "    bbbbbbbb();");
3365   verifyFormat(
3366       "bool aaaaaaa =\n"
3367       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
3368       "    bbbbbbbb();");
3369 
3370   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
3371                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
3372                "    ccccccccc == ddddddddddd;");
3373   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
3374                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
3375                "    ccccccccc == ddddddddddd;");
3376   verifyFormat(
3377       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
3378       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
3379       "    ccccccccc == ddddddddddd;");
3380 
3381   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
3382                "                 aaaaaa) &&\n"
3383                "         bbbbbb && cccccc;");
3384   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
3385                "                 aaaaaa) >>\n"
3386                "         bbbbbb;");
3387   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
3388                "    SourceMgr.getSpellingColumnNumber(\n"
3389                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
3390                "    1);");
3391 
3392   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3393                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
3394                "    cccccc) {\n}");
3395   verifyFormat("b = a &&\n"
3396                "    // Comment\n"
3397                "    b.c && d;");
3398 
3399   // If the LHS of a comparison is not a binary expression itself, the
3400   // additional linebreak confuses many people.
3401   verifyFormat(
3402       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3403       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
3404       "}");
3405   verifyFormat(
3406       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3407       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
3408       "}");
3409   verifyFormat(
3410       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
3411       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
3412       "}");
3413   // Even explicit parentheses stress the precedence enough to make the
3414   // additional break unnecessary.
3415   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3416                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
3417                "}");
3418   // This cases is borderline, but with the indentation it is still readable.
3419   verifyFormat(
3420       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3421       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3422       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
3423       "}",
3424       getLLVMStyleWithColumns(75));
3425 
3426   // If the LHS is a binary expression, we should still use the additional break
3427   // as otherwise the formatting hides the operator precedence.
3428   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3429                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3430                "    5) {\n"
3431                "}");
3432 
3433   FormatStyle OnePerLine = getLLVMStyle();
3434   OnePerLine.BinPackParameters = false;
3435   verifyFormat(
3436       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3437       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3438       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
3439       OnePerLine);
3440 }
3441 
TEST_F(FormatTest,ExpressionIndentation)3442 TEST_F(FormatTest, ExpressionIndentation) {
3443   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3444                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3445                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3446                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3447                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
3448                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
3449                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3450                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
3451                "                 ccccccccccccccccccccccccccccccccccccccccc;");
3452   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3453                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3454                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3455                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
3456   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3457                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3458                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3459                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
3460   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3461                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3462                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3463                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
3464   verifyFormat("if () {\n"
3465                "} else if (aaaaa &&\n"
3466                "           bbbbb > // break\n"
3467                "               ccccc) {\n"
3468                "}");
3469 
3470   // Presence of a trailing comment used to change indentation of b.
3471   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
3472                "       b;\n"
3473                "return aaaaaaaaaaaaaaaaaaa +\n"
3474                "       b; //",
3475                getLLVMStyleWithColumns(30));
3476 }
3477 
TEST_F(FormatTest,ExpressionIndentationBreakingBeforeOperators)3478 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
3479   // Not sure what the best system is here. Like this, the LHS can be found
3480   // immediately above an operator (everything with the same or a higher
3481   // indent). The RHS is aligned right of the operator and so compasses
3482   // everything until something with the same indent as the operator is found.
3483   // FIXME: Is this a good system?
3484   FormatStyle Style = getLLVMStyle();
3485   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
3486   verifyFormat(
3487       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3488       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3489       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3490       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3491       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3492       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3493       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3494       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3495       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
3496       Style);
3497   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3498                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3499                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3500                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
3501                Style);
3502   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3503                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3504                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3505                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
3506                Style);
3507   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3508                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3509                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3510                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
3511                Style);
3512   verifyFormat("if () {\n"
3513                "} else if (aaaaa\n"
3514                "           && bbbbb // break\n"
3515                "                  > ccccc) {\n"
3516                "}",
3517                Style);
3518   verifyFormat("return (a)\n"
3519                "       // comment\n"
3520                "       + b;",
3521                Style);
3522   verifyFormat(
3523       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3524       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3525       "             + cc;",
3526       Style);
3527 
3528   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3529                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
3530                Style);
3531 
3532   // Forced by comments.
3533   verifyFormat(
3534       "unsigned ContentSize =\n"
3535       "    sizeof(int16_t)   // DWARF ARange version number\n"
3536       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
3537       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
3538       "    + sizeof(int8_t); // Segment Size (in bytes)");
3539 
3540   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
3541                "       == boost::fusion::at_c<1>(iiii).second;",
3542                Style);
3543 
3544   Style.ColumnLimit = 60;
3545   verifyFormat("zzzzzzzzzz\n"
3546                "    = bbbbbbbbbbbbbbbbb\n"
3547                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
3548                Style);
3549 }
3550 
TEST_F(FormatTest,NoOperandAlignment)3551 TEST_F(FormatTest, NoOperandAlignment) {
3552   FormatStyle Style = getLLVMStyle();
3553   Style.AlignOperands = false;
3554   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
3555   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3556                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3557                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3558                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3559                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3560                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3561                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3562                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3563                "        > ccccccccccccccccccccccccccccccccccccccccc;",
3564                Style);
3565 
3566   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3567                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3568                "    + cc;",
3569                Style);
3570   verifyFormat("int a = aa\n"
3571                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3572                "        * cccccccccccccccccccccccccccccccccccc;",
3573                Style);
3574 
3575   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
3576   verifyFormat("return (a > b\n"
3577                "    // comment1\n"
3578                "    // comment2\n"
3579                "    || c);",
3580                Style);
3581 }
3582 
TEST_F(FormatTest,BreakingBeforeNonAssigmentOperators)3583 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
3584   FormatStyle Style = getLLVMStyle();
3585   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
3586   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3587                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3588                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
3589                Style);
3590 }
3591 
TEST_F(FormatTest,ConstructorInitializers)3592 TEST_F(FormatTest, ConstructorInitializers) {
3593   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
3594   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
3595                getLLVMStyleWithColumns(45));
3596   verifyFormat("Constructor()\n"
3597                "    : Inttializer(FitsOnTheLine) {}",
3598                getLLVMStyleWithColumns(44));
3599   verifyFormat("Constructor()\n"
3600                "    : Inttializer(FitsOnTheLine) {}",
3601                getLLVMStyleWithColumns(43));
3602 
3603   verifyFormat("template <typename T>\n"
3604                "Constructor() : Initializer(FitsOnTheLine) {}",
3605                getLLVMStyleWithColumns(45));
3606 
3607   verifyFormat(
3608       "SomeClass::Constructor()\n"
3609       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
3610 
3611   verifyFormat(
3612       "SomeClass::Constructor()\n"
3613       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3614       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
3615   verifyFormat(
3616       "SomeClass::Constructor()\n"
3617       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3618       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
3619   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3620                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3621                "    : aaaaaaaaaa(aaaaaa) {}");
3622 
3623   verifyFormat("Constructor()\n"
3624                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3625                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3626                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3627                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
3628 
3629   verifyFormat("Constructor()\n"
3630                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3631                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
3632 
3633   verifyFormat("Constructor(int Parameter = 0)\n"
3634                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
3635                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
3636   verifyFormat("Constructor()\n"
3637                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
3638                "}",
3639                getLLVMStyleWithColumns(60));
3640   verifyFormat("Constructor()\n"
3641                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3642                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
3643 
3644   // Here a line could be saved by splitting the second initializer onto two
3645   // lines, but that is not desirable.
3646   verifyFormat("Constructor()\n"
3647                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
3648                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
3649                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
3650 
3651   FormatStyle OnePerLine = getLLVMStyle();
3652   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
3653   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
3654   verifyFormat("SomeClass::Constructor()\n"
3655                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3656                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3657                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
3658                OnePerLine);
3659   verifyFormat("SomeClass::Constructor()\n"
3660                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
3661                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3662                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
3663                OnePerLine);
3664   verifyFormat("MyClass::MyClass(int var)\n"
3665                "    : some_var_(var),            // 4 space indent\n"
3666                "      some_other_var_(var + 1) { // lined up\n"
3667                "}",
3668                OnePerLine);
3669   verifyFormat("Constructor()\n"
3670                "    : aaaaa(aaaaaa),\n"
3671                "      aaaaa(aaaaaa),\n"
3672                "      aaaaa(aaaaaa),\n"
3673                "      aaaaa(aaaaaa),\n"
3674                "      aaaaa(aaaaaa) {}",
3675                OnePerLine);
3676   verifyFormat("Constructor()\n"
3677                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
3678                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
3679                OnePerLine);
3680   OnePerLine.BinPackParameters = false;
3681   verifyFormat(
3682       "Constructor()\n"
3683       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
3684       "          aaaaaaaaaaa().aaa(),\n"
3685       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
3686       OnePerLine);
3687   OnePerLine.ColumnLimit = 60;
3688   verifyFormat("Constructor()\n"
3689                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
3690                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
3691                OnePerLine);
3692 
3693   EXPECT_EQ("Constructor()\n"
3694             "    : // Comment forcing unwanted break.\n"
3695             "      aaaa(aaaa) {}",
3696             format("Constructor() :\n"
3697                    "    // Comment forcing unwanted break.\n"
3698                    "    aaaa(aaaa) {}"));
3699 }
3700 
TEST_F(FormatTest,MemoizationTests)3701 TEST_F(FormatTest, MemoizationTests) {
3702   // This breaks if the memoization lookup does not take \c Indent and
3703   // \c LastSpace into account.
3704   verifyFormat(
3705       "extern CFRunLoopTimerRef\n"
3706       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
3707       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
3708       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
3709       "                     CFRunLoopTimerContext *context) {}");
3710 
3711   // Deep nesting somewhat works around our memoization.
3712   verifyFormat(
3713       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3714       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3715       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3716       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3717       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
3718       getLLVMStyleWithColumns(65));
3719   verifyFormat(
3720       "aaaaa(\n"
3721       "    aaaaa,\n"
3722       "    aaaaa(\n"
3723       "        aaaaa,\n"
3724       "        aaaaa(\n"
3725       "            aaaaa,\n"
3726       "            aaaaa(\n"
3727       "                aaaaa,\n"
3728       "                aaaaa(\n"
3729       "                    aaaaa,\n"
3730       "                    aaaaa(\n"
3731       "                        aaaaa,\n"
3732       "                        aaaaa(\n"
3733       "                            aaaaa,\n"
3734       "                            aaaaa(\n"
3735       "                                aaaaa,\n"
3736       "                                aaaaa(\n"
3737       "                                    aaaaa,\n"
3738       "                                    aaaaa(\n"
3739       "                                        aaaaa,\n"
3740       "                                        aaaaa(\n"
3741       "                                            aaaaa,\n"
3742       "                                            aaaaa(\n"
3743       "                                                aaaaa,\n"
3744       "                                                aaaaa))))))))))));",
3745       getLLVMStyleWithColumns(65));
3746   verifyFormat(
3747       "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"
3748       "                                  a),\n"
3749       "                                a),\n"
3750       "                              a),\n"
3751       "                            a),\n"
3752       "                          a),\n"
3753       "                        a),\n"
3754       "                      a),\n"
3755       "                    a),\n"
3756       "                  a),\n"
3757       "                a),\n"
3758       "              a),\n"
3759       "            a),\n"
3760       "          a),\n"
3761       "        a),\n"
3762       "      a),\n"
3763       "    a),\n"
3764       "  a)",
3765       getLLVMStyleWithColumns(65));
3766 
3767   // This test takes VERY long when memoization is broken.
3768   FormatStyle OnePerLine = getLLVMStyle();
3769   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
3770   OnePerLine.BinPackParameters = false;
3771   std::string input = "Constructor()\n"
3772                       "    : aaaa(a,\n";
3773   for (unsigned i = 0, e = 80; i != e; ++i) {
3774     input += "           a,\n";
3775   }
3776   input += "           a) {}";
3777   verifyFormat(input, OnePerLine);
3778 }
3779 
TEST_F(FormatTest,BreaksAsHighAsPossible)3780 TEST_F(FormatTest, BreaksAsHighAsPossible) {
3781   verifyFormat(
3782       "void f() {\n"
3783       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
3784       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
3785       "    f();\n"
3786       "}");
3787   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
3788                "    Intervals[i - 1].getRange().getLast()) {\n}");
3789 }
3790 
TEST_F(FormatTest,BreaksFunctionDeclarations)3791 TEST_F(FormatTest, BreaksFunctionDeclarations) {
3792   // Principially, we break function declarations in a certain order:
3793   // 1) break amongst arguments.
3794   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
3795                "                              Cccccccccccccc cccccccccccccc);");
3796   verifyFormat("template <class TemplateIt>\n"
3797                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
3798                "                            TemplateIt *stop) {}");
3799 
3800   // 2) break after return type.
3801   verifyFormat(
3802       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3803       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
3804       getGoogleStyle());
3805 
3806   // 3) break after (.
3807   verifyFormat(
3808       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
3809       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
3810       getGoogleStyle());
3811 
3812   // 4) break before after nested name specifiers.
3813   verifyFormat(
3814       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3815       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
3816       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
3817       getGoogleStyle());
3818 
3819   // However, there are exceptions, if a sufficient amount of lines can be
3820   // saved.
3821   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
3822   // more adjusting.
3823   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
3824                "                                  Cccccccccccccc cccccccccc,\n"
3825                "                                  Cccccccccccccc cccccccccc,\n"
3826                "                                  Cccccccccccccc cccccccccc,\n"
3827                "                                  Cccccccccccccc cccccccccc);");
3828   verifyFormat(
3829       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3830       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3831       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3832       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
3833       getGoogleStyle());
3834   verifyFormat(
3835       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
3836       "                                          Cccccccccccccc cccccccccc,\n"
3837       "                                          Cccccccccccccc cccccccccc,\n"
3838       "                                          Cccccccccccccc cccccccccc,\n"
3839       "                                          Cccccccccccccc cccccccccc,\n"
3840       "                                          Cccccccccccccc cccccccccc,\n"
3841       "                                          Cccccccccccccc cccccccccc);");
3842   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
3843                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3844                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3845                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3846                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
3847 
3848   // Break after multi-line parameters.
3849   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3850                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3851                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3852                "    bbbb bbbb);");
3853   verifyFormat("void SomeLoooooooooooongFunction(\n"
3854                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
3855                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3856                "    int bbbbbbbbbbbbb);");
3857 
3858   // Treat overloaded operators like other functions.
3859   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
3860                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
3861   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
3862                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
3863   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
3864                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
3865   verifyGoogleFormat(
3866       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
3867       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
3868   verifyGoogleFormat(
3869       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
3870       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
3871   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3872                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
3873   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
3874                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
3875   verifyGoogleFormat(
3876       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
3877       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3878       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
3879   verifyGoogleFormat(
3880       "template <typename T>\n"
3881       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3882       "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
3883       "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
3884 
3885   FormatStyle Style = getLLVMStyle();
3886   Style.PointerAlignment = FormatStyle::PAS_Left;
3887   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3888                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
3889                Style);
3890   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
3891                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
3892                Style);
3893 }
3894 
TEST_F(FormatTest,TrailingReturnType)3895 TEST_F(FormatTest, TrailingReturnType) {
3896   verifyFormat("auto foo() -> int;\n");
3897   verifyFormat("struct S {\n"
3898                "  auto bar() const -> int;\n"
3899                "};");
3900   verifyFormat("template <size_t Order, typename T>\n"
3901                "auto load_img(const std::string &filename)\n"
3902                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
3903   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
3904                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
3905   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
3906   verifyFormat("template <typename T>\n"
3907                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
3908                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
3909 
3910   // Not trailing return types.
3911   verifyFormat("void f() { auto a = b->c(); }");
3912 }
3913 
TEST_F(FormatTest,BreaksFunctionDeclarationsWithTrailingTokens)3914 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
3915   // Avoid breaking before trailing 'const' or other trailing annotations, if
3916   // they are not function-like.
3917   FormatStyle Style = getGoogleStyle();
3918   Style.ColumnLimit = 47;
3919   verifyFormat("void someLongFunction(\n"
3920                "    int someLoooooooooooooongParameter) const {\n}",
3921                getLLVMStyleWithColumns(47));
3922   verifyFormat("LoooooongReturnType\n"
3923                "someLoooooooongFunction() const {}",
3924                getLLVMStyleWithColumns(47));
3925   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
3926                "    const {}",
3927                Style);
3928   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
3929                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
3930   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
3931                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
3932   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
3933                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
3934   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
3935                "                   aaaaaaaaaaa aaaaa) const override;");
3936   verifyGoogleFormat(
3937       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
3938       "    const override;");
3939 
3940   // Even if the first parameter has to be wrapped.
3941   verifyFormat("void someLongFunction(\n"
3942                "    int someLongParameter) const {}",
3943                getLLVMStyleWithColumns(46));
3944   verifyFormat("void someLongFunction(\n"
3945                "    int someLongParameter) const {}",
3946                Style);
3947   verifyFormat("void someLongFunction(\n"
3948                "    int someLongParameter) override {}",
3949                Style);
3950   verifyFormat("void someLongFunction(\n"
3951                "    int someLongParameter) OVERRIDE {}",
3952                Style);
3953   verifyFormat("void someLongFunction(\n"
3954                "    int someLongParameter) final {}",
3955                Style);
3956   verifyFormat("void someLongFunction(\n"
3957                "    int someLongParameter) FINAL {}",
3958                Style);
3959   verifyFormat("void someLongFunction(\n"
3960                "    int parameter) const override {}",
3961                Style);
3962 
3963   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
3964   verifyFormat("void someLongFunction(\n"
3965                "    int someLongParameter) const\n"
3966                "{\n"
3967                "}",
3968                Style);
3969 
3970   // Unless these are unknown annotations.
3971   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
3972                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3973                "    LONG_AND_UGLY_ANNOTATION;");
3974 
3975   // Breaking before function-like trailing annotations is fine to keep them
3976   // close to their arguments.
3977   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3978                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
3979   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
3980                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
3981   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
3982                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
3983   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
3984                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
3985   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
3986 
3987   verifyFormat(
3988       "void aaaaaaaaaaaaaaaaaa()\n"
3989       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
3990       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
3991   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3992                "    __attribute__((unused));");
3993   verifyGoogleFormat(
3994       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3995       "    GUARDED_BY(aaaaaaaaaaaa);");
3996   verifyGoogleFormat(
3997       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3998       "    GUARDED_BY(aaaaaaaaaaaa);");
3999   verifyGoogleFormat(
4000       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
4001       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4002   verifyGoogleFormat(
4003       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
4004       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
4005 }
4006 
TEST_F(FormatTest,FunctionAnnotations)4007 TEST_F(FormatTest, FunctionAnnotations) {
4008   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
4009                "int OldFunction(const string &parameter) {}");
4010   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
4011                "string OldFunction(const string &parameter) {}");
4012   verifyFormat("template <typename T>\n"
4013                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
4014                "string OldFunction(const string &parameter) {}");
4015 
4016   // Not function annotations.
4017   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4018                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
4019   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
4020                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
4021   verifyFormat("MACRO(abc).function() // wrap\n"
4022                "    << abc;");
4023   verifyFormat("MACRO(abc)->function() // wrap\n"
4024                "    << abc;");
4025   verifyFormat("MACRO(abc)::function() // wrap\n"
4026                "    << abc;");
4027 }
4028 
TEST_F(FormatTest,BreaksDesireably)4029 TEST_F(FormatTest, BreaksDesireably) {
4030   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
4031                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
4032                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
4033   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4034                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
4035                "}");
4036 
4037   verifyFormat(
4038       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4039       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4040 
4041   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4042                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4043                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
4044 
4045   verifyFormat(
4046       "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4047       "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
4048       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4049       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
4050 
4051   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4052                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4053 
4054   verifyFormat(
4055       "void f() {\n"
4056       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
4057       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
4058       "}");
4059   verifyFormat(
4060       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4061       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
4062   verifyFormat(
4063       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4064       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
4065   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4066                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4067                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4068 
4069   // Indent consistently independent of call expression and unary operator.
4070   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
4071                "    dddddddddddddddddddddddddddddd));");
4072   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
4073                "    dddddddddddddddddddddddddddddd));");
4074   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
4075                "    dddddddddddddddddddddddddddddd));");
4076 
4077   // This test case breaks on an incorrect memoization, i.e. an optimization not
4078   // taking into account the StopAt value.
4079   verifyFormat(
4080       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
4081       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
4082       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
4083       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4084 
4085   verifyFormat("{\n  {\n    {\n"
4086                "      Annotation.SpaceRequiredBefore =\n"
4087                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
4088                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
4089                "    }\n  }\n}");
4090 
4091   // Break on an outer level if there was a break on an inner level.
4092   EXPECT_EQ("f(g(h(a, // comment\n"
4093             "      b, c),\n"
4094             "    d, e),\n"
4095             "  x, y);",
4096             format("f(g(h(a, // comment\n"
4097                    "    b, c), d, e), x, y);"));
4098 
4099   // Prefer breaking similar line breaks.
4100   verifyFormat(
4101       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
4102       "                             NSTrackingMouseEnteredAndExited |\n"
4103       "                             NSTrackingActiveAlways;");
4104 }
4105 
TEST_F(FormatTest,FormatsDeclarationsOnePerLine)4106 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
4107   FormatStyle NoBinPacking = getGoogleStyle();
4108   NoBinPacking.BinPackParameters = false;
4109   NoBinPacking.BinPackArguments = true;
4110   verifyFormat("void f() {\n"
4111                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
4112                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
4113                "}",
4114                NoBinPacking);
4115   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
4116                "       int aaaaaaaaaaaaaaaaaaaa,\n"
4117                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4118                NoBinPacking);
4119 
4120   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
4121   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4122                "                        vector<int> bbbbbbbbbbbbbbb);",
4123                NoBinPacking);
4124   // FIXME: This behavior difference is probably not wanted. However, currently
4125   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
4126   // template arguments from BreakBeforeParameter being set because of the
4127   // one-per-line formatting.
4128   verifyFormat(
4129       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
4130       "                                             aaaaaaaaaa> aaaaaaaaaa);",
4131       NoBinPacking);
4132   verifyFormat(
4133       "void fffffffffff(\n"
4134       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
4135       "        aaaaaaaaaa);");
4136 }
4137 
TEST_F(FormatTest,FormatsOneParameterPerLineIfNecessary)4138 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
4139   FormatStyle NoBinPacking = getGoogleStyle();
4140   NoBinPacking.BinPackParameters = false;
4141   NoBinPacking.BinPackArguments = false;
4142   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
4143                "  aaaaaaaaaaaaaaaaaaaa,\n"
4144                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
4145                NoBinPacking);
4146   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
4147                "        aaaaaaaaaaaaa,\n"
4148                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
4149                NoBinPacking);
4150   verifyFormat(
4151       "aaaaaaaa(aaaaaaaaaaaaa,\n"
4152       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4153       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
4154       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4155       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
4156       NoBinPacking);
4157   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
4158                "    .aaaaaaaaaaaaaaaaaa();",
4159                NoBinPacking);
4160   verifyFormat("void f() {\n"
4161                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4162                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
4163                "}",
4164                NoBinPacking);
4165 
4166   verifyFormat(
4167       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4168       "             aaaaaaaaaaaa,\n"
4169       "             aaaaaaaaaaaa);",
4170       NoBinPacking);
4171   verifyFormat(
4172       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
4173       "                               ddddddddddddddddddddddddddddd),\n"
4174       "             test);",
4175       NoBinPacking);
4176 
4177   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
4178                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
4179                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
4180                "    aaaaaaaaaaaaaaaaaa;",
4181                NoBinPacking);
4182   verifyFormat("a(\"a\"\n"
4183                "  \"a\",\n"
4184                "  a);");
4185 
4186   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
4187   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
4188                "                aaaaaaaaa,\n"
4189                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4190                NoBinPacking);
4191   verifyFormat(
4192       "void f() {\n"
4193       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
4194       "      .aaaaaaa();\n"
4195       "}",
4196       NoBinPacking);
4197   verifyFormat(
4198       "template <class SomeType, class SomeOtherType>\n"
4199       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
4200       NoBinPacking);
4201 }
4202 
TEST_F(FormatTest,AdaptiveOnePerLineFormatting)4203 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
4204   FormatStyle Style = getLLVMStyleWithColumns(15);
4205   Style.ExperimentalAutoDetectBinPacking = true;
4206   EXPECT_EQ("aaa(aaaa,\n"
4207             "    aaaa,\n"
4208             "    aaaa);\n"
4209             "aaa(aaaa,\n"
4210             "    aaaa,\n"
4211             "    aaaa);",
4212             format("aaa(aaaa,\n" // one-per-line
4213                    "  aaaa,\n"
4214                    "    aaaa  );\n"
4215                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
4216                    Style));
4217   EXPECT_EQ("aaa(aaaa, aaaa,\n"
4218             "    aaaa);\n"
4219             "aaa(aaaa, aaaa,\n"
4220             "    aaaa);",
4221             format("aaa(aaaa,  aaaa,\n" // bin-packed
4222                    "    aaaa  );\n"
4223                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
4224                    Style));
4225 }
4226 
TEST_F(FormatTest,FormatsBuilderPattern)4227 TEST_F(FormatTest, FormatsBuilderPattern) {
4228   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
4229                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
4230                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
4231                "    .StartsWith(\".init\", ORDER_INIT)\n"
4232                "    .StartsWith(\".fini\", ORDER_FINI)\n"
4233                "    .StartsWith(\".hash\", ORDER_HASH)\n"
4234                "    .Default(ORDER_TEXT);\n");
4235 
4236   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
4237                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
4238   verifyFormat(
4239       "aaaaaaa->aaaaaaa\n"
4240       "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4241       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4242       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
4243   verifyFormat(
4244       "aaaaaaa->aaaaaaa\n"
4245       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4246       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
4247   verifyFormat(
4248       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
4249       "    aaaaaaaaaaaaaa);");
4250   verifyFormat(
4251       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
4252       "    aaaaaa->aaaaaaaaaaaa()\n"
4253       "        ->aaaaaaaaaaaaaaaa(\n"
4254       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4255       "        ->aaaaaaaaaaaaaaaaa();");
4256   verifyGoogleFormat(
4257       "void f() {\n"
4258       "  someo->Add((new util::filetools::Handler(dir))\n"
4259       "                 ->OnEvent1(NewPermanentCallback(\n"
4260       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
4261       "                 ->OnEvent2(NewPermanentCallback(\n"
4262       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
4263       "                 ->OnEvent3(NewPermanentCallback(\n"
4264       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
4265       "                 ->OnEvent5(NewPermanentCallback(\n"
4266       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
4267       "                 ->OnEvent6(NewPermanentCallback(\n"
4268       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
4269       "}");
4270 
4271   verifyFormat(
4272       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
4273   verifyFormat("aaaaaaaaaaaaaaa()\n"
4274                "    .aaaaaaaaaaaaaaa()\n"
4275                "    .aaaaaaaaaaaaaaa()\n"
4276                "    .aaaaaaaaaaaaaaa()\n"
4277                "    .aaaaaaaaaaaaaaa();");
4278   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
4279                "    .aaaaaaaaaaaaaaa()\n"
4280                "    .aaaaaaaaaaaaaaa()\n"
4281                "    .aaaaaaaaaaaaaaa();");
4282   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
4283                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
4284                "    .aaaaaaaaaaaaaaa();");
4285   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
4286                "    ->aaaaaaaaaaaaaae(0)\n"
4287                "    ->aaaaaaaaaaaaaaa();");
4288 
4289   // Don't linewrap after very short segments.
4290   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4291                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4292                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4293   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4294                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4295                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4296   verifyFormat("aaa()\n"
4297                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4298                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4299                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4300 
4301   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
4302                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4303                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
4304   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
4305                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
4306                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
4307 
4308   // Prefer not to break after empty parentheses.
4309   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
4310                "    First->LastNewlineOffset);");
4311 
4312   // Prefer not to create "hanging" indents.
4313   verifyFormat(
4314       "return !soooooooooooooome_map\n"
4315       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4316       "            .second;");
4317   verifyFormat(
4318       "return aaaaaaaaaaaaaaaa\n"
4319       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
4320       "    .aaaa(aaaaaaaaaaaaaa);");
4321   // No hanging indent here.
4322   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
4323                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4324   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
4325                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4326   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
4327                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4328                getLLVMStyleWithColumns(60));
4329   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
4330                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
4331                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4332                getLLVMStyleWithColumns(59));
4333   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4334                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4335                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4336 }
4337 
TEST_F(FormatTest,BreaksAccordingToOperatorPrecedence)4338 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
4339   verifyFormat(
4340       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4341       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
4342   verifyFormat(
4343       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
4344       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
4345 
4346   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
4347                "    ccccccccccccccccccccccccc) {\n}");
4348   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
4349                "    ccccccccccccccccccccccccc) {\n}");
4350 
4351   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
4352                "    ccccccccccccccccccccccccc) {\n}");
4353   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
4354                "    ccccccccccccccccccccccccc) {\n}");
4355 
4356   verifyFormat(
4357       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
4358       "    ccccccccccccccccccccccccc) {\n}");
4359   verifyFormat(
4360       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
4361       "    ccccccccccccccccccccccccc) {\n}");
4362 
4363   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
4364                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
4365                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
4366                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
4367   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
4368                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
4369                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
4370                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
4371 
4372   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
4373                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
4374                "    aaaaaaaaaaaaaaa != aa) {\n}");
4375   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
4376                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
4377                "    aaaaaaaaaaaaaaa != aa) {\n}");
4378 }
4379 
TEST_F(FormatTest,BreaksAfterAssignments)4380 TEST_F(FormatTest, BreaksAfterAssignments) {
4381   verifyFormat(
4382       "unsigned Cost =\n"
4383       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
4384       "                        SI->getPointerAddressSpaceee());\n");
4385   verifyFormat(
4386       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
4387       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
4388 
4389   verifyFormat(
4390       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
4391       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
4392   verifyFormat("unsigned OriginalStartColumn =\n"
4393                "    SourceMgr.getSpellingColumnNumber(\n"
4394                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
4395                "    1;");
4396 }
4397 
TEST_F(FormatTest,AlignsAfterAssignments)4398 TEST_F(FormatTest, AlignsAfterAssignments) {
4399   verifyFormat(
4400       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4401       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
4402   verifyFormat(
4403       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4404       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
4405   verifyFormat(
4406       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4407       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
4408   verifyFormat(
4409       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4410       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
4411   verifyFormat(
4412       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
4413       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
4414       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
4415 }
4416 
TEST_F(FormatTest,AlignsAfterReturn)4417 TEST_F(FormatTest, AlignsAfterReturn) {
4418   verifyFormat(
4419       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4420       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
4421   verifyFormat(
4422       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4423       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
4424   verifyFormat(
4425       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
4426       "       aaaaaaaaaaaaaaaaaaaaaa();");
4427   verifyFormat(
4428       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
4429       "        aaaaaaaaaaaaaaaaaaaaaa());");
4430   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4431                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4432   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4433                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
4434                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4435   verifyFormat("return\n"
4436                "    // true if code is one of a or b.\n"
4437                "    code == a || code == b;");
4438 }
4439 
TEST_F(FormatTest,AlignsAfterOpenBracket)4440 TEST_F(FormatTest, AlignsAfterOpenBracket) {
4441   verifyFormat(
4442       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
4443       "                                                aaaaaaaaa aaaaaaa) {}");
4444   verifyFormat(
4445       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
4446       "                                               aaaaaaaaaaa aaaaaaaaa);");
4447   verifyFormat(
4448       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
4449       "                                             aaaaaaaaaaaaaaaaaaaaa));");
4450   FormatStyle Style = getLLVMStyle();
4451   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4452   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4453                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
4454                Style);
4455   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
4456                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
4457                Style);
4458   verifyFormat("SomeLongVariableName->someFunction(\n"
4459                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
4460                Style);
4461   verifyFormat(
4462       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
4463       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4464       Style);
4465   verifyFormat(
4466       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
4467       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4468       Style);
4469   verifyFormat(
4470       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
4471       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
4472       Style);
4473 
4474   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
4475                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
4476                "        b));",
4477                Style);
4478 
4479   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
4480   Style.BinPackArguments = false;
4481   Style.BinPackParameters = false;
4482   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4483                "    aaaaaaaaaaa aaaaaaaa,\n"
4484                "    aaaaaaaaa aaaaaaa,\n"
4485                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4486                Style);
4487   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
4488                "    aaaaaaaaaaa aaaaaaaaa,\n"
4489                "    aaaaaaaaaaa aaaaaaaaa,\n"
4490                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4491                Style);
4492   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
4493                "    aaaaaaaaaaaaaaa,\n"
4494                "    aaaaaaaaaaaaaaaaaaaaa,\n"
4495                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
4496                Style);
4497   verifyFormat(
4498       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
4499       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
4500       Style);
4501   verifyFormat(
4502       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
4503       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
4504       Style);
4505   verifyFormat(
4506       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4507       "    aaaaaaaaaaaaaaaaaaaaa(\n"
4508       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
4509       "    aaaaaaaaaaaaaaaa);",
4510       Style);
4511   verifyFormat(
4512       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4513       "    aaaaaaaaaaaaaaaaaaaaa(\n"
4514       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
4515       "    aaaaaaaaaaaaaaaa);",
4516       Style);
4517 }
4518 
TEST_F(FormatTest,ParenthesesAndOperandAlignment)4519 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
4520   FormatStyle Style = getLLVMStyleWithColumns(40);
4521   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4522                "          bbbbbbbbbbbbbbbbbbbbbb);",
4523                Style);
4524   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
4525   Style.AlignOperands = false;
4526   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4527                "          bbbbbbbbbbbbbbbbbbbbbb);",
4528                Style);
4529   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4530   Style.AlignOperands = true;
4531   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4532                "          bbbbbbbbbbbbbbbbbbbbbb);",
4533                Style);
4534   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4535   Style.AlignOperands = false;
4536   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4537                "    bbbbbbbbbbbbbbbbbbbbbb);",
4538                Style);
4539 }
4540 
TEST_F(FormatTest,BreaksConditionalExpressions)4541 TEST_F(FormatTest, BreaksConditionalExpressions) {
4542   verifyFormat(
4543       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4544       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4545       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4546   verifyFormat(
4547       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4548       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4549   verifyFormat(
4550       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
4551       "                                                    : aaaaaaaaaaaaa);");
4552   verifyFormat(
4553       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4554       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4555       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4556       "                   aaaaaaaaaaaaa);");
4557   verifyFormat(
4558       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4559       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4560       "                   aaaaaaaaaaaaa);");
4561   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4562                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4563                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4564                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4565                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4566   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4567                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4568                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4569                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4570                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4571                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4572                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4573   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4574                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4575                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4576                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4577                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4578   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4579                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4580                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4581   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
4582                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4583                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4584                "        : aaaaaaaaaaaaaaaa;");
4585   verifyFormat(
4586       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4587       "    ? aaaaaaaaaaaaaaa\n"
4588       "    : aaaaaaaaaaaaaaa;");
4589   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
4590                "          aaaaaaaaa\n"
4591                "      ? b\n"
4592                "      : c);");
4593   verifyFormat("return aaaa == bbbb\n"
4594                "           // comment\n"
4595                "           ? aaaa\n"
4596                "           : bbbb;");
4597   verifyFormat("unsigned Indent =\n"
4598                "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0\n"
4599                "                              ? IndentForLevel[TheLine.Level]\n"
4600                "                              : TheLine * 2,\n"
4601                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
4602                getLLVMStyleWithColumns(70));
4603   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
4604                "                  ? aaaaaaaaaaaaaaa\n"
4605                "                  : bbbbbbbbbbbbbbb //\n"
4606                "                        ? ccccccccccccccc\n"
4607                "                        : ddddddddddddddd;");
4608   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
4609                "                  ? aaaaaaaaaaaaaaa\n"
4610                "                  : (bbbbbbbbbbbbbbb //\n"
4611                "                         ? ccccccccccccccc\n"
4612                "                         : ddddddddddddddd);");
4613   verifyFormat(
4614       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4615       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4616       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
4617       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
4618       "                                      : aaaaaaaaaa;");
4619   verifyFormat(
4620       "aaaaaa = aaaaaaaaaaaa\n"
4621       "             ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4622       "                          : aaaaaaaaaaaaaaaaaaaaaa\n"
4623       "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4624 
4625   FormatStyle NoBinPacking = getLLVMStyle();
4626   NoBinPacking.BinPackArguments = false;
4627   verifyFormat(
4628       "void f() {\n"
4629       "  g(aaa,\n"
4630       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
4631       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4632       "        ? aaaaaaaaaaaaaaa\n"
4633       "        : aaaaaaaaaaaaaaa);\n"
4634       "}",
4635       NoBinPacking);
4636   verifyFormat(
4637       "void f() {\n"
4638       "  g(aaa,\n"
4639       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
4640       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4641       "        ?: aaaaaaaaaaaaaaa);\n"
4642       "}",
4643       NoBinPacking);
4644 
4645   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
4646                "             // comment.\n"
4647                "             ccccccccccccccccccccccccccccccccccccccc\n"
4648                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4649                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
4650 
4651   // Assignments in conditional expressions. Apparently not uncommon :-(.
4652   verifyFormat("return a != b\n"
4653                "           // comment\n"
4654                "           ? a = b\n"
4655                "           : a = b;");
4656   verifyFormat("return a != b\n"
4657                "           // comment\n"
4658                "           ? a = a != b\n"
4659                "                     // comment\n"
4660                "                     ? a = b\n"
4661                "                     : a\n"
4662                "           : a;\n");
4663   verifyFormat("return a != b\n"
4664                "           // comment\n"
4665                "           ? a\n"
4666                "           : a = a != b\n"
4667                "                     // comment\n"
4668                "                     ? a = b\n"
4669                "                     : a;");
4670 }
4671 
TEST_F(FormatTest,BreaksConditionalExpressionsAfterOperator)4672 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
4673   FormatStyle Style = getLLVMStyle();
4674   Style.BreakBeforeTernaryOperators = false;
4675   Style.ColumnLimit = 70;
4676   verifyFormat(
4677       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4678       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4679       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4680       Style);
4681   verifyFormat(
4682       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4683       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4684       Style);
4685   verifyFormat(
4686       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
4687       "                                                      aaaaaaaaaaaaa);",
4688       Style);
4689   verifyFormat(
4690       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4691       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4692       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4693       "                   aaaaaaaaaaaaa);",
4694       Style);
4695   verifyFormat(
4696       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4697       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4698       "                   aaaaaaaaaaaaa);",
4699       Style);
4700   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4701                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4702                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
4703                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4704                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4705                Style);
4706   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4707                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4708                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4709                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
4710                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4711                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4712                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4713                Style);
4714   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4715                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
4716                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4717                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4718                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4719                Style);
4720   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4721                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4722                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4723                Style);
4724   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
4725                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4726                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4727                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4728                Style);
4729   verifyFormat(
4730       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4731       "    aaaaaaaaaaaaaaa :\n"
4732       "    aaaaaaaaaaaaaaa;",
4733       Style);
4734   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
4735                "          aaaaaaaaa ?\n"
4736                "      b :\n"
4737                "      c);",
4738                Style);
4739   verifyFormat(
4740       "unsigned Indent =\n"
4741       "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0 ?\n"
4742       "                              IndentForLevel[TheLine.Level] :\n"
4743       "                              TheLine * 2,\n"
4744       "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
4745       Style);
4746   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
4747                "                  aaaaaaaaaaaaaaa :\n"
4748                "                  bbbbbbbbbbbbbbb ? //\n"
4749                "                      ccccccccccccccc :\n"
4750                "                      ddddddddddddddd;",
4751                Style);
4752   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
4753                "                  aaaaaaaaaaaaaaa :\n"
4754                "                  (bbbbbbbbbbbbbbb ? //\n"
4755                "                       ccccccccccccccc :\n"
4756                "                       ddddddddddddddd);",
4757                Style);
4758   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4759                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
4760                "            ccccccccccccccccccccccccccc;",
4761                Style);
4762   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4763                "           aaaaa :\n"
4764                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
4765                Style);
4766 }
4767 
TEST_F(FormatTest,DeclarationsOfMultipleVariables)4768 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
4769   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
4770                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
4771   verifyFormat("bool a = true, b = false;");
4772 
4773   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4774                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
4775                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
4776                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
4777   verifyFormat(
4778       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
4779       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
4780       "     d = e && f;");
4781   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
4782                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
4783   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
4784                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
4785   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
4786                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
4787 
4788   FormatStyle Style = getGoogleStyle();
4789   Style.PointerAlignment = FormatStyle::PAS_Left;
4790   Style.DerivePointerAlignment = false;
4791   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4792                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
4793                "    *b = bbbbbbbbbbbbbbbbbbb;",
4794                Style);
4795   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
4796                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
4797                Style);
4798 }
4799 
TEST_F(FormatTest,ConditionalExpressionsInBrackets)4800 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
4801   verifyFormat("arr[foo ? bar : baz];");
4802   verifyFormat("f()[foo ? bar : baz];");
4803   verifyFormat("(a + b)[foo ? bar : baz];");
4804   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
4805 }
4806 
TEST_F(FormatTest,AlignsStringLiterals)4807 TEST_F(FormatTest, AlignsStringLiterals) {
4808   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
4809                "                                      \"short literal\");");
4810   verifyFormat(
4811       "looooooooooooooooooooooooongFunction(\n"
4812       "    \"short literal\"\n"
4813       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
4814   verifyFormat("someFunction(\"Always break between multi-line\"\n"
4815                "             \" string literals\",\n"
4816                "             and, other, parameters);");
4817   EXPECT_EQ("fun + \"1243\" /* comment */\n"
4818             "      \"5678\";",
4819             format("fun + \"1243\" /* comment */\n"
4820                    "      \"5678\";",
4821                    getLLVMStyleWithColumns(28)));
4822   EXPECT_EQ(
4823       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
4824       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
4825       "         \"aaaaaaaaaaaaaaaa\";",
4826       format("aaaaaa ="
4827              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
4828              "aaaaaaaaaaaaaaaaaaaaa\" "
4829              "\"aaaaaaaaaaaaaaaa\";"));
4830   verifyFormat("a = a + \"a\"\n"
4831                "        \"a\"\n"
4832                "        \"a\";");
4833   verifyFormat("f(\"a\", \"b\"\n"
4834                "       \"c\");");
4835 
4836   verifyFormat(
4837       "#define LL_FORMAT \"ll\"\n"
4838       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
4839       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
4840 
4841   verifyFormat("#define A(X)          \\\n"
4842                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
4843                "  \"ccccc\"",
4844                getLLVMStyleWithColumns(23));
4845   verifyFormat("#define A \"def\"\n"
4846                "f(\"abc\" A \"ghi\"\n"
4847                "  \"jkl\");");
4848 
4849   verifyFormat("f(L\"a\"\n"
4850                "  L\"b\");");
4851   verifyFormat("#define A(X)            \\\n"
4852                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
4853                "  L\"ccccc\"",
4854                getLLVMStyleWithColumns(25));
4855 
4856   verifyFormat("f(@\"a\"\n"
4857                "  @\"b\");");
4858   verifyFormat("NSString s = @\"a\"\n"
4859                "             @\"b\"\n"
4860                "             @\"c\";");
4861   verifyFormat("NSString s = @\"a\"\n"
4862                "              \"b\"\n"
4863                "              \"c\";");
4864 }
4865 
TEST_F(FormatTest,ReturnTypeBreakingStyle)4866 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
4867   FormatStyle Style = getLLVMStyle();
4868   // No declarations or definitions should be moved to own line.
4869   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
4870   verifyFormat("class A {\n"
4871                "  int f() { return 1; }\n"
4872                "  int g();\n"
4873                "};\n"
4874                "int f() { return 1; }\n"
4875                "int g();\n",
4876                Style);
4877 
4878   // All declarations and definitions should have the return type moved to its
4879   // own
4880   // line.
4881   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
4882   verifyFormat("class E {\n"
4883                "  int\n"
4884                "  f() {\n"
4885                "    return 1;\n"
4886                "  }\n"
4887                "  int\n"
4888                "  g();\n"
4889                "};\n"
4890                "int\n"
4891                "f() {\n"
4892                "  return 1;\n"
4893                "}\n"
4894                "int\n"
4895                "g();\n",
4896                Style);
4897 
4898   // Top-level definitions, and no kinds of declarations should have the
4899   // return type moved to its own line.
4900   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
4901   verifyFormat("class B {\n"
4902                "  int f() { return 1; }\n"
4903                "  int g();\n"
4904                "};\n"
4905                "int\n"
4906                "f() {\n"
4907                "  return 1;\n"
4908                "}\n"
4909                "int g();\n",
4910                Style);
4911 
4912   // Top-level definitions and declarations should have the return type moved
4913   // to its own line.
4914   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
4915   verifyFormat("class C {\n"
4916                "  int f() { return 1; }\n"
4917                "  int g();\n"
4918                "};\n"
4919                "int\n"
4920                "f() {\n"
4921                "  return 1;\n"
4922                "}\n"
4923                "int\n"
4924                "g();\n",
4925                Style);
4926 
4927   // All definitions should have the return type moved to its own line, but no
4928   // kinds of declarations.
4929   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
4930   verifyFormat("class D {\n"
4931                "  int\n"
4932                "  f() {\n"
4933                "    return 1;\n"
4934                "  }\n"
4935                "  int g();\n"
4936                "};\n"
4937                "int\n"
4938                "f() {\n"
4939                "  return 1;\n"
4940                "}\n"
4941                "int g();\n",
4942                Style);
4943   verifyFormat("const char *\n"
4944                "f(void) {\n" // Break here.
4945                "  return \"\";\n"
4946                "}\n"
4947                "const char *bar(void);\n", // No break here.
4948                Style);
4949   verifyFormat("template <class T>\n"
4950                "T *\n"
4951                "f(T &c) {\n" // Break here.
4952                "  return NULL;\n"
4953                "}\n"
4954                "template <class T> T *f(T &c);\n", // No break here.
4955                Style);
4956   verifyFormat("class C {\n"
4957                "  int\n"
4958                "  operator+() {\n"
4959                "    return 1;\n"
4960                "  }\n"
4961                "  int\n"
4962                "  operator()() {\n"
4963                "    return 1;\n"
4964                "  }\n"
4965                "};\n",
4966                Style);
4967   verifyFormat("void\n"
4968                "A::operator()() {}\n"
4969                "void\n"
4970                "A::operator>>() {}\n"
4971                "void\n"
4972                "A::operator+() {}\n",
4973                Style);
4974   verifyFormat("void *operator new(std::size_t s);", // No break here.
4975                Style);
4976   verifyFormat("void *\n"
4977                "operator new(std::size_t s) {}",
4978                Style);
4979   verifyFormat("void *\n"
4980                "operator delete[](void *ptr) {}",
4981                Style);
4982   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4983   verifyFormat("const char *\n"
4984                "f(void)\n" // Break here.
4985                "{\n"
4986                "  return \"\";\n"
4987                "}\n"
4988                "const char *bar(void);\n", // No break here.
4989                Style);
4990   verifyFormat("template <class T>\n"
4991                "T *\n"     // Problem here: no line break
4992                "f(T &c)\n" // Break here.
4993                "{\n"
4994                "  return NULL;\n"
4995                "}\n"
4996                "template <class T> T *f(T &c);\n", // No break here.
4997                Style);
4998 }
4999 
TEST_F(FormatTest,AlwaysBreakBeforeMultilineStrings)5000 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
5001   FormatStyle NoBreak = getLLVMStyle();
5002   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
5003   FormatStyle Break = getLLVMStyle();
5004   Break.AlwaysBreakBeforeMultilineStrings = true;
5005   verifyFormat("aaaa = \"bbbb\"\n"
5006                "       \"cccc\";",
5007                NoBreak);
5008   verifyFormat("aaaa =\n"
5009                "    \"bbbb\"\n"
5010                "    \"cccc\";",
5011                Break);
5012   verifyFormat("aaaa(\"bbbb\"\n"
5013                "     \"cccc\");",
5014                NoBreak);
5015   verifyFormat("aaaa(\n"
5016                "    \"bbbb\"\n"
5017                "    \"cccc\");",
5018                Break);
5019   verifyFormat("aaaa(qqq, \"bbbb\"\n"
5020                "          \"cccc\");",
5021                NoBreak);
5022   verifyFormat("aaaa(qqq,\n"
5023                "     \"bbbb\"\n"
5024                "     \"cccc\");",
5025                Break);
5026   verifyFormat("aaaa(qqq,\n"
5027                "     L\"bbbb\"\n"
5028                "     L\"cccc\");",
5029                Break);
5030   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
5031                "                      \"bbbb\"));",
5032                Break);
5033   verifyFormat("string s = someFunction(\n"
5034                "    \"abc\"\n"
5035                "    \"abc\");",
5036                Break);
5037 
5038   // As we break before unary operators, breaking right after them is bad.
5039   verifyFormat("string foo = abc ? \"x\"\n"
5040                "                   \"blah blah blah blah blah blah\"\n"
5041                "                 : \"y\";",
5042                Break);
5043 
5044   // Don't break if there is no column gain.
5045   verifyFormat("f(\"aaaa\"\n"
5046                "  \"bbbb\");",
5047                Break);
5048 
5049   // Treat literals with escaped newlines like multi-line string literals.
5050   EXPECT_EQ("x = \"a\\\n"
5051             "b\\\n"
5052             "c\";",
5053             format("x = \"a\\\n"
5054                    "b\\\n"
5055                    "c\";",
5056                    NoBreak));
5057   EXPECT_EQ("xxxx =\n"
5058             "    \"a\\\n"
5059             "b\\\n"
5060             "c\";",
5061             format("xxxx = \"a\\\n"
5062                    "b\\\n"
5063                    "c\";",
5064                    Break));
5065 
5066   // Exempt ObjC strings for now.
5067   EXPECT_EQ("NSString *const kString = @\"aaaa\"\n"
5068             "                          @\"bbbb\";",
5069             format("NSString *const kString = @\"aaaa\"\n"
5070                    "@\"bbbb\";",
5071                    Break));
5072 
5073   Break.ColumnLimit = 0;
5074   verifyFormat("const char *hello = \"hello llvm\";", Break);
5075 }
5076 
TEST_F(FormatTest,AlignsPipes)5077 TEST_F(FormatTest, AlignsPipes) {
5078   verifyFormat(
5079       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5080       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5081       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5082   verifyFormat(
5083       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
5084       "                     << aaaaaaaaaaaaaaaaaaaa;");
5085   verifyFormat(
5086       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5087       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5088   verifyFormat(
5089       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
5090       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
5091       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
5092   verifyFormat(
5093       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5094       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5095       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5096   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5097                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5098                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5099                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
5100   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
5101                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
5102   verifyFormat(
5103       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5104       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5105 
5106   verifyFormat("return out << \"somepacket = {\\n\"\n"
5107                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
5108                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
5109                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
5110                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
5111                "           << \"}\";");
5112 
5113   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
5114                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
5115                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
5116   verifyFormat(
5117       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
5118       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
5119       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
5120       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
5121       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
5122   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
5123                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
5124   verifyFormat(
5125       "void f() {\n"
5126       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
5127       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5128       "}");
5129   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
5130                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
5131   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5132                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5133                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
5134                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
5135   verifyFormat("LOG_IF(aaa == //\n"
5136                "       bbb)\n"
5137                "    << a << b;");
5138 
5139   // Breaking before the first "<<" is generally not desirable.
5140   verifyFormat(
5141       "llvm::errs()\n"
5142       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5143       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5144       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5145       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5146       getLLVMStyleWithColumns(70));
5147   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
5148                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5149                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
5150                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5151                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
5152                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5153                getLLVMStyleWithColumns(70));
5154 
5155   // But sometimes, breaking before the first "<<" is desirable.
5156   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
5157                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
5158   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
5159                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5160                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5161   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
5162                "    << BEF << IsTemplate << Description << E->getType();");
5163   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
5164                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5165                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5166   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
5167                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5168                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5169                "    << aaa;");
5170 
5171   verifyFormat(
5172       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5173       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5174 
5175   // Incomplete string literal.
5176   EXPECT_EQ("llvm::errs() << \"\n"
5177             "             << a;",
5178             format("llvm::errs() << \"\n<<a;"));
5179 
5180   verifyFormat("void f() {\n"
5181                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
5182                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
5183                "}");
5184 
5185   // Handle 'endl'.
5186   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
5187                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
5188   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
5189 
5190   // Handle '\n'.
5191   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
5192                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
5193   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
5194                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
5195   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
5196                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
5197   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
5198 }
5199 
TEST_F(FormatTest,UnderstandsEquals)5200 TEST_F(FormatTest, UnderstandsEquals) {
5201   verifyFormat(
5202       "aaaaaaaaaaaaaaaaa =\n"
5203       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5204   verifyFormat(
5205       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5206       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
5207   verifyFormat(
5208       "if (a) {\n"
5209       "  f();\n"
5210       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5211       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
5212       "}");
5213 
5214   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5215                "        100000000 + 10000000) {\n}");
5216 }
5217 
TEST_F(FormatTest,WrapsAtFunctionCallsIfNecessary)5218 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
5219   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
5220                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
5221 
5222   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
5223                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
5224 
5225   verifyFormat(
5226       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
5227       "                                                          Parameter2);");
5228 
5229   verifyFormat(
5230       "ShortObject->shortFunction(\n"
5231       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
5232       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
5233 
5234   verifyFormat("loooooooooooooongFunction(\n"
5235                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
5236 
5237   verifyFormat(
5238       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
5239       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
5240 
5241   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
5242                "    .WillRepeatedly(Return(SomeValue));");
5243   verifyFormat("void f() {\n"
5244                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
5245                "      .Times(2)\n"
5246                "      .WillRepeatedly(Return(SomeValue));\n"
5247                "}");
5248   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
5249                "    ccccccccccccccccccccccc);");
5250   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5251                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5252                "          .aaaaa(aaaaa),\n"
5253                "      aaaaaaaaaaaaaaaaaaaaa);");
5254   verifyFormat("void f() {\n"
5255                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5256                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
5257                "}");
5258   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5259                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5260                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5261                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5262                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5263   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5264                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5265                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5266                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
5267                "}");
5268 
5269   // Here, it is not necessary to wrap at "." or "->".
5270   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
5271                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
5272   verifyFormat(
5273       "aaaaaaaaaaa->aaaaaaaaa(\n"
5274       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5275       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
5276 
5277   verifyFormat(
5278       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5279       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
5280   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
5281                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
5282   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
5283                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
5284 
5285   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5286                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5287                "    .a();");
5288 
5289   FormatStyle NoBinPacking = getLLVMStyle();
5290   NoBinPacking.BinPackParameters = false;
5291   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
5292                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
5293                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
5294                "                         aaaaaaaaaaaaaaaaaaa,\n"
5295                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5296                NoBinPacking);
5297 
5298   // If there is a subsequent call, change to hanging indentation.
5299   verifyFormat(
5300       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5301       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
5302       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5303   verifyFormat(
5304       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5305       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
5306   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5307                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5308                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5309   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5310                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5311                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
5312 }
5313 
TEST_F(FormatTest,WrapsTemplateDeclarations)5314 TEST_F(FormatTest, WrapsTemplateDeclarations) {
5315   verifyFormat("template <typename T>\n"
5316                "virtual void loooooooooooongFunction(int Param1, int Param2);");
5317   verifyFormat("template <typename T>\n"
5318                "// T should be one of {A, B}.\n"
5319                "virtual void loooooooooooongFunction(int Param1, int Param2);");
5320   verifyFormat(
5321       "template <typename T>\n"
5322       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
5323   verifyFormat("template <typename T>\n"
5324                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
5325                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
5326   verifyFormat(
5327       "template <typename T>\n"
5328       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
5329       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
5330   verifyFormat(
5331       "template <typename T>\n"
5332       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
5333       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
5334       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5335   verifyFormat("template <typename T>\n"
5336                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5337                "    int aaaaaaaaaaaaaaaaaaaaaa);");
5338   verifyFormat(
5339       "template <typename T1, typename T2 = char, typename T3 = char,\n"
5340       "          typename T4 = char>\n"
5341       "void f();");
5342   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
5343                "          template <typename> class cccccccccccccccccccccc,\n"
5344                "          typename ddddddddddddd>\n"
5345                "class C {};");
5346   verifyFormat(
5347       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
5348       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5349 
5350   verifyFormat("void f() {\n"
5351                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
5352                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
5353                "}");
5354 
5355   verifyFormat("template <typename T> class C {};");
5356   verifyFormat("template <typename T> void f();");
5357   verifyFormat("template <typename T> void f() {}");
5358   verifyFormat(
5359       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
5360       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5361       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
5362       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
5363       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5364       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
5365       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
5366       getLLVMStyleWithColumns(72));
5367   EXPECT_EQ("static_cast<A< //\n"
5368             "    B> *>(\n"
5369             "\n"
5370             "    );",
5371             format("static_cast<A<//\n"
5372                    "    B>*>(\n"
5373                    "\n"
5374                    "    );"));
5375   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5376                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
5377 
5378   FormatStyle AlwaysBreak = getLLVMStyle();
5379   AlwaysBreak.AlwaysBreakTemplateDeclarations = true;
5380   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
5381   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
5382   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
5383   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5384                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
5385                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
5386   verifyFormat("template <template <typename> class Fooooooo,\n"
5387                "          template <typename> class Baaaaaaar>\n"
5388                "struct C {};",
5389                AlwaysBreak);
5390   verifyFormat("template <typename T> // T can be A, B or C.\n"
5391                "struct C {};",
5392                AlwaysBreak);
5393   verifyFormat("template <enum E> class A {\n"
5394                "public:\n"
5395                "  E *f();\n"
5396                "};");
5397 }
5398 
TEST_F(FormatTest,WrapsAtNestedNameSpecifiers)5399 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
5400   verifyFormat(
5401       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5402       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5403   verifyFormat(
5404       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5405       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5406       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
5407 
5408   // FIXME: Should we have the extra indent after the second break?
5409   verifyFormat(
5410       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5411       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5412       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5413 
5414   verifyFormat(
5415       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
5416       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
5417 
5418   // Breaking at nested name specifiers is generally not desirable.
5419   verifyFormat(
5420       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5421       "    aaaaaaaaaaaaaaaaaaaaaaa);");
5422 
5423   verifyFormat(
5424       "aaaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5425       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5426       "                   aaaaaaaaaaaaaaaaaaaaa);",
5427       getLLVMStyleWithColumns(74));
5428 
5429   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5430                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5431                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5432 }
5433 
TEST_F(FormatTest,UnderstandsTemplateParameters)5434 TEST_F(FormatTest, UnderstandsTemplateParameters) {
5435   verifyFormat("A<int> a;");
5436   verifyFormat("A<A<A<int>>> a;");
5437   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
5438   verifyFormat("bool x = a < 1 || 2 > a;");
5439   verifyFormat("bool x = 5 < f<int>();");
5440   verifyFormat("bool x = f<int>() > 5;");
5441   verifyFormat("bool x = 5 < a<int>::x;");
5442   verifyFormat("bool x = a < 4 ? a > 2 : false;");
5443   verifyFormat("bool x = f() ? a < 2 : a > 2;");
5444 
5445   verifyGoogleFormat("A<A<int>> a;");
5446   verifyGoogleFormat("A<A<A<int>>> a;");
5447   verifyGoogleFormat("A<A<A<A<int>>>> a;");
5448   verifyGoogleFormat("A<A<int> > a;");
5449   verifyGoogleFormat("A<A<A<int> > > a;");
5450   verifyGoogleFormat("A<A<A<A<int> > > > a;");
5451   verifyGoogleFormat("A<::A<int>> a;");
5452   verifyGoogleFormat("A<::A> a;");
5453   verifyGoogleFormat("A< ::A> a;");
5454   verifyGoogleFormat("A< ::A<int> > a;");
5455   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
5456   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
5457   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
5458   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
5459   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
5460             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
5461 
5462   verifyFormat("A<A>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
5463 
5464   verifyFormat("test >> a >> b;");
5465   verifyFormat("test << a >> b;");
5466 
5467   verifyFormat("f<int>();");
5468   verifyFormat("template <typename T> void f() {}");
5469   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
5470   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
5471                "sizeof(char)>::type>;");
5472   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
5473   verifyFormat("f(a.operator()<A>());");
5474   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5475                "      .template operator()<A>());",
5476                getLLVMStyleWithColumns(35));
5477 
5478   // Not template parameters.
5479   verifyFormat("return a < b && c > d;");
5480   verifyFormat("void f() {\n"
5481                "  while (a < b && c > d) {\n"
5482                "  }\n"
5483                "}");
5484   verifyFormat("template <typename... Types>\n"
5485                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
5486 
5487   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5488                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
5489                getLLVMStyleWithColumns(60));
5490   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
5491   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
5492   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
5493 }
5494 
TEST_F(FormatTest,UnderstandsBinaryOperators)5495 TEST_F(FormatTest, UnderstandsBinaryOperators) {
5496   verifyFormat("COMPARE(a, ==, b);");
5497   verifyFormat("auto s = sizeof...(Ts) - 1;");
5498 }
5499 
TEST_F(FormatTest,UnderstandsPointersToMembers)5500 TEST_F(FormatTest, UnderstandsPointersToMembers) {
5501   verifyFormat("int A::*x;");
5502   verifyFormat("int (S::*func)(void *);");
5503   verifyFormat("void f() { int (S::*func)(void *); }");
5504   verifyFormat("typedef bool *(Class::*Member)() const;");
5505   verifyFormat("void f() {\n"
5506                "  (a->*f)();\n"
5507                "  a->*x;\n"
5508                "  (a.*f)();\n"
5509                "  ((*a).*f)();\n"
5510                "  a.*x;\n"
5511                "}");
5512   verifyFormat("void f() {\n"
5513                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
5514                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
5515                "}");
5516   verifyFormat(
5517       "(aaaaaaaaaa->*bbbbbbb)(\n"
5518       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5519   FormatStyle Style = getLLVMStyle();
5520   Style.PointerAlignment = FormatStyle::PAS_Left;
5521   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
5522 }
5523 
TEST_F(FormatTest,UnderstandsUnaryOperators)5524 TEST_F(FormatTest, UnderstandsUnaryOperators) {
5525   verifyFormat("int a = -2;");
5526   verifyFormat("f(-1, -2, -3);");
5527   verifyFormat("a[-1] = 5;");
5528   verifyFormat("int a = 5 + -2;");
5529   verifyFormat("if (i == -1) {\n}");
5530   verifyFormat("if (i != -1) {\n}");
5531   verifyFormat("if (i > -1) {\n}");
5532   verifyFormat("if (i < -1) {\n}");
5533   verifyFormat("++(a->f());");
5534   verifyFormat("--(a->f());");
5535   verifyFormat("(a->f())++;");
5536   verifyFormat("a[42]++;");
5537   verifyFormat("if (!(a->f())) {\n}");
5538 
5539   verifyFormat("a-- > b;");
5540   verifyFormat("b ? -a : c;");
5541   verifyFormat("n * sizeof char16;");
5542   verifyFormat("n * alignof char16;", getGoogleStyle());
5543   verifyFormat("sizeof(char);");
5544   verifyFormat("alignof(char);", getGoogleStyle());
5545 
5546   verifyFormat("return -1;");
5547   verifyFormat("switch (a) {\n"
5548                "case -1:\n"
5549                "  break;\n"
5550                "}");
5551   verifyFormat("#define X -1");
5552   verifyFormat("#define X -kConstant");
5553 
5554   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
5555   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
5556 
5557   verifyFormat("int a = /* confusing comment */ -1;");
5558   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
5559   verifyFormat("int a = i /* confusing comment */++;");
5560 }
5561 
TEST_F(FormatTest,DoesNotIndentRelativeToUnaryOperators)5562 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
5563   verifyFormat("if (!aaaaaaaaaa( // break\n"
5564                "        aaaaa)) {\n"
5565                "}");
5566   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
5567                "    aaaaa));");
5568   verifyFormat("*aaa = aaaaaaa( // break\n"
5569                "    bbbbbb);");
5570 }
5571 
TEST_F(FormatTest,UnderstandsOverloadedOperators)5572 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
5573   verifyFormat("bool operator<();");
5574   verifyFormat("bool operator>();");
5575   verifyFormat("bool operator=();");
5576   verifyFormat("bool operator==();");
5577   verifyFormat("bool operator!=();");
5578   verifyFormat("int operator+();");
5579   verifyFormat("int operator++();");
5580   verifyFormat("bool operator,();");
5581   verifyFormat("bool operator();");
5582   verifyFormat("bool operator()();");
5583   verifyFormat("bool operator[]();");
5584   verifyFormat("operator bool();");
5585   verifyFormat("operator int();");
5586   verifyFormat("operator void *();");
5587   verifyFormat("operator SomeType<int>();");
5588   verifyFormat("operator SomeType<int, int>();");
5589   verifyFormat("operator SomeType<SomeType<int>>();");
5590   verifyFormat("void *operator new(std::size_t size);");
5591   verifyFormat("void *operator new[](std::size_t size);");
5592   verifyFormat("void operator delete(void *ptr);");
5593   verifyFormat("void operator delete[](void *ptr);");
5594   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
5595                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
5596   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
5597                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
5598 
5599   verifyFormat(
5600       "ostream &operator<<(ostream &OutputStream,\n"
5601       "                    SomeReallyLongType WithSomeReallyLongValue);");
5602   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
5603                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
5604                "  return left.group < right.group;\n"
5605                "}");
5606   verifyFormat("SomeType &operator=(const SomeType &S);");
5607   verifyFormat("f.template operator()<int>();");
5608 
5609   verifyGoogleFormat("operator void*();");
5610   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
5611   verifyGoogleFormat("operator ::A();");
5612 
5613   verifyFormat("using A::operator+;");
5614   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
5615                "int i;");
5616 }
5617 
TEST_F(FormatTest,UnderstandsFunctionRefQualification)5618 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
5619   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
5620   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
5621   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
5622   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
5623   verifyFormat("Deleted &operator=(const Deleted &) &;");
5624   verifyFormat("Deleted &operator=(const Deleted &) &&;");
5625   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
5626   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
5627   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
5628   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
5629   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
5630   verifyFormat("SomeType MemberFunction(const Deleted &) const &;");
5631 
5632   FormatStyle AlignLeft = getLLVMStyle();
5633   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
5634   verifyFormat("void A::b() && {}", AlignLeft);
5635   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
5636   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
5637                AlignLeft);
5638   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
5639   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
5640   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
5641   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
5642   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
5643   verifyFormat("auto Function(T) & -> void;", AlignLeft);
5644   verifyFormat("SomeType MemberFunction(const Deleted&) const &;", AlignLeft);
5645 
5646   FormatStyle Spaces = getLLVMStyle();
5647   Spaces.SpacesInCStyleCastParentheses = true;
5648   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
5649   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
5650   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
5651   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
5652 
5653   Spaces.SpacesInCStyleCastParentheses = false;
5654   Spaces.SpacesInParentheses = true;
5655   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
5656   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", Spaces);
5657   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
5658   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
5659 }
5660 
TEST_F(FormatTest,UnderstandsNewAndDelete)5661 TEST_F(FormatTest, UnderstandsNewAndDelete) {
5662   verifyFormat("void f() {\n"
5663                "  A *a = new A;\n"
5664                "  A *a = new (placement) A;\n"
5665                "  delete a;\n"
5666                "  delete (A *)a;\n"
5667                "}");
5668   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
5669                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
5670   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5671                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
5672                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
5673   verifyFormat("delete[] h->p;");
5674 }
5675 
TEST_F(FormatTest,UnderstandsUsesOfStarAndAmp)5676 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
5677   verifyFormat("int *f(int *a) {}");
5678   verifyFormat("int main(int argc, char **argv) {}");
5679   verifyFormat("Test::Test(int b) : a(b * b) {}");
5680   verifyIndependentOfContext("f(a, *a);");
5681   verifyFormat("void g() { f(*a); }");
5682   verifyIndependentOfContext("int a = b * 10;");
5683   verifyIndependentOfContext("int a = 10 * b;");
5684   verifyIndependentOfContext("int a = b * c;");
5685   verifyIndependentOfContext("int a += b * c;");
5686   verifyIndependentOfContext("int a -= b * c;");
5687   verifyIndependentOfContext("int a *= b * c;");
5688   verifyIndependentOfContext("int a /= b * c;");
5689   verifyIndependentOfContext("int a = *b;");
5690   verifyIndependentOfContext("int a = *b * c;");
5691   verifyIndependentOfContext("int a = b * *c;");
5692   verifyIndependentOfContext("int a = b * (10);");
5693   verifyIndependentOfContext("S << b * (10);");
5694   verifyIndependentOfContext("return 10 * b;");
5695   verifyIndependentOfContext("return *b * *c;");
5696   verifyIndependentOfContext("return a & ~b;");
5697   verifyIndependentOfContext("f(b ? *c : *d);");
5698   verifyIndependentOfContext("int a = b ? *c : *d;");
5699   verifyIndependentOfContext("*b = a;");
5700   verifyIndependentOfContext("a * ~b;");
5701   verifyIndependentOfContext("a * !b;");
5702   verifyIndependentOfContext("a * +b;");
5703   verifyIndependentOfContext("a * -b;");
5704   verifyIndependentOfContext("a * ++b;");
5705   verifyIndependentOfContext("a * --b;");
5706   verifyIndependentOfContext("a[4] * b;");
5707   verifyIndependentOfContext("a[a * a] = 1;");
5708   verifyIndependentOfContext("f() * b;");
5709   verifyIndependentOfContext("a * [self dostuff];");
5710   verifyIndependentOfContext("int x = a * (a + b);");
5711   verifyIndependentOfContext("(a *)(a + b);");
5712   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
5713   verifyIndependentOfContext("int *pa = (int *)&a;");
5714   verifyIndependentOfContext("return sizeof(int **);");
5715   verifyIndependentOfContext("return sizeof(int ******);");
5716   verifyIndependentOfContext("return (int **&)a;");
5717   verifyIndependentOfContext("f((*PointerToArray)[10]);");
5718   verifyFormat("void f(Type (*parameter)[10]) {}");
5719   verifyFormat("void f(Type (&parameter)[10]) {}");
5720   verifyGoogleFormat("return sizeof(int**);");
5721   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
5722   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
5723   verifyFormat("auto a = [](int **&, int ***) {};");
5724   verifyFormat("auto PointerBinding = [](const char *S) {};");
5725   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
5726   verifyFormat("[](const decltype(*a) &value) {}");
5727   verifyFormat("decltype(a * b) F();");
5728   verifyFormat("#define MACRO() [](A *a) { return 1; }");
5729   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
5730   verifyIndependentOfContext("typedef void (*f)(int *a);");
5731   verifyIndependentOfContext("int i{a * b};");
5732   verifyIndependentOfContext("aaa && aaa->f();");
5733   verifyIndependentOfContext("int x = ~*p;");
5734   verifyFormat("Constructor() : a(a), area(width * height) {}");
5735   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
5736   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
5737   verifyFormat("void f() { f(a, c * d); }");
5738   verifyFormat("void f() { f(new a(), c * d); }");
5739 
5740   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
5741 
5742   verifyIndependentOfContext("A<int *> a;");
5743   verifyIndependentOfContext("A<int **> a;");
5744   verifyIndependentOfContext("A<int *, int *> a;");
5745   verifyIndependentOfContext("A<int *[]> a;");
5746   verifyIndependentOfContext(
5747       "const char *const p = reinterpret_cast<const char *const>(q);");
5748   verifyIndependentOfContext("A<int **, int **> a;");
5749   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
5750   verifyFormat("for (char **a = b; *a; ++a) {\n}");
5751   verifyFormat("for (; a && b;) {\n}");
5752   verifyFormat("bool foo = true && [] { return false; }();");
5753 
5754   verifyFormat(
5755       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5756       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5757 
5758   verifyGoogleFormat("int const* a = &b;");
5759   verifyGoogleFormat("**outparam = 1;");
5760   verifyGoogleFormat("*outparam = a * b;");
5761   verifyGoogleFormat("int main(int argc, char** argv) {}");
5762   verifyGoogleFormat("A<int*> a;");
5763   verifyGoogleFormat("A<int**> a;");
5764   verifyGoogleFormat("A<int*, int*> a;");
5765   verifyGoogleFormat("A<int**, int**> a;");
5766   verifyGoogleFormat("f(b ? *c : *d);");
5767   verifyGoogleFormat("int a = b ? *c : *d;");
5768   verifyGoogleFormat("Type* t = **x;");
5769   verifyGoogleFormat("Type* t = *++*x;");
5770   verifyGoogleFormat("*++*x;");
5771   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
5772   verifyGoogleFormat("Type* t = x++ * y;");
5773   verifyGoogleFormat(
5774       "const char* const p = reinterpret_cast<const char* const>(q);");
5775   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
5776   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
5777   verifyGoogleFormat("template <typename T>\n"
5778                      "void f(int i = 0, SomeType** temps = NULL);");
5779 
5780   FormatStyle Left = getLLVMStyle();
5781   Left.PointerAlignment = FormatStyle::PAS_Left;
5782   verifyFormat("x = *a(x) = *a(y);", Left);
5783   verifyFormat("for (;; * = b) {\n}", Left);
5784   verifyFormat("return *this += 1;", Left);
5785 
5786   verifyIndependentOfContext("a = *(x + y);");
5787   verifyIndependentOfContext("a = &(x + y);");
5788   verifyIndependentOfContext("*(x + y).call();");
5789   verifyIndependentOfContext("&(x + y)->call();");
5790   verifyFormat("void f() { &(*I).first; }");
5791 
5792   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
5793   verifyFormat(
5794       "int *MyValues = {\n"
5795       "    *A, // Operator detection might be confused by the '{'\n"
5796       "    *BB // Operator detection might be confused by previous comment\n"
5797       "};");
5798 
5799   verifyIndependentOfContext("if (int *a = &b)");
5800   verifyIndependentOfContext("if (int &a = *b)");
5801   verifyIndependentOfContext("if (a & b[i])");
5802   verifyIndependentOfContext("if (a::b::c::d & b[i])");
5803   verifyIndependentOfContext("if (*b[i])");
5804   verifyIndependentOfContext("if (int *a = (&b))");
5805   verifyIndependentOfContext("while (int *a = &b)");
5806   verifyIndependentOfContext("size = sizeof *a;");
5807   verifyIndependentOfContext("if (a && (b = c))");
5808   verifyFormat("void f() {\n"
5809                "  for (const int &v : Values) {\n"
5810                "  }\n"
5811                "}");
5812   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
5813   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
5814   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
5815 
5816   verifyFormat("#define A (!a * b)");
5817   verifyFormat("#define MACRO     \\\n"
5818                "  int *i = a * b; \\\n"
5819                "  void f(a *b);",
5820                getLLVMStyleWithColumns(19));
5821 
5822   verifyIndependentOfContext("A = new SomeType *[Length];");
5823   verifyIndependentOfContext("A = new SomeType *[Length]();");
5824   verifyIndependentOfContext("T **t = new T *;");
5825   verifyIndependentOfContext("T **t = new T *();");
5826   verifyGoogleFormat("A = new SomeType*[Length]();");
5827   verifyGoogleFormat("A = new SomeType*[Length];");
5828   verifyGoogleFormat("T** t = new T*;");
5829   verifyGoogleFormat("T** t = new T*();");
5830 
5831   FormatStyle PointerLeft = getLLVMStyle();
5832   PointerLeft.PointerAlignment = FormatStyle::PAS_Left;
5833   verifyFormat("delete *x;", PointerLeft);
5834   verifyFormat("STATIC_ASSERT((a & b) == 0);");
5835   verifyFormat("STATIC_ASSERT(0 == (a & b));");
5836   verifyFormat("template <bool a, bool b> "
5837                "typename t::if<x && y>::type f() {}");
5838   verifyFormat("template <int *y> f() {}");
5839   verifyFormat("vector<int *> v;");
5840   verifyFormat("vector<int *const> v;");
5841   verifyFormat("vector<int *const **const *> v;");
5842   verifyFormat("vector<int *volatile> v;");
5843   verifyFormat("vector<a * b> v;");
5844   verifyFormat("foo<b && false>();");
5845   verifyFormat("foo<b & 1>();");
5846   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
5847   verifyFormat(
5848       "template <class T, class = typename std::enable_if<\n"
5849       "                       std::is_integral<T>::value &&\n"
5850       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
5851       "void F();",
5852       getLLVMStyleWithColumns(76));
5853   verifyFormat(
5854       "template <class T,\n"
5855       "          class = typename ::std::enable_if<\n"
5856       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
5857       "void F();",
5858       getGoogleStyleWithColumns(68));
5859 
5860   verifyIndependentOfContext("MACRO(int *i);");
5861   verifyIndependentOfContext("MACRO(auto *a);");
5862   verifyIndependentOfContext("MACRO(const A *a);");
5863   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
5864   // FIXME: Is there a way to make this work?
5865   // verifyIndependentOfContext("MACRO(A *a);");
5866 
5867   verifyFormat("DatumHandle const *operator->() const { return input_; }");
5868   verifyFormat("return options != nullptr && operator==(*options);");
5869 
5870   EXPECT_EQ("#define OP(x)                                    \\\n"
5871             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
5872             "    return s << a.DebugString();                 \\\n"
5873             "  }",
5874             format("#define OP(x) \\\n"
5875                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
5876                    "    return s << a.DebugString(); \\\n"
5877                    "  }",
5878                    getLLVMStyleWithColumns(50)));
5879 
5880   // FIXME: We cannot handle this case yet; we might be able to figure out that
5881   // foo<x> d > v; doesn't make sense.
5882   verifyFormat("foo<a<b && c> d> v;");
5883 
5884   FormatStyle PointerMiddle = getLLVMStyle();
5885   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
5886   verifyFormat("delete *x;", PointerMiddle);
5887   verifyFormat("int * x;", PointerMiddle);
5888   verifyFormat("template <int * y> f() {}", PointerMiddle);
5889   verifyFormat("int * f(int * a) {}", PointerMiddle);
5890   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
5891   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
5892   verifyFormat("A<int *> a;", PointerMiddle);
5893   verifyFormat("A<int **> a;", PointerMiddle);
5894   verifyFormat("A<int *, int *> a;", PointerMiddle);
5895   verifyFormat("A<int * []> a;", PointerMiddle);
5896   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
5897   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
5898   verifyFormat("T ** t = new T *;", PointerMiddle);
5899 
5900   // Member function reference qualifiers aren't binary operators.
5901   verifyFormat("string // break\n"
5902                "operator()() & {}");
5903   verifyFormat("string // break\n"
5904                "operator()() && {}");
5905   verifyGoogleFormat("template <typename T>\n"
5906                      "auto x() & -> int {}");
5907 }
5908 
TEST_F(FormatTest,UnderstandsAttributes)5909 TEST_F(FormatTest, UnderstandsAttributes) {
5910   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
5911   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
5912                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
5913   FormatStyle AfterType = getLLVMStyle();
5914   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
5915   verifyFormat("__attribute__((nodebug)) void\n"
5916                "foo() {}\n",
5917                AfterType);
5918 }
5919 
TEST_F(FormatTest,UnderstandsEllipsis)5920 TEST_F(FormatTest, UnderstandsEllipsis) {
5921   verifyFormat("int printf(const char *fmt, ...);");
5922   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
5923   verifyFormat("template <class... Ts> void Foo(Ts *... ts) {}");
5924 
5925   FormatStyle PointersLeft = getLLVMStyle();
5926   PointersLeft.PointerAlignment = FormatStyle::PAS_Left;
5927   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", PointersLeft);
5928 }
5929 
TEST_F(FormatTest,AdaptivelyFormatsPointersAndReferences)5930 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
5931   EXPECT_EQ("int *a;\n"
5932             "int *a;\n"
5933             "int *a;",
5934             format("int *a;\n"
5935                    "int* a;\n"
5936                    "int *a;",
5937                    getGoogleStyle()));
5938   EXPECT_EQ("int* a;\n"
5939             "int* a;\n"
5940             "int* a;",
5941             format("int* a;\n"
5942                    "int* a;\n"
5943                    "int *a;",
5944                    getGoogleStyle()));
5945   EXPECT_EQ("int *a;\n"
5946             "int *a;\n"
5947             "int *a;",
5948             format("int *a;\n"
5949                    "int * a;\n"
5950                    "int *  a;",
5951                    getGoogleStyle()));
5952   EXPECT_EQ("auto x = [] {\n"
5953             "  int *a;\n"
5954             "  int *a;\n"
5955             "  int *a;\n"
5956             "};",
5957             format("auto x=[]{int *a;\n"
5958                    "int * a;\n"
5959                    "int *  a;};",
5960                    getGoogleStyle()));
5961 }
5962 
TEST_F(FormatTest,UnderstandsRvalueReferences)5963 TEST_F(FormatTest, UnderstandsRvalueReferences) {
5964   verifyFormat("int f(int &&a) {}");
5965   verifyFormat("int f(int a, char &&b) {}");
5966   verifyFormat("void f() { int &&a = b; }");
5967   verifyGoogleFormat("int f(int a, char&& b) {}");
5968   verifyGoogleFormat("void f() { int&& a = b; }");
5969 
5970   verifyIndependentOfContext("A<int &&> a;");
5971   verifyIndependentOfContext("A<int &&, int &&> a;");
5972   verifyGoogleFormat("A<int&&> a;");
5973   verifyGoogleFormat("A<int&&, int&&> a;");
5974 
5975   // Not rvalue references:
5976   verifyFormat("template <bool B, bool C> class A {\n"
5977                "  static_assert(B && C, \"Something is wrong\");\n"
5978                "};");
5979   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
5980   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
5981   verifyFormat("#define A(a, b) (a && b)");
5982 }
5983 
TEST_F(FormatTest,FormatsBinaryOperatorsPrecedingEquals)5984 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
5985   verifyFormat("void f() {\n"
5986                "  x[aaaaaaaaa -\n"
5987                "    b] = 23;\n"
5988                "}",
5989                getLLVMStyleWithColumns(15));
5990 }
5991 
TEST_F(FormatTest,FormatsCasts)5992 TEST_F(FormatTest, FormatsCasts) {
5993   verifyFormat("Type *A = static_cast<Type *>(P);");
5994   verifyFormat("Type *A = (Type *)P;");
5995   verifyFormat("Type *A = (vector<Type *, int *>)P;");
5996   verifyFormat("int a = (int)(2.0f);");
5997   verifyFormat("int a = (int)2.0f;");
5998   verifyFormat("x[(int32)y];");
5999   verifyFormat("x = (int32)y;");
6000   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
6001   verifyFormat("int a = (int)*b;");
6002   verifyFormat("int a = (int)2.0f;");
6003   verifyFormat("int a = (int)~0;");
6004   verifyFormat("int a = (int)++a;");
6005   verifyFormat("int a = (int)sizeof(int);");
6006   verifyFormat("int a = (int)+2;");
6007   verifyFormat("my_int a = (my_int)2.0f;");
6008   verifyFormat("my_int a = (my_int)sizeof(int);");
6009   verifyFormat("return (my_int)aaa;");
6010   verifyFormat("#define x ((int)-1)");
6011   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
6012   verifyFormat("#define p(q) ((int *)&q)");
6013   verifyFormat("fn(a)(b) + 1;");
6014 
6015   verifyFormat("void f() { my_int a = (my_int)*b; }");
6016   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
6017   verifyFormat("my_int a = (my_int)~0;");
6018   verifyFormat("my_int a = (my_int)++a;");
6019   verifyFormat("my_int a = (my_int)-2;");
6020   verifyFormat("my_int a = (my_int)1;");
6021   verifyFormat("my_int a = (my_int *)1;");
6022   verifyFormat("my_int a = (const my_int)-1;");
6023   verifyFormat("my_int a = (const my_int *)-1;");
6024   verifyFormat("my_int a = (my_int)(my_int)-1;");
6025   verifyFormat("my_int a = (ns::my_int)-2;");
6026   verifyFormat("case (my_int)ONE:");
6027   verifyFormat("auto x = (X)this;");
6028 
6029   // FIXME: single value wrapped with paren will be treated as cast.
6030   verifyFormat("void f(int i = (kValue)*kMask) {}");
6031 
6032   verifyFormat("{ (void)F; }");
6033 
6034   // Don't break after a cast's
6035   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6036                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
6037                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
6038 
6039   // These are not casts.
6040   verifyFormat("void f(int *) {}");
6041   verifyFormat("f(foo)->b;");
6042   verifyFormat("f(foo).b;");
6043   verifyFormat("f(foo)(b);");
6044   verifyFormat("f(foo)[b];");
6045   verifyFormat("[](foo) { return 4; }(bar);");
6046   verifyFormat("(*funptr)(foo)[4];");
6047   verifyFormat("funptrs[4](foo)[4];");
6048   verifyFormat("void f(int *);");
6049   verifyFormat("void f(int *) = 0;");
6050   verifyFormat("void f(SmallVector<int>) {}");
6051   verifyFormat("void f(SmallVector<int>);");
6052   verifyFormat("void f(SmallVector<int>) = 0;");
6053   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
6054   verifyFormat("int a = sizeof(int) * b;");
6055   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
6056   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
6057   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
6058   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
6059 
6060   // These are not casts, but at some point were confused with casts.
6061   verifyFormat("virtual void foo(int *) override;");
6062   verifyFormat("virtual void foo(char &) const;");
6063   verifyFormat("virtual void foo(int *a, char *) const;");
6064   verifyFormat("int a = sizeof(int *) + b;");
6065   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
6066   verifyFormat("bool b = f(g<int>) && c;");
6067   verifyFormat("typedef void (*f)(int i) func;");
6068 
6069   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
6070                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
6071   // FIXME: The indentation here is not ideal.
6072   verifyFormat(
6073       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6074       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
6075       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
6076 }
6077 
TEST_F(FormatTest,FormatsFunctionTypes)6078 TEST_F(FormatTest, FormatsFunctionTypes) {
6079   verifyFormat("A<bool()> a;");
6080   verifyFormat("A<SomeType()> a;");
6081   verifyFormat("A<void (*)(int, std::string)> a;");
6082   verifyFormat("A<void *(int)>;");
6083   verifyFormat("void *(*a)(int *, SomeType *);");
6084   verifyFormat("int (*func)(void *);");
6085   verifyFormat("void f() { int (*func)(void *); }");
6086   verifyFormat("template <class CallbackClass>\n"
6087                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
6088 
6089   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
6090   verifyGoogleFormat("void* (*a)(int);");
6091   verifyGoogleFormat(
6092       "template <class CallbackClass>\n"
6093       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
6094 
6095   // Other constructs can look somewhat like function types:
6096   verifyFormat("A<sizeof(*x)> a;");
6097   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
6098   verifyFormat("some_var = function(*some_pointer_var)[0];");
6099   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
6100   verifyFormat("int x = f(&h)();");
6101   verifyFormat("returnsFunction(&param1, &param2)(param);");
6102 }
6103 
TEST_F(FormatTest,FormatsPointersToArrayTypes)6104 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
6105   verifyFormat("A (*foo_)[6];");
6106   verifyFormat("vector<int> (*foo_)[6];");
6107 }
6108 
TEST_F(FormatTest,BreaksLongVariableDeclarations)6109 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
6110   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
6111                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
6112   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
6113                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
6114   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
6115                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
6116 
6117   // Different ways of ()-initializiation.
6118   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
6119                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
6120   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
6121                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
6122   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
6123                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
6124   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
6125                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
6126 }
6127 
TEST_F(FormatTest,BreaksLongDeclarations)6128 TEST_F(FormatTest, BreaksLongDeclarations) {
6129   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
6130                "    AnotherNameForTheLongType;");
6131   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
6132                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6133   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
6134                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
6135   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
6136                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
6137   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
6138                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
6139   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
6140                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
6141   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
6142                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
6143   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
6144                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
6145   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
6146                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
6147   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
6148                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
6149   FormatStyle Indented = getLLVMStyle();
6150   Indented.IndentWrappedFunctionNames = true;
6151   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
6152                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
6153                Indented);
6154   verifyFormat(
6155       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
6156       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
6157       Indented);
6158   verifyFormat(
6159       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
6160       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
6161       Indented);
6162   verifyFormat(
6163       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
6164       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
6165       Indented);
6166 
6167   // FIXME: Without the comment, this breaks after "(".
6168   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
6169                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
6170                getGoogleStyle());
6171 
6172   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
6173                "                  int LoooooooooooooooooooongParam2) {}");
6174   verifyFormat(
6175       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
6176       "                                   SourceLocation L, IdentifierIn *II,\n"
6177       "                                   Type *T) {}");
6178   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
6179                "ReallyReaaallyLongFunctionName(\n"
6180                "    const std::string &SomeParameter,\n"
6181                "    const SomeType<string, SomeOtherTemplateParameter>\n"
6182                "        &ReallyReallyLongParameterName,\n"
6183                "    const SomeType<string, SomeOtherTemplateParameter>\n"
6184                "        &AnotherLongParameterName) {}");
6185   verifyFormat("template <typename A>\n"
6186                "SomeLoooooooooooooooooooooongType<\n"
6187                "    typename some_namespace::SomeOtherType<A>::Type>\n"
6188                "Function() {}");
6189 
6190   verifyGoogleFormat(
6191       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
6192       "    aaaaaaaaaaaaaaaaaaaaaaa;");
6193   verifyGoogleFormat(
6194       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
6195       "                                   SourceLocation L) {}");
6196   verifyGoogleFormat(
6197       "some_namespace::LongReturnType\n"
6198       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
6199       "    int first_long_parameter, int second_parameter) {}");
6200 
6201   verifyGoogleFormat("template <typename T>\n"
6202                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
6203                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
6204   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6205                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
6206 
6207   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
6208                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6209                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6210   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6211                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
6212                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
6213   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6214                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
6215                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
6216                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6217 }
6218 
TEST_F(FormatTest,FormatsArrays)6219 TEST_F(FormatTest, FormatsArrays) {
6220   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6221                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
6222   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
6223                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
6224   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
6225                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
6226   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6227                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
6228   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6229                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
6230   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6231                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6232                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
6233   verifyFormat(
6234       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
6235       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6236       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
6237   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
6238                "    .aaaaaaaaaaaaaaaaaaaaaa();");
6239 
6240   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
6241                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
6242   verifyFormat(
6243       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
6244       "                                  .aaaaaaa[0]\n"
6245       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
6246   verifyFormat("a[::b::c];");
6247 
6248   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
6249 
6250   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
6251   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
6252 }
6253 
TEST_F(FormatTest,LineStartsWithSpecialCharacter)6254 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
6255   verifyFormat("(a)->b();");
6256   verifyFormat("--a;");
6257 }
6258 
TEST_F(FormatTest,HandlesIncludeDirectives)6259 TEST_F(FormatTest, HandlesIncludeDirectives) {
6260   verifyFormat("#include <string>\n"
6261                "#include <a/b/c.h>\n"
6262                "#include \"a/b/string\"\n"
6263                "#include \"string.h\"\n"
6264                "#include \"string.h\"\n"
6265                "#include <a-a>\n"
6266                "#include < path with space >\n"
6267                "#include_next <test.h>"
6268                "#include \"abc.h\" // this is included for ABC\n"
6269                "#include \"some long include\" // with a comment\n"
6270                "#include \"some very long include paaaaaaaaaaaaaaaaaaaaaaath\"",
6271                getLLVMStyleWithColumns(35));
6272   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
6273   EXPECT_EQ("#include <a>", format("#include<a>"));
6274 
6275   verifyFormat("#import <string>");
6276   verifyFormat("#import <a/b/c.h>");
6277   verifyFormat("#import \"a/b/string\"");
6278   verifyFormat("#import \"string.h\"");
6279   verifyFormat("#import \"string.h\"");
6280   verifyFormat("#if __has_include(<strstream>)\n"
6281                "#include <strstream>\n"
6282                "#endif");
6283 
6284   verifyFormat("#define MY_IMPORT <a/b>");
6285 
6286   // Protocol buffer definition or missing "#".
6287   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
6288                getLLVMStyleWithColumns(30));
6289 
6290   FormatStyle Style = getLLVMStyle();
6291   Style.AlwaysBreakBeforeMultilineStrings = true;
6292   Style.ColumnLimit = 0;
6293   verifyFormat("#import \"abc.h\"", Style);
6294 
6295   // But 'import' might also be a regular C++ namespace.
6296   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6297                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6298 }
6299 
6300 //===----------------------------------------------------------------------===//
6301 // Error recovery tests.
6302 //===----------------------------------------------------------------------===//
6303 
TEST_F(FormatTest,IncompleteParameterLists)6304 TEST_F(FormatTest, IncompleteParameterLists) {
6305   FormatStyle NoBinPacking = getLLVMStyle();
6306   NoBinPacking.BinPackParameters = false;
6307   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
6308                "                        double *min_x,\n"
6309                "                        double *max_x,\n"
6310                "                        double *min_y,\n"
6311                "                        double *max_y,\n"
6312                "                        double *min_z,\n"
6313                "                        double *max_z, ) {}",
6314                NoBinPacking);
6315 }
6316 
TEST_F(FormatTest,IncorrectCodeTrailingStuff)6317 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
6318   verifyFormat("void f() { return; }\n42");
6319   verifyFormat("void f() {\n"
6320                "  if (0)\n"
6321                "    return;\n"
6322                "}\n"
6323                "42");
6324   verifyFormat("void f() { return }\n42");
6325   verifyFormat("void f() {\n"
6326                "  if (0)\n"
6327                "    return\n"
6328                "}\n"
6329                "42");
6330 }
6331 
TEST_F(FormatTest,IncorrectCodeMissingSemicolon)6332 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
6333   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
6334   EXPECT_EQ("void f() {\n"
6335             "  if (a)\n"
6336             "    return\n"
6337             "}",
6338             format("void  f  (  )  {  if  ( a )  return  }"));
6339   EXPECT_EQ("namespace N {\n"
6340             "void f()\n"
6341             "}",
6342             format("namespace  N  {  void f()  }"));
6343   EXPECT_EQ("namespace N {\n"
6344             "void f() {}\n"
6345             "void g()\n"
6346             "}",
6347             format("namespace N  { void f( ) { } void g( ) }"));
6348 }
6349 
TEST_F(FormatTest,IndentationWithinColumnLimitNotPossible)6350 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
6351   verifyFormat("int aaaaaaaa =\n"
6352                "    // Overlylongcomment\n"
6353                "    b;",
6354                getLLVMStyleWithColumns(20));
6355   verifyFormat("function(\n"
6356                "    ShortArgument,\n"
6357                "    LoooooooooooongArgument);\n",
6358                getLLVMStyleWithColumns(20));
6359 }
6360 
TEST_F(FormatTest,IncorrectAccessSpecifier)6361 TEST_F(FormatTest, IncorrectAccessSpecifier) {
6362   verifyFormat("public:");
6363   verifyFormat("class A {\n"
6364                "public\n"
6365                "  void f() {}\n"
6366                "};");
6367   verifyFormat("public\n"
6368                "int qwerty;");
6369   verifyFormat("public\n"
6370                "B {}");
6371   verifyFormat("public\n"
6372                "{}");
6373   verifyFormat("public\n"
6374                "B { int x; }");
6375 }
6376 
TEST_F(FormatTest,IncorrectCodeUnbalancedBraces)6377 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
6378   verifyFormat("{");
6379   verifyFormat("#})");
6380   verifyNoCrash("(/**/[:!] ?[).");
6381 }
6382 
TEST_F(FormatTest,IncorrectCodeDoNoWhile)6383 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
6384   verifyFormat("do {\n}");
6385   verifyFormat("do {\n}\n"
6386                "f();");
6387   verifyFormat("do {\n}\n"
6388                "wheeee(fun);");
6389   verifyFormat("do {\n"
6390                "  f();\n"
6391                "}");
6392 }
6393 
TEST_F(FormatTest,IncorrectCodeMissingParens)6394 TEST_F(FormatTest, IncorrectCodeMissingParens) {
6395   verifyFormat("if {\n  foo;\n  foo();\n}");
6396   verifyFormat("switch {\n  foo;\n  foo();\n}");
6397   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
6398   verifyFormat("while {\n  foo;\n  foo();\n}");
6399   verifyFormat("do {\n  foo;\n  foo();\n} while;");
6400 }
6401 
TEST_F(FormatTest,DoesNotTouchUnwrappedLinesWithErrors)6402 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
6403   verifyIncompleteFormat("namespace {\n"
6404                          "class Foo { Foo (\n"
6405                          "};\n"
6406                          "} // comment");
6407 }
6408 
TEST_F(FormatTest,IncorrectCodeErrorDetection)6409 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
6410   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
6411   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
6412   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
6413   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
6414 
6415   EXPECT_EQ("{\n"
6416             "  {\n"
6417             "    breakme(\n"
6418             "        qwe);\n"
6419             "  }\n",
6420             format("{\n"
6421                    "    {\n"
6422                    " breakme(qwe);\n"
6423                    "}\n",
6424                    getLLVMStyleWithColumns(10)));
6425 }
6426 
TEST_F(FormatTest,LayoutCallsInsideBraceInitializers)6427 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
6428   verifyFormat("int x = {\n"
6429                "    avariable,\n"
6430                "    b(alongervariable)};",
6431                getLLVMStyleWithColumns(25));
6432 }
6433 
TEST_F(FormatTest,LayoutBraceInitializersInReturnStatement)6434 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
6435   verifyFormat("return (a)(b){1, 2, 3};");
6436 }
6437 
TEST_F(FormatTest,LayoutCxx11BraceInitializers)6438 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
6439   verifyFormat("vector<int> x{1, 2, 3, 4};");
6440   verifyFormat("vector<int> x{\n"
6441                "    1, 2, 3, 4,\n"
6442                "};");
6443   verifyFormat("vector<T> x{{}, {}, {}, {}};");
6444   verifyFormat("f({1, 2});");
6445   verifyFormat("auto v = Foo{-1};");
6446   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
6447   verifyFormat("Class::Class : member{1, 2, 3} {}");
6448   verifyFormat("new vector<int>{1, 2, 3};");
6449   verifyFormat("new int[3]{1, 2, 3};");
6450   verifyFormat("new int{1};");
6451   verifyFormat("return {arg1, arg2};");
6452   verifyFormat("return {arg1, SomeType{parameter}};");
6453   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
6454   verifyFormat("new T{arg1, arg2};");
6455   verifyFormat("f(MyMap[{composite, key}]);");
6456   verifyFormat("class Class {\n"
6457                "  T member = {arg1, arg2};\n"
6458                "};");
6459   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
6460   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
6461   verifyFormat("int a = std::is_integral<int>{} + 0;");
6462 
6463   verifyFormat("int foo(int i) { return fo1{}(i); }");
6464   verifyFormat("int foo(int i) { return fo1{}(i); }");
6465   verifyFormat("auto i = decltype(x){};");
6466   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
6467   verifyFormat("Node n{1, Node{1000}, //\n"
6468                "       2};");
6469   verifyFormat("Aaaa aaaaaaa{\n"
6470                "    {\n"
6471                "        aaaa,\n"
6472                "    },\n"
6473                "};");
6474   verifyFormat("class C : public D {\n"
6475                "  SomeClass SC{2};\n"
6476                "};");
6477   verifyFormat("class C : public A {\n"
6478                "  class D : public B {\n"
6479                "    void f() { int i{2}; }\n"
6480                "  };\n"
6481                "};");
6482   verifyFormat("#define A {a, a},");
6483 
6484   // In combination with BinPackArguments = false.
6485   FormatStyle NoBinPacking = getLLVMStyle();
6486   NoBinPacking.BinPackArguments = false;
6487   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
6488                "                      bbbbb,\n"
6489                "                      ccccc,\n"
6490                "                      ddddd,\n"
6491                "                      eeeee,\n"
6492                "                      ffffff,\n"
6493                "                      ggggg,\n"
6494                "                      hhhhhh,\n"
6495                "                      iiiiii,\n"
6496                "                      jjjjjj,\n"
6497                "                      kkkkkk};",
6498                NoBinPacking);
6499   verifyFormat("const Aaaaaa aaaaa = {\n"
6500                "    aaaaa,\n"
6501                "    bbbbb,\n"
6502                "    ccccc,\n"
6503                "    ddddd,\n"
6504                "    eeeee,\n"
6505                "    ffffff,\n"
6506                "    ggggg,\n"
6507                "    hhhhhh,\n"
6508                "    iiiiii,\n"
6509                "    jjjjjj,\n"
6510                "    kkkkkk,\n"
6511                "};",
6512                NoBinPacking);
6513   verifyFormat(
6514       "const Aaaaaa aaaaa = {\n"
6515       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
6516       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
6517       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
6518       "};",
6519       NoBinPacking);
6520 
6521   // FIXME: The alignment of these trailing comments might be bad. Then again,
6522   // this might be utterly useless in real code.
6523   verifyFormat("Constructor::Constructor()\n"
6524                "    : some_value{         //\n"
6525                "                 aaaaaaa, //\n"
6526                "                 bbbbbbb} {}");
6527 
6528   // In braced lists, the first comment is always assumed to belong to the
6529   // first element. Thus, it can be moved to the next or previous line as
6530   // appropriate.
6531   EXPECT_EQ("function({// First element:\n"
6532             "          1,\n"
6533             "          // Second element:\n"
6534             "          2});",
6535             format("function({\n"
6536                    "    // First element:\n"
6537                    "    1,\n"
6538                    "    // Second element:\n"
6539                    "    2});"));
6540   EXPECT_EQ("std::vector<int> MyNumbers{\n"
6541             "    // First element:\n"
6542             "    1,\n"
6543             "    // Second element:\n"
6544             "    2};",
6545             format("std::vector<int> MyNumbers{// First element:\n"
6546                    "                           1,\n"
6547                    "                           // Second element:\n"
6548                    "                           2};",
6549                    getLLVMStyleWithColumns(30)));
6550   // A trailing comma should still lead to an enforced line break.
6551   EXPECT_EQ("vector<int> SomeVector = {\n"
6552             "    // aaa\n"
6553             "    1, 2,\n"
6554             "};",
6555             format("vector<int> SomeVector = { // aaa\n"
6556                    "    1, 2, };"));
6557 
6558   FormatStyle ExtraSpaces = getLLVMStyle();
6559   ExtraSpaces.Cpp11BracedListStyle = false;
6560   ExtraSpaces.ColumnLimit = 75;
6561   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
6562   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
6563   verifyFormat("f({ 1, 2 });", ExtraSpaces);
6564   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
6565   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
6566   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
6567   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
6568   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
6569   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
6570   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
6571   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
6572   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
6573   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
6574   verifyFormat("class Class {\n"
6575                "  T member = { arg1, arg2 };\n"
6576                "};",
6577                ExtraSpaces);
6578   verifyFormat(
6579       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6580       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
6581       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
6582       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
6583       ExtraSpaces);
6584   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
6585   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
6586                ExtraSpaces);
6587   verifyFormat(
6588       "someFunction(OtherParam,\n"
6589       "             BracedList{ // comment 1 (Forcing interesting break)\n"
6590       "                         param1, param2,\n"
6591       "                         // comment 2\n"
6592       "                         param3, param4 });",
6593       ExtraSpaces);
6594   verifyFormat(
6595       "std::this_thread::sleep_for(\n"
6596       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
6597       ExtraSpaces);
6598   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaa{\n"
6599                "    aaaaaaa,\n"
6600                "    aaaaaaaaaa,\n"
6601                "    aaaaa,\n"
6602                "    aaaaaaaaaaaaaaa,\n"
6603                "    aaa,\n"
6604                "    aaaaaaaaaa,\n"
6605                "    a,\n"
6606                "    aaaaaaaaaaaaaaaaaaaaa,\n"
6607                "    aaaaaaaaaaaa,\n"
6608                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
6609                "    aaaaaaa,\n"
6610                "    a};");
6611   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
6612 }
6613 
TEST_F(FormatTest,FormatsBracedListsInColumnLayout)6614 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
6615   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6616                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6617                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6618                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6619                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6620                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
6621   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
6622                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6623                "                 1, 22, 333, 4444, 55555, //\n"
6624                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6625                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
6626   verifyFormat(
6627       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
6628       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
6629       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
6630       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
6631       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
6632       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
6633       "                 7777777};");
6634   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
6635                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
6636                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
6637   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
6638                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
6639                "    // Separating comment.\n"
6640                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
6641   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
6642                "    // Leading comment\n"
6643                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
6644                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
6645   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
6646                "                 1, 1, 1, 1};",
6647                getLLVMStyleWithColumns(39));
6648   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
6649                "                 1, 1, 1, 1};",
6650                getLLVMStyleWithColumns(38));
6651   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
6652                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
6653                getLLVMStyleWithColumns(43));
6654   verifyFormat(
6655       "static unsigned SomeValues[10][3] = {\n"
6656       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
6657       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
6658   verifyFormat("static auto fields = new vector<string>{\n"
6659                "    \"aaaaaaaaaaaaa\",\n"
6660                "    \"aaaaaaaaaaaaa\",\n"
6661                "    \"aaaaaaaaaaaa\",\n"
6662                "    \"aaaaaaaaaaaaaa\",\n"
6663                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
6664                "    \"aaaaaaaaaaaa\",\n"
6665                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
6666                "};");
6667   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
6668   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
6669                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
6670                "                 3, cccccccccccccccccccccc};",
6671                getLLVMStyleWithColumns(60));
6672 
6673   // Trailing commas.
6674   verifyFormat("vector<int> x = {\n"
6675                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
6676                "};",
6677                getLLVMStyleWithColumns(39));
6678   verifyFormat("vector<int> x = {\n"
6679                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
6680                "};",
6681                getLLVMStyleWithColumns(39));
6682   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
6683                "                 1, 1, 1, 1,\n"
6684                "                 /**/ /**/};",
6685                getLLVMStyleWithColumns(39));
6686 
6687   // Trailing comment in the first line.
6688   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
6689                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
6690                "    111111111,  222222222,  3333333333,  444444444,  //\n"
6691                "    11111111,   22222222,   333333333,   44444444};");
6692   // Trailing comment in the last line.
6693   verifyFormat("int aaaaa[] = {\n"
6694                "    1, 2, 3, // comment\n"
6695                "    4, 5, 6  // comment\n"
6696                "};");
6697 
6698   // With nested lists, we should either format one item per line or all nested
6699   // lists one on line.
6700   // FIXME: For some nested lists, we can do better.
6701   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
6702                "        {aaaaaaaaaaaaaaaaaaa},\n"
6703                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
6704                "        {aaaaaaaaaaaaaaaaa}};",
6705                getLLVMStyleWithColumns(60));
6706   verifyFormat(
6707       "SomeStruct my_struct_array = {\n"
6708       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
6709       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
6710       "    {aaa, aaa},\n"
6711       "    {aaa, aaa},\n"
6712       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
6713       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6714       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
6715 
6716   // No column layout should be used here.
6717   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
6718                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
6719 
6720   verifyNoCrash("a<,");
6721 
6722   // No braced initializer here.
6723   verifyFormat("void f() {\n"
6724                "  struct Dummy {};\n"
6725                "  f(v);\n"
6726                "}");
6727 
6728   // Long lists should be formatted in columns even if they are nested.
6729   verifyFormat(
6730       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6731       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6732       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6733       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6734       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6735       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
6736 }
6737 
TEST_F(FormatTest,PullTrivialFunctionDefinitionsIntoSingleLine)6738 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
6739   FormatStyle DoNotMerge = getLLVMStyle();
6740   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6741 
6742   verifyFormat("void f() { return 42; }");
6743   verifyFormat("void f() {\n"
6744                "  return 42;\n"
6745                "}",
6746                DoNotMerge);
6747   verifyFormat("void f() {\n"
6748                "  // Comment\n"
6749                "}");
6750   verifyFormat("{\n"
6751                "#error {\n"
6752                "  int a;\n"
6753                "}");
6754   verifyFormat("{\n"
6755                "  int a;\n"
6756                "#error {\n"
6757                "}");
6758   verifyFormat("void f() {} // comment");
6759   verifyFormat("void f() { int a; } // comment");
6760   verifyFormat("void f() {\n"
6761                "} // comment",
6762                DoNotMerge);
6763   verifyFormat("void f() {\n"
6764                "  int a;\n"
6765                "} // comment",
6766                DoNotMerge);
6767   verifyFormat("void f() {\n"
6768                "} // comment",
6769                getLLVMStyleWithColumns(15));
6770 
6771   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
6772   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
6773 
6774   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
6775   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
6776   verifyFormat("class C {\n"
6777                "  C()\n"
6778                "      : iiiiiiii(nullptr),\n"
6779                "        kkkkkkk(nullptr),\n"
6780                "        mmmmmmm(nullptr),\n"
6781                "        nnnnnnn(nullptr) {}\n"
6782                "};",
6783                getGoogleStyle());
6784 
6785   FormatStyle NoColumnLimit = getLLVMStyle();
6786   NoColumnLimit.ColumnLimit = 0;
6787   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
6788   EXPECT_EQ("class C {\n"
6789             "  A() : b(0) {}\n"
6790             "};",
6791             format("class C{A():b(0){}};", NoColumnLimit));
6792   EXPECT_EQ("A()\n"
6793             "    : b(0) {\n"
6794             "}",
6795             format("A()\n:b(0)\n{\n}", NoColumnLimit));
6796 
6797   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
6798   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
6799       FormatStyle::SFS_None;
6800   EXPECT_EQ("A()\n"
6801             "    : b(0) {\n"
6802             "}",
6803             format("A():b(0){}", DoNotMergeNoColumnLimit));
6804   EXPECT_EQ("A()\n"
6805             "    : b(0) {\n"
6806             "}",
6807             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
6808 
6809   verifyFormat("#define A          \\\n"
6810                "  void f() {       \\\n"
6811                "    int i;         \\\n"
6812                "  }",
6813                getLLVMStyleWithColumns(20));
6814   verifyFormat("#define A           \\\n"
6815                "  void f() { int i; }",
6816                getLLVMStyleWithColumns(21));
6817   verifyFormat("#define A            \\\n"
6818                "  void f() {         \\\n"
6819                "    int i;           \\\n"
6820                "  }                  \\\n"
6821                "  int j;",
6822                getLLVMStyleWithColumns(22));
6823   verifyFormat("#define A             \\\n"
6824                "  void f() { int i; } \\\n"
6825                "  int j;",
6826                getLLVMStyleWithColumns(23));
6827 }
6828 
TEST_F(FormatTest,PullInlineFunctionDefinitionsIntoSingleLine)6829 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
6830   FormatStyle MergeInlineOnly = getLLVMStyle();
6831   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
6832   verifyFormat("class C {\n"
6833                "  int f() { return 42; }\n"
6834                "};",
6835                MergeInlineOnly);
6836   verifyFormat("int f() {\n"
6837                "  return 42;\n"
6838                "}",
6839                MergeInlineOnly);
6840 }
6841 
TEST_F(FormatTest,UnderstandContextOfRecordTypeKeywords)6842 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
6843   // Elaborate type variable declarations.
6844   verifyFormat("struct foo a = {bar};\nint n;");
6845   verifyFormat("class foo a = {bar};\nint n;");
6846   verifyFormat("union foo a = {bar};\nint n;");
6847 
6848   // Elaborate types inside function definitions.
6849   verifyFormat("struct foo f() {}\nint n;");
6850   verifyFormat("class foo f() {}\nint n;");
6851   verifyFormat("union foo f() {}\nint n;");
6852 
6853   // Templates.
6854   verifyFormat("template <class X> void f() {}\nint n;");
6855   verifyFormat("template <struct X> void f() {}\nint n;");
6856   verifyFormat("template <union X> void f() {}\nint n;");
6857 
6858   // Actual definitions...
6859   verifyFormat("struct {\n} n;");
6860   verifyFormat(
6861       "template <template <class T, class Y>, class Z> class X {\n} n;");
6862   verifyFormat("union Z {\n  int n;\n} x;");
6863   verifyFormat("class MACRO Z {\n} n;");
6864   verifyFormat("class MACRO(X) Z {\n} n;");
6865   verifyFormat("class __attribute__(X) Z {\n} n;");
6866   verifyFormat("class __declspec(X) Z {\n} n;");
6867   verifyFormat("class A##B##C {\n} n;");
6868   verifyFormat("class alignas(16) Z {\n} n;");
6869   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
6870   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
6871 
6872   // Redefinition from nested context:
6873   verifyFormat("class A::B::C {\n} n;");
6874 
6875   // Template definitions.
6876   verifyFormat(
6877       "template <typename F>\n"
6878       "Matcher(const Matcher<F> &Other,\n"
6879       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
6880       "                             !is_same<F, T>::value>::type * = 0)\n"
6881       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
6882 
6883   // FIXME: This is still incorrectly handled at the formatter side.
6884   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
6885   verifyFormat("int i = SomeFunction(a<b, a> b);");
6886 
6887   // FIXME:
6888   // This now gets parsed incorrectly as class definition.
6889   // verifyFormat("class A<int> f() {\n}\nint n;");
6890 
6891   // Elaborate types where incorrectly parsing the structural element would
6892   // break the indent.
6893   verifyFormat("if (true)\n"
6894                "  class X x;\n"
6895                "else\n"
6896                "  f();\n");
6897 
6898   // This is simply incomplete. Formatting is not important, but must not crash.
6899   verifyFormat("class A:");
6900 }
6901 
TEST_F(FormatTest,DoNotInterfereWithErrorAndWarning)6902 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
6903   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
6904             format("#error Leave     all         white!!!!! space* alone!\n"));
6905   EXPECT_EQ(
6906       "#warning Leave     all         white!!!!! space* alone!\n",
6907       format("#warning Leave     all         white!!!!! space* alone!\n"));
6908   EXPECT_EQ("#error 1", format("  #  error   1"));
6909   EXPECT_EQ("#warning 1", format("  #  warning 1"));
6910 }
6911 
TEST_F(FormatTest,FormatHashIfExpressions)6912 TEST_F(FormatTest, FormatHashIfExpressions) {
6913   verifyFormat("#if AAAA && BBBB");
6914   verifyFormat("#if (AAAA && BBBB)");
6915   verifyFormat("#elif (AAAA && BBBB)");
6916   // FIXME: Come up with a better indentation for #elif.
6917   verifyFormat(
6918       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
6919       "    defined(BBBBBBBB)\n"
6920       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
6921       "    defined(BBBBBBBB)\n"
6922       "#endif",
6923       getLLVMStyleWithColumns(65));
6924 }
6925 
TEST_F(FormatTest,MergeHandlingInTheFaceOfPreprocessorDirectives)6926 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
6927   FormatStyle AllowsMergedIf = getGoogleStyle();
6928   AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
6929   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
6930   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
6931   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
6932   EXPECT_EQ("if (true) return 42;",
6933             format("if (true)\nreturn 42;", AllowsMergedIf));
6934   FormatStyle ShortMergedIf = AllowsMergedIf;
6935   ShortMergedIf.ColumnLimit = 25;
6936   verifyFormat("#define A \\\n"
6937                "  if (true) return 42;",
6938                ShortMergedIf);
6939   verifyFormat("#define A \\\n"
6940                "  f();    \\\n"
6941                "  if (true)\n"
6942                "#define B",
6943                ShortMergedIf);
6944   verifyFormat("#define A \\\n"
6945                "  f();    \\\n"
6946                "  if (true)\n"
6947                "g();",
6948                ShortMergedIf);
6949   verifyFormat("{\n"
6950                "#ifdef A\n"
6951                "  // Comment\n"
6952                "  if (true) continue;\n"
6953                "#endif\n"
6954                "  // Comment\n"
6955                "  if (true) continue;\n"
6956                "}",
6957                ShortMergedIf);
6958   ShortMergedIf.ColumnLimit = 29;
6959   verifyFormat("#define A                   \\\n"
6960                "  if (aaaaaaaaaa) return 1; \\\n"
6961                "  return 2;",
6962                ShortMergedIf);
6963   ShortMergedIf.ColumnLimit = 28;
6964   verifyFormat("#define A         \\\n"
6965                "  if (aaaaaaaaaa) \\\n"
6966                "    return 1;     \\\n"
6967                "  return 2;",
6968                ShortMergedIf);
6969 }
6970 
TEST_F(FormatTest,BlockCommentsInControlLoops)6971 TEST_F(FormatTest, BlockCommentsInControlLoops) {
6972   verifyFormat("if (0) /* a comment in a strange place */ {\n"
6973                "  f();\n"
6974                "}");
6975   verifyFormat("if (0) /* a comment in a strange place */ {\n"
6976                "  f();\n"
6977                "} /* another comment */ else /* comment #3 */ {\n"
6978                "  g();\n"
6979                "}");
6980   verifyFormat("while (0) /* a comment in a strange place */ {\n"
6981                "  f();\n"
6982                "}");
6983   verifyFormat("for (;;) /* a comment in a strange place */ {\n"
6984                "  f();\n"
6985                "}");
6986   verifyFormat("do /* a comment in a strange place */ {\n"
6987                "  f();\n"
6988                "} /* another comment */ while (0);");
6989 }
6990 
TEST_F(FormatTest,BlockComments)6991 TEST_F(FormatTest, BlockComments) {
6992   EXPECT_EQ("/* */ /* */ /* */\n/* */ /* */ /* */",
6993             format("/* *//* */  /* */\n/* *//* */  /* */"));
6994   EXPECT_EQ("/* */ a /* */ b;", format("  /* */  a/* */  b;"));
6995   EXPECT_EQ("#define A /*123*/ \\\n"
6996             "  b\n"
6997             "/* */\n"
6998             "someCall(\n"
6999             "    parameter);",
7000             format("#define A /*123*/ b\n"
7001                    "/* */\n"
7002                    "someCall(parameter);",
7003                    getLLVMStyleWithColumns(15)));
7004 
7005   EXPECT_EQ("#define A\n"
7006             "/* */ someCall(\n"
7007             "    parameter);",
7008             format("#define A\n"
7009                    "/* */someCall(parameter);",
7010                    getLLVMStyleWithColumns(15)));
7011   EXPECT_EQ("/*\n**\n*/", format("/*\n**\n*/"));
7012   EXPECT_EQ("/*\n"
7013             "*\n"
7014             " * aaaaaa\n"
7015             " * aaaaaa\n"
7016             "*/",
7017             format("/*\n"
7018                    "*\n"
7019                    " * aaaaaa aaaaaa\n"
7020                    "*/",
7021                    getLLVMStyleWithColumns(10)));
7022   EXPECT_EQ("/*\n"
7023             "**\n"
7024             "* aaaaaa\n"
7025             "*aaaaaa\n"
7026             "*/",
7027             format("/*\n"
7028                    "**\n"
7029                    "* aaaaaa aaaaaa\n"
7030                    "*/",
7031                    getLLVMStyleWithColumns(10)));
7032   EXPECT_EQ("int aaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7033             "    /* line 1\n"
7034             "       bbbbbbbbbbbb */\n"
7035             "    bbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
7036             format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7037                    "    /* line 1\n"
7038                    "       bbbbbbbbbbbb */ bbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
7039             getLLVMStyleWithColumns(50)));
7040 
7041   FormatStyle NoBinPacking = getLLVMStyle();
7042   NoBinPacking.BinPackParameters = false;
7043   EXPECT_EQ("someFunction(1, /* comment 1 */\n"
7044             "             2, /* comment 2 */\n"
7045             "             3, /* comment 3 */\n"
7046             "             aaaa,\n"
7047             "             bbbb);",
7048             format("someFunction (1,   /* comment 1 */\n"
7049                    "                2, /* comment 2 */  \n"
7050                    "               3,   /* comment 3 */\n"
7051                    "aaaa, bbbb );",
7052                    NoBinPacking));
7053   verifyFormat(
7054       "bool aaaaaaaaaaaaa = /* comment: */ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7055       "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7056   EXPECT_EQ(
7057       "bool aaaaaaaaaaaaa = /* trailing comment */\n"
7058       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7059       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;",
7060       format(
7061           "bool       aaaaaaaaaaaaa =       /* trailing comment */\n"
7062           "    aaaaaaaaaaaaaaaaaaaaaaaaaaa||aaaaaaaaaaaaaaaaaaaaaaaaa    ||\n"
7063           "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa   || aaaaaaaaaaaaaaaaaaaaaaaaaa;"));
7064   EXPECT_EQ(
7065       "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
7066       "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   /* comment */\n"
7067       "int cccccccccccccccccccccccccccccc;       /* comment */\n",
7068       format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
7069              "int      bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n"
7070              "int    cccccccccccccccccccccccccccccc;  /* comment */\n"));
7071 
7072   verifyFormat("void f(int * /* unused */) {}");
7073 
7074   EXPECT_EQ("/*\n"
7075             " **\n"
7076             " */",
7077             format("/*\n"
7078                    " **\n"
7079                    " */"));
7080   EXPECT_EQ("/*\n"
7081             " *q\n"
7082             " */",
7083             format("/*\n"
7084                    " *q\n"
7085                    " */"));
7086   EXPECT_EQ("/*\n"
7087             " * q\n"
7088             " */",
7089             format("/*\n"
7090                    " * q\n"
7091                    " */"));
7092   EXPECT_EQ("/*\n"
7093             " **/",
7094             format("/*\n"
7095                    " **/"));
7096   EXPECT_EQ("/*\n"
7097             " ***/",
7098             format("/*\n"
7099                    " ***/"));
7100 }
7101 
TEST_F(FormatTest,BlockCommentsInMacros)7102 TEST_F(FormatTest, BlockCommentsInMacros) {
7103   EXPECT_EQ("#define A          \\\n"
7104             "  {                \\\n"
7105             "    /* one line */ \\\n"
7106             "    someCall();",
7107             format("#define A {        \\\n"
7108                    "  /* one line */   \\\n"
7109                    "  someCall();",
7110                    getLLVMStyleWithColumns(20)));
7111   EXPECT_EQ("#define A          \\\n"
7112             "  {                \\\n"
7113             "    /* previous */ \\\n"
7114             "    /* one line */ \\\n"
7115             "    someCall();",
7116             format("#define A {        \\\n"
7117                    "  /* previous */   \\\n"
7118                    "  /* one line */   \\\n"
7119                    "  someCall();",
7120                    getLLVMStyleWithColumns(20)));
7121 }
7122 
TEST_F(FormatTest,BlockCommentsAtEndOfLine)7123 TEST_F(FormatTest, BlockCommentsAtEndOfLine) {
7124   EXPECT_EQ("a = {\n"
7125             "    1111 /*    */\n"
7126             "};",
7127             format("a = {1111 /*    */\n"
7128                    "};",
7129                    getLLVMStyleWithColumns(15)));
7130   EXPECT_EQ("a = {\n"
7131             "    1111 /*      */\n"
7132             "};",
7133             format("a = {1111 /*      */\n"
7134                    "};",
7135                    getLLVMStyleWithColumns(15)));
7136 
7137   // FIXME: The formatting is still wrong here.
7138   EXPECT_EQ("a = {\n"
7139             "    1111 /*      a\n"
7140             "            */\n"
7141             "};",
7142             format("a = {1111 /*      a */\n"
7143                    "};",
7144                    getLLVMStyleWithColumns(15)));
7145 }
7146 
TEST_F(FormatTest,IndentLineCommentsInStartOfBlockAtEndOfFile)7147 TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
7148   verifyFormat("{\n"
7149                "  // a\n"
7150                "  // b");
7151 }
7152 
TEST_F(FormatTest,FormatStarDependingOnContext)7153 TEST_F(FormatTest, FormatStarDependingOnContext) {
7154   verifyFormat("void f(int *a);");
7155   verifyFormat("void f() { f(fint * b); }");
7156   verifyFormat("class A {\n  void f(int *a);\n};");
7157   verifyFormat("class A {\n  int *a;\n};");
7158   verifyFormat("namespace a {\n"
7159                "namespace b {\n"
7160                "class A {\n"
7161                "  void f() {}\n"
7162                "  int *a;\n"
7163                "};\n"
7164                "}\n"
7165                "}");
7166 }
7167 
TEST_F(FormatTest,SpecialTokensAtEndOfLine)7168 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
7169   verifyFormat("while");
7170   verifyFormat("operator");
7171 }
7172 
7173 //===----------------------------------------------------------------------===//
7174 // Objective-C tests.
7175 //===----------------------------------------------------------------------===//
7176 
TEST_F(FormatTest,FormatForObjectiveCMethodDecls)7177 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
7178   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
7179   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
7180             format("-(NSUInteger)indexOfObject:(id)anObject;"));
7181   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
7182   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
7183   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
7184             format("-(NSInteger)Method3:(id)anObject;"));
7185   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
7186             format("-(NSInteger)Method4:(id)anObject;"));
7187   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
7188             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
7189   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
7190             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
7191   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
7192             "forAllCells:(BOOL)flag;",
7193             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
7194                    "forAllCells:(BOOL)flag;"));
7195 
7196   // Very long objectiveC method declaration.
7197   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
7198                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
7199   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
7200                "                    inRange:(NSRange)range\n"
7201                "                   outRange:(NSRange)out_range\n"
7202                "                  outRange1:(NSRange)out_range1\n"
7203                "                  outRange2:(NSRange)out_range2\n"
7204                "                  outRange3:(NSRange)out_range3\n"
7205                "                  outRange4:(NSRange)out_range4\n"
7206                "                  outRange5:(NSRange)out_range5\n"
7207                "                  outRange6:(NSRange)out_range6\n"
7208                "                  outRange7:(NSRange)out_range7\n"
7209                "                  outRange8:(NSRange)out_range8\n"
7210                "                  outRange9:(NSRange)out_range9;");
7211 
7212   // When the function name has to be wrapped.
7213   FormatStyle Style = getLLVMStyle();
7214   Style.IndentWrappedFunctionNames = false;
7215   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
7216                "veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
7217                "           anotherName:(NSString)bbbbbbbbbbbbbb {\n"
7218                "}",
7219                Style);
7220   Style.IndentWrappedFunctionNames = true;
7221   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
7222                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
7223                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
7224                "}",
7225                Style);
7226 
7227   verifyFormat("- (int)sum:(vector<int>)numbers;");
7228   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
7229   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
7230   // protocol lists (but not for template classes):
7231   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
7232 
7233   verifyFormat("- (int (*)())foo:(int (*)())f;");
7234   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
7235 
7236   // If there's no return type (very rare in practice!), LLVM and Google style
7237   // agree.
7238   verifyFormat("- foo;");
7239   verifyFormat("- foo:(int)f;");
7240   verifyGoogleFormat("- foo:(int)foo;");
7241 }
7242 
TEST_F(FormatTest,FormatObjCInterface)7243 TEST_F(FormatTest, FormatObjCInterface) {
7244   verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
7245                "@public\n"
7246                "  int field1;\n"
7247                "@protected\n"
7248                "  int field2;\n"
7249                "@private\n"
7250                "  int field3;\n"
7251                "@package\n"
7252                "  int field4;\n"
7253                "}\n"
7254                "+ (id)init;\n"
7255                "@end");
7256 
7257   verifyGoogleFormat("@interface Foo : NSObject<NSSomeDelegate> {\n"
7258                      " @public\n"
7259                      "  int field1;\n"
7260                      " @protected\n"
7261                      "  int field2;\n"
7262                      " @private\n"
7263                      "  int field3;\n"
7264                      " @package\n"
7265                      "  int field4;\n"
7266                      "}\n"
7267                      "+ (id)init;\n"
7268                      "@end");
7269 
7270   verifyFormat("@interface /* wait for it */ Foo\n"
7271                "+ (id)init;\n"
7272                "// Look, a comment!\n"
7273                "- (int)answerWith:(int)i;\n"
7274                "@end");
7275 
7276   verifyFormat("@interface Foo\n"
7277                "@end\n"
7278                "@interface Bar\n"
7279                "@end");
7280 
7281   verifyFormat("@interface Foo : Bar\n"
7282                "+ (id)init;\n"
7283                "@end");
7284 
7285   verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
7286                "+ (id)init;\n"
7287                "@end");
7288 
7289   verifyGoogleFormat("@interface Foo : Bar<Baz, Quux>\n"
7290                      "+ (id)init;\n"
7291                      "@end");
7292 
7293   verifyFormat("@interface Foo (HackStuff)\n"
7294                "+ (id)init;\n"
7295                "@end");
7296 
7297   verifyFormat("@interface Foo ()\n"
7298                "+ (id)init;\n"
7299                "@end");
7300 
7301   verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
7302                "+ (id)init;\n"
7303                "@end");
7304 
7305   verifyGoogleFormat("@interface Foo (HackStuff)<MyProtocol>\n"
7306                      "+ (id)init;\n"
7307                      "@end");
7308 
7309   verifyFormat("@interface Foo {\n"
7310                "  int _i;\n"
7311                "}\n"
7312                "+ (id)init;\n"
7313                "@end");
7314 
7315   verifyFormat("@interface Foo : Bar {\n"
7316                "  int _i;\n"
7317                "}\n"
7318                "+ (id)init;\n"
7319                "@end");
7320 
7321   verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
7322                "  int _i;\n"
7323                "}\n"
7324                "+ (id)init;\n"
7325                "@end");
7326 
7327   verifyFormat("@interface Foo (HackStuff) {\n"
7328                "  int _i;\n"
7329                "}\n"
7330                "+ (id)init;\n"
7331                "@end");
7332 
7333   verifyFormat("@interface Foo () {\n"
7334                "  int _i;\n"
7335                "}\n"
7336                "+ (id)init;\n"
7337                "@end");
7338 
7339   verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
7340                "  int _i;\n"
7341                "}\n"
7342                "+ (id)init;\n"
7343                "@end");
7344 
7345   FormatStyle OnePerLine = getGoogleStyle();
7346   OnePerLine.BinPackParameters = false;
7347   verifyFormat("@interface aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ()<\n"
7348                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7349                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7350                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7351                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
7352                "}",
7353                OnePerLine);
7354 }
7355 
TEST_F(FormatTest,FormatObjCImplementation)7356 TEST_F(FormatTest, FormatObjCImplementation) {
7357   verifyFormat("@implementation Foo : NSObject {\n"
7358                "@public\n"
7359                "  int field1;\n"
7360                "@protected\n"
7361                "  int field2;\n"
7362                "@private\n"
7363                "  int field3;\n"
7364                "@package\n"
7365                "  int field4;\n"
7366                "}\n"
7367                "+ (id)init {\n}\n"
7368                "@end");
7369 
7370   verifyGoogleFormat("@implementation Foo : NSObject {\n"
7371                      " @public\n"
7372                      "  int field1;\n"
7373                      " @protected\n"
7374                      "  int field2;\n"
7375                      " @private\n"
7376                      "  int field3;\n"
7377                      " @package\n"
7378                      "  int field4;\n"
7379                      "}\n"
7380                      "+ (id)init {\n}\n"
7381                      "@end");
7382 
7383   verifyFormat("@implementation Foo\n"
7384                "+ (id)init {\n"
7385                "  if (true)\n"
7386                "    return nil;\n"
7387                "}\n"
7388                "// Look, a comment!\n"
7389                "- (int)answerWith:(int)i {\n"
7390                "  return i;\n"
7391                "}\n"
7392                "+ (int)answerWith:(int)i {\n"
7393                "  return i;\n"
7394                "}\n"
7395                "@end");
7396 
7397   verifyFormat("@implementation Foo\n"
7398                "@end\n"
7399                "@implementation Bar\n"
7400                "@end");
7401 
7402   EXPECT_EQ("@implementation Foo : Bar\n"
7403             "+ (id)init {\n}\n"
7404             "- (void)foo {\n}\n"
7405             "@end",
7406             format("@implementation Foo : Bar\n"
7407                    "+(id)init{}\n"
7408                    "-(void)foo{}\n"
7409                    "@end"));
7410 
7411   verifyFormat("@implementation Foo {\n"
7412                "  int _i;\n"
7413                "}\n"
7414                "+ (id)init {\n}\n"
7415                "@end");
7416 
7417   verifyFormat("@implementation Foo : Bar {\n"
7418                "  int _i;\n"
7419                "}\n"
7420                "+ (id)init {\n}\n"
7421                "@end");
7422 
7423   verifyFormat("@implementation Foo (HackStuff)\n"
7424                "+ (id)init {\n}\n"
7425                "@end");
7426   verifyFormat("@implementation ObjcClass\n"
7427                "- (void)method;\n"
7428                "{}\n"
7429                "@end");
7430 }
7431 
TEST_F(FormatTest,FormatObjCProtocol)7432 TEST_F(FormatTest, FormatObjCProtocol) {
7433   verifyFormat("@protocol Foo\n"
7434                "@property(weak) id delegate;\n"
7435                "- (NSUInteger)numberOfThings;\n"
7436                "@end");
7437 
7438   verifyFormat("@protocol MyProtocol <NSObject>\n"
7439                "- (NSUInteger)numberOfThings;\n"
7440                "@end");
7441 
7442   verifyGoogleFormat("@protocol MyProtocol<NSObject>\n"
7443                      "- (NSUInteger)numberOfThings;\n"
7444                      "@end");
7445 
7446   verifyFormat("@protocol Foo;\n"
7447                "@protocol Bar;\n");
7448 
7449   verifyFormat("@protocol Foo\n"
7450                "@end\n"
7451                "@protocol Bar\n"
7452                "@end");
7453 
7454   verifyFormat("@protocol myProtocol\n"
7455                "- (void)mandatoryWithInt:(int)i;\n"
7456                "@optional\n"
7457                "- (void)optional;\n"
7458                "@required\n"
7459                "- (void)required;\n"
7460                "@optional\n"
7461                "@property(assign) int madProp;\n"
7462                "@end\n");
7463 
7464   verifyFormat("@property(nonatomic, assign, readonly)\n"
7465                "    int *looooooooooooooooooooooooooooongNumber;\n"
7466                "@property(nonatomic, assign, readonly)\n"
7467                "    NSString *looooooooooooooooooooooooooooongName;");
7468 
7469   verifyFormat("@implementation PR18406\n"
7470                "}\n"
7471                "@end");
7472 }
7473 
TEST_F(FormatTest,FormatObjCMethodDeclarations)7474 TEST_F(FormatTest, FormatObjCMethodDeclarations) {
7475   verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
7476                "                   rect:(NSRect)theRect\n"
7477                "               interval:(float)theInterval {\n"
7478                "}");
7479   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
7480                "      longKeyword:(NSRect)theRect\n"
7481                "    longerKeyword:(float)theInterval\n"
7482                "            error:(NSError **)theError {\n"
7483                "}");
7484   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
7485                "          longKeyword:(NSRect)theRect\n"
7486                "    evenLongerKeyword:(float)theInterval\n"
7487                "                error:(NSError **)theError {\n"
7488                "}");
7489   verifyFormat("- (instancetype)initXxxxxx:(id<x>)x\n"
7490                "                         y:(id<yyyyyyyyyyyyyyyyyyyy>)y\n"
7491                "    NS_DESIGNATED_INITIALIZER;",
7492                getLLVMStyleWithColumns(60));
7493 
7494   // Continuation indent width should win over aligning colons if the function
7495   // name is long.
7496   FormatStyle continuationStyle = getGoogleStyle();
7497   continuationStyle.ColumnLimit = 40;
7498   continuationStyle.IndentWrappedFunctionNames = true;
7499   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
7500                "    dontAlignNamef:(NSRect)theRect {\n"
7501                "}",
7502                continuationStyle);
7503 
7504   // Make sure we don't break aligning for short parameter names.
7505   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
7506                "       aShortf:(NSRect)theRect {\n"
7507                "}",
7508                continuationStyle);
7509 }
7510 
TEST_F(FormatTest,FormatObjCMethodExpr)7511 TEST_F(FormatTest, FormatObjCMethodExpr) {
7512   verifyFormat("[foo bar:baz];");
7513   verifyFormat("return [foo bar:baz];");
7514   verifyFormat("return (a)[foo bar:baz];");
7515   verifyFormat("f([foo bar:baz]);");
7516   verifyFormat("f(2, [foo bar:baz]);");
7517   verifyFormat("f(2, a ? b : c);");
7518   verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
7519 
7520   // Unary operators.
7521   verifyFormat("int a = +[foo bar:baz];");
7522   verifyFormat("int a = -[foo bar:baz];");
7523   verifyFormat("int a = ![foo bar:baz];");
7524   verifyFormat("int a = ~[foo bar:baz];");
7525   verifyFormat("int a = ++[foo bar:baz];");
7526   verifyFormat("int a = --[foo bar:baz];");
7527   verifyFormat("int a = sizeof [foo bar:baz];");
7528   verifyFormat("int a = alignof [foo bar:baz];", getGoogleStyle());
7529   verifyFormat("int a = &[foo bar:baz];");
7530   verifyFormat("int a = *[foo bar:baz];");
7531   // FIXME: Make casts work, without breaking f()[4].
7532   // verifyFormat("int a = (int)[foo bar:baz];");
7533   // verifyFormat("return (int)[foo bar:baz];");
7534   // verifyFormat("(void)[foo bar:baz];");
7535   verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
7536 
7537   // Binary operators.
7538   verifyFormat("[foo bar:baz], [foo bar:baz];");
7539   verifyFormat("[foo bar:baz] = [foo bar:baz];");
7540   verifyFormat("[foo bar:baz] *= [foo bar:baz];");
7541   verifyFormat("[foo bar:baz] /= [foo bar:baz];");
7542   verifyFormat("[foo bar:baz] %= [foo bar:baz];");
7543   verifyFormat("[foo bar:baz] += [foo bar:baz];");
7544   verifyFormat("[foo bar:baz] -= [foo bar:baz];");
7545   verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
7546   verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
7547   verifyFormat("[foo bar:baz] &= [foo bar:baz];");
7548   verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
7549   verifyFormat("[foo bar:baz] |= [foo bar:baz];");
7550   verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
7551   verifyFormat("[foo bar:baz] || [foo bar:baz];");
7552   verifyFormat("[foo bar:baz] && [foo bar:baz];");
7553   verifyFormat("[foo bar:baz] | [foo bar:baz];");
7554   verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
7555   verifyFormat("[foo bar:baz] & [foo bar:baz];");
7556   verifyFormat("[foo bar:baz] == [foo bar:baz];");
7557   verifyFormat("[foo bar:baz] != [foo bar:baz];");
7558   verifyFormat("[foo bar:baz] >= [foo bar:baz];");
7559   verifyFormat("[foo bar:baz] <= [foo bar:baz];");
7560   verifyFormat("[foo bar:baz] > [foo bar:baz];");
7561   verifyFormat("[foo bar:baz] < [foo bar:baz];");
7562   verifyFormat("[foo bar:baz] >> [foo bar:baz];");
7563   verifyFormat("[foo bar:baz] << [foo bar:baz];");
7564   verifyFormat("[foo bar:baz] - [foo bar:baz];");
7565   verifyFormat("[foo bar:baz] + [foo bar:baz];");
7566   verifyFormat("[foo bar:baz] * [foo bar:baz];");
7567   verifyFormat("[foo bar:baz] / [foo bar:baz];");
7568   verifyFormat("[foo bar:baz] % [foo bar:baz];");
7569   // Whew!
7570 
7571   verifyFormat("return in[42];");
7572   verifyFormat("for (auto v : in[1]) {\n}");
7573   verifyFormat("for (int i = 0; i < in[a]; ++i) {\n}");
7574   verifyFormat("for (int i = 0; in[a] < i; ++i) {\n}");
7575   verifyFormat("for (int i = 0; i < n; ++i, ++in[a]) {\n}");
7576   verifyFormat("for (int i = 0; i < n; ++i, in[a]++) {\n}");
7577   verifyFormat("for (int i = 0; i < f(in[a]); ++i, in[a]++) {\n}");
7578   verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
7579                "}");
7580   verifyFormat("[self aaaaa:MACRO(a, b:, c:)];");
7581   verifyFormat("[self aaaaa:(1 + 2) bbbbb:3];");
7582   verifyFormat("[self aaaaa:(Type)a bbbbb:3];");
7583 
7584   verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
7585   verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
7586   verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
7587   verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
7588   verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
7589   verifyFormat("[button setAction:@selector(zoomOut:)];");
7590   verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
7591 
7592   verifyFormat("arr[[self indexForFoo:a]];");
7593   verifyFormat("throw [self errorFor:a];");
7594   verifyFormat("@throw [self errorFor:a];");
7595 
7596   verifyFormat("[(id)foo bar:(id)baz quux:(id)snorf];");
7597   verifyFormat("[(id)foo bar:(id) ? baz : quux];");
7598   verifyFormat("4 > 4 ? (id)a : (id)baz;");
7599 
7600   // This tests that the formatter doesn't break after "backing" but before ":",
7601   // which would be at 80 columns.
7602   verifyFormat(
7603       "void f() {\n"
7604       "  if ((self = [super initWithContentRect:contentRect\n"
7605       "                               styleMask:styleMask ?: otherMask\n"
7606       "                                 backing:NSBackingStoreBuffered\n"
7607       "                                   defer:YES]))");
7608 
7609   verifyFormat(
7610       "[foo checkThatBreakingAfterColonWorksOk:\n"
7611       "         [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
7612 
7613   verifyFormat("[myObj short:arg1 // Force line break\n"
7614                "          longKeyword:arg2 != nil ? arg2 : @\"longKeyword\"\n"
7615                "    evenLongerKeyword:arg3 ?: @\"evenLongerKeyword\"\n"
7616                "                error:arg4];");
7617   verifyFormat(
7618       "void f() {\n"
7619       "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
7620       "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
7621       "                                     pos.width(), pos.height())\n"
7622       "                styleMask:NSBorderlessWindowMask\n"
7623       "                  backing:NSBackingStoreBuffered\n"
7624       "                    defer:NO]);\n"
7625       "}");
7626   verifyFormat(
7627       "void f() {\n"
7628       "  popup_wdow_.reset([[RenderWidgetPopupWindow alloc]\n"
7629       "      iniithContentRect:NSMakRet(origin_global.x, origin_global.y,\n"
7630       "                                 pos.width(), pos.height())\n"
7631       "                syeMask:NSBorderlessWindowMask\n"
7632       "                  bking:NSBackingStoreBuffered\n"
7633       "                    der:NO]);\n"
7634       "}",
7635       getLLVMStyleWithColumns(70));
7636   verifyFormat(
7637       "void f() {\n"
7638       "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
7639       "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
7640       "                                     pos.width(), pos.height())\n"
7641       "                styleMask:NSBorderlessWindowMask\n"
7642       "                  backing:NSBackingStoreBuffered\n"
7643       "                    defer:NO]);\n"
7644       "}",
7645       getChromiumStyle(FormatStyle::LK_Cpp));
7646   verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
7647                "                             with:contentsNativeView];");
7648 
7649   verifyFormat(
7650       "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
7651       "           owner:nillllll];");
7652 
7653   verifyFormat(
7654       "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
7655       "        forType:kBookmarkButtonDragType];");
7656 
7657   verifyFormat("[defaultCenter addObserver:self\n"
7658                "                  selector:@selector(willEnterFullscreen)\n"
7659                "                      name:kWillEnterFullscreenNotification\n"
7660                "                    object:nil];");
7661   verifyFormat("[image_rep drawInRect:drawRect\n"
7662                "             fromRect:NSZeroRect\n"
7663                "            operation:NSCompositeCopy\n"
7664                "             fraction:1.0\n"
7665                "       respectFlipped:NO\n"
7666                "                hints:nil];");
7667   verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7668                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
7669   verifyFormat("[aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7670                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
7671   verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaa[aaaaaaaaaaaaaaaaaaaaa]\n"
7672                "    aaaaaaaaaaaaaaaaaaaaaa];");
7673   verifyFormat("[call aaaaaaaa.aaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa\n"
7674                "        .aaaaaaaa];", // FIXME: Indentation seems off.
7675                getLLVMStyleWithColumns(60));
7676 
7677   verifyFormat(
7678       "scoped_nsobject<NSTextField> message(\n"
7679       "    // The frame will be fixed up when |-setMessageText:| is called.\n"
7680       "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
7681   verifyFormat("[self aaaaaa:bbbbbbbbbbbbb\n"
7682                "    aaaaaaaaaa:bbbbbbbbbbbbbbbbb\n"
7683                "         aaaaa:bbbbbbbbbbb + bbbbbbbbbbbb\n"
7684                "          aaaa:bbb];");
7685   verifyFormat("[self param:function( //\n"
7686                "                parameter)]");
7687   verifyFormat(
7688       "[self aaaaaaaaaa:aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
7689       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
7690       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa];");
7691 
7692   // FIXME: This violates the column limit.
7693   verifyFormat(
7694       "[aaaaaaaaaaaaaaaaaaaaaaaaa\n"
7695       "    aaaaaaaaaaaaaaaaa:aaaaaaaa\n"
7696       "                  aaa:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];",
7697       getLLVMStyleWithColumns(60));
7698 
7699   // Variadic parameters.
7700   verifyFormat(
7701       "NSArray *myStrings = [NSArray stringarray:@\"a\", @\"b\", nil];");
7702   verifyFormat(
7703       "[self aaaaaaaaaaaaa:aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
7704       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
7705       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa];");
7706   verifyFormat("[self // break\n"
7707                "      a:a\n"
7708                "    aaa:aaa];");
7709   verifyFormat("bool a = ([aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaa ||\n"
7710                "          [aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaaaaa);");
7711 }
7712 
TEST_F(FormatTest,ObjCAt)7713 TEST_F(FormatTest, ObjCAt) {
7714   verifyFormat("@autoreleasepool");
7715   verifyFormat("@catch");
7716   verifyFormat("@class");
7717   verifyFormat("@compatibility_alias");
7718   verifyFormat("@defs");
7719   verifyFormat("@dynamic");
7720   verifyFormat("@encode");
7721   verifyFormat("@end");
7722   verifyFormat("@finally");
7723   verifyFormat("@implementation");
7724   verifyFormat("@import");
7725   verifyFormat("@interface");
7726   verifyFormat("@optional");
7727   verifyFormat("@package");
7728   verifyFormat("@private");
7729   verifyFormat("@property");
7730   verifyFormat("@protected");
7731   verifyFormat("@protocol");
7732   verifyFormat("@public");
7733   verifyFormat("@required");
7734   verifyFormat("@selector");
7735   verifyFormat("@synchronized");
7736   verifyFormat("@synthesize");
7737   verifyFormat("@throw");
7738   verifyFormat("@try");
7739 
7740   EXPECT_EQ("@interface", format("@ interface"));
7741 
7742   // The precise formatting of this doesn't matter, nobody writes code like
7743   // this.
7744   verifyFormat("@ /*foo*/ interface");
7745 }
7746 
TEST_F(FormatTest,ObjCSnippets)7747 TEST_F(FormatTest, ObjCSnippets) {
7748   verifyFormat("@autoreleasepool {\n"
7749                "  foo();\n"
7750                "}");
7751   verifyFormat("@class Foo, Bar;");
7752   verifyFormat("@compatibility_alias AliasName ExistingClass;");
7753   verifyFormat("@dynamic textColor;");
7754   verifyFormat("char *buf1 = @encode(int *);");
7755   verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
7756   verifyFormat("char *buf1 = @encode(int **);");
7757   verifyFormat("Protocol *proto = @protocol(p1);");
7758   verifyFormat("SEL s = @selector(foo:);");
7759   verifyFormat("@synchronized(self) {\n"
7760                "  f();\n"
7761                "}");
7762 
7763   verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
7764   verifyGoogleFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
7765 
7766   verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
7767   verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
7768   verifyGoogleFormat("@property(assign, getter=isEditable) BOOL editable;");
7769   verifyFormat("@property (assign, getter=isEditable) BOOL editable;",
7770                getMozillaStyle());
7771   verifyFormat("@property BOOL editable;", getMozillaStyle());
7772   verifyFormat("@property (assign, getter=isEditable) BOOL editable;",
7773                getWebKitStyle());
7774   verifyFormat("@property BOOL editable;", getWebKitStyle());
7775 
7776   verifyFormat("@import foo.bar;\n"
7777                "@import baz;");
7778 }
7779 
TEST_F(FormatTest,ObjCForIn)7780 TEST_F(FormatTest, ObjCForIn) {
7781   verifyFormat("- (void)test {\n"
7782                "  for (NSString *n in arrayOfStrings) {\n"
7783                "    foo(n);\n"
7784                "  }\n"
7785                "}");
7786   verifyFormat("- (void)test {\n"
7787                "  for (NSString *n in (__bridge NSArray *)arrayOfStrings) {\n"
7788                "    foo(n);\n"
7789                "  }\n"
7790                "}");
7791 }
7792 
TEST_F(FormatTest,ObjCLiterals)7793 TEST_F(FormatTest, ObjCLiterals) {
7794   verifyFormat("@\"String\"");
7795   verifyFormat("@1");
7796   verifyFormat("@+4.8");
7797   verifyFormat("@-4");
7798   verifyFormat("@1LL");
7799   verifyFormat("@.5");
7800   verifyFormat("@'c'");
7801   verifyFormat("@true");
7802 
7803   verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
7804   verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
7805   verifyFormat("NSNumber *favoriteColor = @(Green);");
7806   verifyFormat("NSString *path = @(getenv(\"PATH\"));");
7807 
7808   verifyFormat("[dictionary setObject:@(1) forKey:@\"number\"];");
7809 }
7810 
TEST_F(FormatTest,ObjCDictLiterals)7811 TEST_F(FormatTest, ObjCDictLiterals) {
7812   verifyFormat("@{");
7813   verifyFormat("@{}");
7814   verifyFormat("@{@\"one\" : @1}");
7815   verifyFormat("return @{@\"one\" : @1;");
7816   verifyFormat("@{@\"one\" : @1}");
7817 
7818   verifyFormat("@{@\"one\" : @{@2 : @1}}");
7819   verifyFormat("@{\n"
7820                "  @\"one\" : @{@2 : @1},\n"
7821                "}");
7822 
7823   verifyFormat("@{1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2}");
7824   verifyIncompleteFormat("[self setDict:@{}");
7825   verifyIncompleteFormat("[self setDict:@{@1 : @2}");
7826   verifyFormat("NSLog(@\"%@\", @{@1 : @2, @2 : @3}[@1]);");
7827   verifyFormat(
7828       "NSDictionary *masses = @{@\"H\" : @1.0078, @\"He\" : @4.0026};");
7829   verifyFormat(
7830       "NSDictionary *settings = @{AVEncoderKey : @(AVAudioQualityMax)};");
7831 
7832   verifyFormat("NSDictionary *d = @{\n"
7833                "  @\"nam\" : NSUserNam(),\n"
7834                "  @\"dte\" : [NSDate date],\n"
7835                "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
7836                "};");
7837   verifyFormat(
7838       "@{\n"
7839       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
7840       "regularFont,\n"
7841       "};");
7842   verifyGoogleFormat(
7843       "@{\n"
7844       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
7845       "regularFont,\n"
7846       "};");
7847   verifyFormat(
7848       "@{\n"
7849       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :\n"
7850       "      reeeeeeeeeeeeeeeeeeeeeeeegularFont,\n"
7851       "};");
7852 
7853   // We should try to be robust in case someone forgets the "@".
7854   verifyFormat("NSDictionary *d = {\n"
7855                "  @\"nam\" : NSUserNam(),\n"
7856                "  @\"dte\" : [NSDate date],\n"
7857                "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
7858                "};");
7859   verifyFormat("NSMutableDictionary *dictionary =\n"
7860                "    [NSMutableDictionary dictionaryWithDictionary:@{\n"
7861                "      aaaaaaaaaaaaaaaaaaaaa : aaaaaaaaaaaaa,\n"
7862                "      bbbbbbbbbbbbbbbbbb : bbbbb,\n"
7863                "      cccccccccccccccc : ccccccccccccccc\n"
7864                "    }];");
7865 
7866   // Ensure that casts before the key are kept on the same line as the key.
7867   verifyFormat(
7868       "NSDictionary *d = @{\n"
7869       "  (aaaaaaaa id)aaaaaaaaa : (aaaaaaaa id)aaaaaaaaaaaaaaaaaaaaaaaa,\n"
7870       "  (aaaaaaaa id)aaaaaaaaaaaaaa : (aaaaaaaa id)aaaaaaaaaaaaaa,\n"
7871       "};");
7872 }
7873 
TEST_F(FormatTest,ObjCArrayLiterals)7874 TEST_F(FormatTest, ObjCArrayLiterals) {
7875   verifyIncompleteFormat("@[");
7876   verifyFormat("@[]");
7877   verifyFormat(
7878       "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
7879   verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
7880   verifyFormat("NSArray *array = @[ [foo description] ];");
7881 
7882   verifyFormat(
7883       "NSArray *some_variable = @[\n"
7884       "  aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
7885       "  @\"aaaaaaaaaaaaaaaaa\",\n"
7886       "  @\"aaaaaaaaaaaaaaaaa\",\n"
7887       "  @\"aaaaaaaaaaaaaaaaa\",\n"
7888       "];");
7889   verifyFormat(
7890       "NSArray *some_variable = @[\n"
7891       "  aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
7892       "  @\"aaaaaaaaaaaaaaaa\", @\"aaaaaaaaaaaaaaaa\", @\"aaaaaaaaaaaaaaaa\"\n"
7893       "];");
7894   verifyFormat("NSArray *some_variable = @[\n"
7895                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7896                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7897                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7898                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7899                "];");
7900   verifyFormat("NSArray *array = @[\n"
7901                "  @\"a\",\n"
7902                "  @\"a\",\n" // Trailing comma -> one per line.
7903                "];");
7904 
7905   // We should try to be robust in case someone forgets the "@".
7906   verifyFormat("NSArray *some_variable = [\n"
7907                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7908                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7909                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7910                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7911                "];");
7912   verifyFormat(
7913       "- (NSAttributedString *)attributedStringForSegment:(NSUInteger)segment\n"
7914       "                                             index:(NSUInteger)index\n"
7915       "                                nonDigitAttributes:\n"
7916       "                                    (NSDictionary *)noDigitAttributes;");
7917   verifyFormat("[someFunction someLooooooooooooongParameter:@[\n"
7918                "  NSBundle.mainBundle.infoDictionary[@\"a\"]\n"
7919                "]];");
7920 }
7921 
TEST_F(FormatTest,BreaksStringLiterals)7922 TEST_F(FormatTest, BreaksStringLiterals) {
7923   EXPECT_EQ("\"some text \"\n"
7924             "\"other\";",
7925             format("\"some text other\";", getLLVMStyleWithColumns(12)));
7926   EXPECT_EQ("\"some text \"\n"
7927             "\"other\";",
7928             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
7929   EXPECT_EQ(
7930       "#define A  \\\n"
7931       "  \"some \"  \\\n"
7932       "  \"text \"  \\\n"
7933       "  \"other\";",
7934       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
7935   EXPECT_EQ(
7936       "#define A  \\\n"
7937       "  \"so \"    \\\n"
7938       "  \"text \"  \\\n"
7939       "  \"other\";",
7940       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
7941 
7942   EXPECT_EQ("\"some text\"",
7943             format("\"some text\"", getLLVMStyleWithColumns(1)));
7944   EXPECT_EQ("\"some text\"",
7945             format("\"some text\"", getLLVMStyleWithColumns(11)));
7946   EXPECT_EQ("\"some \"\n"
7947             "\"text\"",
7948             format("\"some text\"", getLLVMStyleWithColumns(10)));
7949   EXPECT_EQ("\"some \"\n"
7950             "\"text\"",
7951             format("\"some text\"", getLLVMStyleWithColumns(7)));
7952   EXPECT_EQ("\"some\"\n"
7953             "\" tex\"\n"
7954             "\"t\"",
7955             format("\"some text\"", getLLVMStyleWithColumns(6)));
7956   EXPECT_EQ("\"some\"\n"
7957             "\" tex\"\n"
7958             "\" and\"",
7959             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
7960   EXPECT_EQ("\"some\"\n"
7961             "\"/tex\"\n"
7962             "\"/and\"",
7963             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
7964 
7965   EXPECT_EQ("variable =\n"
7966             "    \"long string \"\n"
7967             "    \"literal\";",
7968             format("variable = \"long string literal\";",
7969                    getLLVMStyleWithColumns(20)));
7970 
7971   EXPECT_EQ("variable = f(\n"
7972             "    \"long string \"\n"
7973             "    \"literal\",\n"
7974             "    short,\n"
7975             "    loooooooooooooooooooong);",
7976             format("variable = f(\"long string literal\", short, "
7977                    "loooooooooooooooooooong);",
7978                    getLLVMStyleWithColumns(20)));
7979 
7980   EXPECT_EQ(
7981       "f(g(\"long string \"\n"
7982       "    \"literal\"),\n"
7983       "  b);",
7984       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
7985   EXPECT_EQ("f(g(\"long string \"\n"
7986             "    \"literal\",\n"
7987             "    a),\n"
7988             "  b);",
7989             format("f(g(\"long string literal\", a), b);",
7990                    getLLVMStyleWithColumns(20)));
7991   EXPECT_EQ(
7992       "f(\"one two\".split(\n"
7993       "    variable));",
7994       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
7995   EXPECT_EQ("f(\"one two three four five six \"\n"
7996             "  \"seven\".split(\n"
7997             "      really_looooong_variable));",
7998             format("f(\"one two three four five six seven\"."
7999                    "split(really_looooong_variable));",
8000                    getLLVMStyleWithColumns(33)));
8001 
8002   EXPECT_EQ("f(\"some \"\n"
8003             "  \"text\",\n"
8004             "  other);",
8005             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
8006 
8007   // Only break as a last resort.
8008   verifyFormat(
8009       "aaaaaaaaaaaaaaaaaaaa(\n"
8010       "    aaaaaaaaaaaaaaaaaaaa,\n"
8011       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
8012 
8013   EXPECT_EQ("\"splitmea\"\n"
8014             "\"trandomp\"\n"
8015             "\"oint\"",
8016             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
8017 
8018   EXPECT_EQ("\"split/\"\n"
8019             "\"pathat/\"\n"
8020             "\"slashes\"",
8021             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
8022 
8023   EXPECT_EQ("\"split/\"\n"
8024             "\"pathat/\"\n"
8025             "\"slashes\"",
8026             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
8027   EXPECT_EQ("\"split at \"\n"
8028             "\"spaces/at/\"\n"
8029             "\"slashes.at.any$\"\n"
8030             "\"non-alphanumeric%\"\n"
8031             "\"1111111111characte\"\n"
8032             "\"rs\"",
8033             format("\"split at "
8034                    "spaces/at/"
8035                    "slashes.at."
8036                    "any$non-"
8037                    "alphanumeric%"
8038                    "1111111111characte"
8039                    "rs\"",
8040                    getLLVMStyleWithColumns(20)));
8041 
8042   // Verify that splitting the strings understands
8043   // Style::AlwaysBreakBeforeMultilineStrings.
8044   EXPECT_EQ(
8045       "aaaaaaaaaaaa(\n"
8046       "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
8047       "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
8048       format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
8049              "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
8050              "aaaaaaaaaaaaaaaaaaaaaa\");",
8051              getGoogleStyle()));
8052   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8053             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
8054             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
8055                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
8056                    "aaaaaaaaaaaaaaaaaaaaaa\";",
8057                    getGoogleStyle()));
8058   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8059             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
8060             format("llvm::outs() << "
8061                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
8062                    "aaaaaaaaaaaaaaaaaaa\";"));
8063   EXPECT_EQ("ffff(\n"
8064             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
8065             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
8066             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
8067                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
8068                    getGoogleStyle()));
8069 
8070   FormatStyle Style = getLLVMStyleWithColumns(12);
8071   Style.BreakStringLiterals = false;
8072   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
8073 
8074   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
8075   AlignLeft.AlignEscapedNewlinesLeft = true;
8076   EXPECT_EQ("#define A \\\n"
8077             "  \"some \" \\\n"
8078             "  \"text \" \\\n"
8079             "  \"other\";",
8080             format("#define A \"some text other\";", AlignLeft));
8081 }
8082 
TEST_F(FormatTest,FullyRemoveEmptyLines)8083 TEST_F(FormatTest, FullyRemoveEmptyLines) {
8084   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
8085   NoEmptyLines.MaxEmptyLinesToKeep = 0;
8086   EXPECT_EQ("int i = a(b());",
8087             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
8088 }
8089 
TEST_F(FormatTest,BreaksStringLiteralsWithTabs)8090 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
8091   EXPECT_EQ(
8092       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
8093       "(\n"
8094       "    \"x\t\");",
8095       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
8096              "aaaaaaa("
8097              "\"x\t\");"));
8098 }
8099 
TEST_F(FormatTest,BreaksWideAndNSStringLiterals)8100 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
8101   EXPECT_EQ(
8102       "u8\"utf8 string \"\n"
8103       "u8\"literal\";",
8104       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
8105   EXPECT_EQ(
8106       "u\"utf16 string \"\n"
8107       "u\"literal\";",
8108       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
8109   EXPECT_EQ(
8110       "U\"utf32 string \"\n"
8111       "U\"literal\";",
8112       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
8113   EXPECT_EQ("L\"wide string \"\n"
8114             "L\"literal\";",
8115             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
8116   EXPECT_EQ("@\"NSString \"\n"
8117             "@\"literal\";",
8118             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
8119 
8120   // This input makes clang-format try to split the incomplete unicode escape
8121   // sequence, which used to lead to a crasher.
8122   verifyNoCrash(
8123       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
8124       getLLVMStyleWithColumns(60));
8125 }
8126 
TEST_F(FormatTest,DoesNotBreakRawStringLiterals)8127 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
8128   FormatStyle Style = getGoogleStyleWithColumns(15);
8129   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
8130   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
8131   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
8132   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
8133   EXPECT_EQ("u8R\"x(raw literal)x\";",
8134             format("u8R\"x(raw literal)x\";", Style));
8135 }
8136 
TEST_F(FormatTest,BreaksStringLiteralsWithin_TMacro)8137 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
8138   FormatStyle Style = getLLVMStyleWithColumns(20);
8139   EXPECT_EQ(
8140       "_T(\"aaaaaaaaaaaaaa\")\n"
8141       "_T(\"aaaaaaaaaaaaaa\")\n"
8142       "_T(\"aaaaaaaaaaaa\")",
8143       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
8144   EXPECT_EQ("f(x, _T(\"aaaaaaaaa\")\n"
8145             "     _T(\"aaaaaa\"),\n"
8146             "  z);",
8147             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
8148 
8149   // FIXME: Handle embedded spaces in one iteration.
8150   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
8151   //            "_T(\"aaaaaaaaaaaaa\")\n"
8152   //            "_T(\"aaaaaaaaaaaaa\")\n"
8153   //            "_T(\"a\")",
8154   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
8155   //                   getLLVMStyleWithColumns(20)));
8156   EXPECT_EQ(
8157       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
8158       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
8159   EXPECT_EQ("f(\n"
8160             "#if !TEST\n"
8161             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
8162             "#endif\n"
8163             "    );",
8164             format("f(\n"
8165                    "#if !TEST\n"
8166                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
8167                    "#endif\n"
8168                    ");"));
8169   EXPECT_EQ("f(\n"
8170             "\n"
8171             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
8172             format("f(\n"
8173                    "\n"
8174                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
8175 }
8176 
TEST_F(FormatTest,DontSplitStringLiteralsWithEscapedNewlines)8177 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
8178   EXPECT_EQ(
8179       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
8180       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
8181       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
8182       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
8183              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
8184              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
8185 }
8186 
TEST_F(FormatTest,CountsCharactersInMultilineRawStringLiterals)8187 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
8188   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
8189             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
8190   EXPECT_EQ("fffffffffff(g(R\"x(\n"
8191             "multiline raw string literal xxxxxxxxxxxxxx\n"
8192             ")x\",\n"
8193             "              a),\n"
8194             "            b);",
8195             format("fffffffffff(g(R\"x(\n"
8196                    "multiline raw string literal xxxxxxxxxxxxxx\n"
8197                    ")x\", a), b);",
8198                    getGoogleStyleWithColumns(20)));
8199   EXPECT_EQ("fffffffffff(\n"
8200             "    g(R\"x(qqq\n"
8201             "multiline raw string literal xxxxxxxxxxxxxx\n"
8202             ")x\",\n"
8203             "      a),\n"
8204             "    b);",
8205             format("fffffffffff(g(R\"x(qqq\n"
8206                    "multiline raw string literal xxxxxxxxxxxxxx\n"
8207                    ")x\", a), b);",
8208                    getGoogleStyleWithColumns(20)));
8209 
8210   EXPECT_EQ("fffffffffff(R\"x(\n"
8211             "multiline raw string literal xxxxxxxxxxxxxx\n"
8212             ")x\");",
8213             format("fffffffffff(R\"x(\n"
8214                    "multiline raw string literal xxxxxxxxxxxxxx\n"
8215                    ")x\");",
8216                    getGoogleStyleWithColumns(20)));
8217   EXPECT_EQ("fffffffffff(R\"x(\n"
8218             "multiline raw string literal xxxxxxxxxxxxxx\n"
8219             ")x\" + bbbbbb);",
8220             format("fffffffffff(R\"x(\n"
8221                    "multiline raw string literal xxxxxxxxxxxxxx\n"
8222                    ")x\" +   bbbbbb);",
8223                    getGoogleStyleWithColumns(20)));
8224   EXPECT_EQ("fffffffffff(\n"
8225             "    R\"x(\n"
8226             "multiline raw string literal xxxxxxxxxxxxxx\n"
8227             ")x\" +\n"
8228             "    bbbbbb);",
8229             format("fffffffffff(\n"
8230                    " R\"x(\n"
8231                    "multiline raw string literal xxxxxxxxxxxxxx\n"
8232                    ")x\" + bbbbbb);",
8233                    getGoogleStyleWithColumns(20)));
8234 }
8235 
TEST_F(FormatTest,SkipsUnknownStringLiterals)8236 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
8237   verifyFormat("string a = \"unterminated;");
8238   EXPECT_EQ("function(\"unterminated,\n"
8239             "         OtherParameter);",
8240             format("function(  \"unterminated,\n"
8241                    "    OtherParameter);"));
8242 }
8243 
TEST_F(FormatTest,DoesNotTryToParseUDLiteralsInPreCpp11Code)8244 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
8245   FormatStyle Style = getLLVMStyle();
8246   Style.Standard = FormatStyle::LS_Cpp03;
8247   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
8248             format("#define x(_a) printf(\"foo\"_a);", Style));
8249 }
8250 
TEST_F(FormatTest,UnderstandsCpp1y)8251 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
8252 
TEST_F(FormatTest,BreakStringLiteralsBeforeUnbreakableTokenSequence)8253 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
8254   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
8255             "             \"ddeeefff\");",
8256             format("someFunction(\"aaabbbcccdddeeefff\");",
8257                    getLLVMStyleWithColumns(25)));
8258   EXPECT_EQ("someFunction1234567890(\n"
8259             "    \"aaabbbcccdddeeefff\");",
8260             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
8261                    getLLVMStyleWithColumns(26)));
8262   EXPECT_EQ("someFunction1234567890(\n"
8263             "    \"aaabbbcccdddeeeff\"\n"
8264             "    \"f\");",
8265             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
8266                    getLLVMStyleWithColumns(25)));
8267   EXPECT_EQ("someFunction1234567890(\n"
8268             "    \"aaabbbcccdddeeeff\"\n"
8269             "    \"f\");",
8270             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
8271                    getLLVMStyleWithColumns(24)));
8272   EXPECT_EQ("someFunction(\"aaabbbcc \"\n"
8273             "             \"ddde \"\n"
8274             "             \"efff\");",
8275             format("someFunction(\"aaabbbcc ddde efff\");",
8276                    getLLVMStyleWithColumns(25)));
8277   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
8278             "             \"ddeeefff\");",
8279             format("someFunction(\"aaabbbccc ddeeefff\");",
8280                    getLLVMStyleWithColumns(25)));
8281   EXPECT_EQ("someFunction1234567890(\n"
8282             "    \"aaabb \"\n"
8283             "    \"cccdddeeefff\");",
8284             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
8285                    getLLVMStyleWithColumns(25)));
8286   EXPECT_EQ("#define A          \\\n"
8287             "  string s =       \\\n"
8288             "      \"123456789\"  \\\n"
8289             "      \"0\";         \\\n"
8290             "  int i;",
8291             format("#define A string s = \"1234567890\"; int i;",
8292                    getLLVMStyleWithColumns(20)));
8293   // FIXME: Put additional penalties on breaking at non-whitespace locations.
8294   EXPECT_EQ("someFunction(\"aaabbbcc \"\n"
8295             "             \"dddeeeff\"\n"
8296             "             \"f\");",
8297             format("someFunction(\"aaabbbcc dddeeefff\");",
8298                    getLLVMStyleWithColumns(25)));
8299 }
8300 
TEST_F(FormatTest,DoNotBreakStringLiteralsInEscapeSequence)8301 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
8302   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
8303   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
8304   EXPECT_EQ("\"test\"\n"
8305             "\"\\n\"",
8306             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
8307   EXPECT_EQ("\"tes\\\\\"\n"
8308             "\"n\"",
8309             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
8310   EXPECT_EQ("\"\\\\\\\\\"\n"
8311             "\"\\n\"",
8312             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
8313   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
8314   EXPECT_EQ("\"\\uff01\"\n"
8315             "\"test\"",
8316             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
8317   EXPECT_EQ("\"\\Uff01ff02\"",
8318             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
8319   EXPECT_EQ("\"\\x000000000001\"\n"
8320             "\"next\"",
8321             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
8322   EXPECT_EQ("\"\\x000000000001next\"",
8323             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
8324   EXPECT_EQ("\"\\x000000000001\"",
8325             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
8326   EXPECT_EQ("\"test\"\n"
8327             "\"\\000000\"\n"
8328             "\"000001\"",
8329             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
8330   EXPECT_EQ("\"test\\000\"\n"
8331             "\"00000000\"\n"
8332             "\"1\"",
8333             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
8334 }
8335 
TEST_F(FormatTest,DoNotCreateUnreasonableUnwrappedLines)8336 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
8337   verifyFormat("void f() {\n"
8338                "  return g() {}\n"
8339                "  void h() {}");
8340   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
8341                "g();\n"
8342                "}");
8343 }
8344 
TEST_F(FormatTest,DoNotPrematurelyEndUnwrappedLineForReturnStatements)8345 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
8346   verifyFormat(
8347       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
8348 }
8349 
TEST_F(FormatTest,FormatsClosingBracesInEmptyNestedBlocks)8350 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
8351   verifyFormat("class X {\n"
8352                "  void f() {\n"
8353                "  }\n"
8354                "};",
8355                getLLVMStyleWithColumns(12));
8356 }
8357 
TEST_F(FormatTest,ConfigurableIndentWidth)8358 TEST_F(FormatTest, ConfigurableIndentWidth) {
8359   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
8360   EightIndent.IndentWidth = 8;
8361   EightIndent.ContinuationIndentWidth = 8;
8362   verifyFormat("void f() {\n"
8363                "        someFunction();\n"
8364                "        if (true) {\n"
8365                "                f();\n"
8366                "        }\n"
8367                "}",
8368                EightIndent);
8369   verifyFormat("class X {\n"
8370                "        void f() {\n"
8371                "        }\n"
8372                "};",
8373                EightIndent);
8374   verifyFormat("int x[] = {\n"
8375                "        call(),\n"
8376                "        call()};",
8377                EightIndent);
8378 }
8379 
TEST_F(FormatTest,ConfigurableFunctionDeclarationIndentAfterType)8380 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
8381   verifyFormat("double\n"
8382                "f();",
8383                getLLVMStyleWithColumns(8));
8384 }
8385 
TEST_F(FormatTest,ConfigurableUseOfTab)8386 TEST_F(FormatTest, ConfigurableUseOfTab) {
8387   FormatStyle Tab = getLLVMStyleWithColumns(42);
8388   Tab.IndentWidth = 8;
8389   Tab.UseTab = FormatStyle::UT_Always;
8390   Tab.AlignEscapedNewlinesLeft = true;
8391 
8392   EXPECT_EQ("if (aaaaaaaa && // q\n"
8393             "    bb)\t\t// w\n"
8394             "\t;",
8395             format("if (aaaaaaaa &&// q\n"
8396                    "bb)// w\n"
8397                    ";",
8398                    Tab));
8399   EXPECT_EQ("if (aaa && bbb) // w\n"
8400             "\t;",
8401             format("if(aaa&&bbb)// w\n"
8402                    ";",
8403                    Tab));
8404 
8405   verifyFormat("class X {\n"
8406                "\tvoid f() {\n"
8407                "\t\tsomeFunction(parameter1,\n"
8408                "\t\t\t     parameter2);\n"
8409                "\t}\n"
8410                "};",
8411                Tab);
8412   verifyFormat("#define A                        \\\n"
8413                "\tvoid f() {               \\\n"
8414                "\t\tsomeFunction(    \\\n"
8415                "\t\t    parameter1,  \\\n"
8416                "\t\t    parameter2); \\\n"
8417                "\t}",
8418                Tab);
8419 
8420   Tab.TabWidth = 4;
8421   Tab.IndentWidth = 8;
8422   verifyFormat("class TabWidth4Indent8 {\n"
8423                "\t\tvoid f() {\n"
8424                "\t\t\t\tsomeFunction(parameter1,\n"
8425                "\t\t\t\t\t\t\t parameter2);\n"
8426                "\t\t}\n"
8427                "};",
8428                Tab);
8429 
8430   Tab.TabWidth = 4;
8431   Tab.IndentWidth = 4;
8432   verifyFormat("class TabWidth4Indent4 {\n"
8433                "\tvoid f() {\n"
8434                "\t\tsomeFunction(parameter1,\n"
8435                "\t\t\t\t\t parameter2);\n"
8436                "\t}\n"
8437                "};",
8438                Tab);
8439 
8440   Tab.TabWidth = 8;
8441   Tab.IndentWidth = 4;
8442   verifyFormat("class TabWidth8Indent4 {\n"
8443                "    void f() {\n"
8444                "\tsomeFunction(parameter1,\n"
8445                "\t\t     parameter2);\n"
8446                "    }\n"
8447                "};",
8448                Tab);
8449 
8450   Tab.TabWidth = 8;
8451   Tab.IndentWidth = 8;
8452   EXPECT_EQ("/*\n"
8453             "\t      a\t\tcomment\n"
8454             "\t      in multiple lines\n"
8455             "       */",
8456             format("   /*\t \t \n"
8457                    " \t \t a\t\tcomment\t \t\n"
8458                    " \t \t in multiple lines\t\n"
8459                    " \t  */",
8460                    Tab));
8461 
8462   Tab.UseTab = FormatStyle::UT_ForIndentation;
8463   verifyFormat("{\n"
8464                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8465                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8466                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8467                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8468                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8469                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8470                "};",
8471                Tab);
8472   verifyFormat("enum AA {\n"
8473                "\ta1, // Force multiple lines\n"
8474                "\ta2,\n"
8475                "\ta3\n"
8476                "};",
8477                Tab);
8478   EXPECT_EQ("if (aaaaaaaa && // q\n"
8479             "    bb)         // w\n"
8480             "\t;",
8481             format("if (aaaaaaaa &&// q\n"
8482                    "bb)// w\n"
8483                    ";",
8484                    Tab));
8485   verifyFormat("class X {\n"
8486                "\tvoid f() {\n"
8487                "\t\tsomeFunction(parameter1,\n"
8488                "\t\t             parameter2);\n"
8489                "\t}\n"
8490                "};",
8491                Tab);
8492   verifyFormat("{\n"
8493                "\tQ(\n"
8494                "\t    {\n"
8495                "\t\t    int a;\n"
8496                "\t\t    someFunction(aaaaaaaa,\n"
8497                "\t\t                 bbbbbbb);\n"
8498                "\t    },\n"
8499                "\t    p);\n"
8500                "}",
8501                Tab);
8502   EXPECT_EQ("{\n"
8503             "\t/* aaaa\n"
8504             "\t   bbbb */\n"
8505             "}",
8506             format("{\n"
8507                    "/* aaaa\n"
8508                    "   bbbb */\n"
8509                    "}",
8510                    Tab));
8511   EXPECT_EQ("{\n"
8512             "\t/*\n"
8513             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8514             "\t  bbbbbbbbbbbbb\n"
8515             "\t*/\n"
8516             "}",
8517             format("{\n"
8518                    "/*\n"
8519                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
8520                    "*/\n"
8521                    "}",
8522                    Tab));
8523   EXPECT_EQ("{\n"
8524             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8525             "\t// bbbbbbbbbbbbb\n"
8526             "}",
8527             format("{\n"
8528                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
8529                    "}",
8530                    Tab));
8531   EXPECT_EQ("{\n"
8532             "\t/*\n"
8533             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8534             "\t  bbbbbbbbbbbbb\n"
8535             "\t*/\n"
8536             "}",
8537             format("{\n"
8538                    "\t/*\n"
8539                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
8540                    "\t*/\n"
8541                    "}",
8542                    Tab));
8543   EXPECT_EQ("{\n"
8544             "\t/*\n"
8545             "\n"
8546             "\t*/\n"
8547             "}",
8548             format("{\n"
8549                    "\t/*\n"
8550                    "\n"
8551                    "\t*/\n"
8552                    "}",
8553                    Tab));
8554   EXPECT_EQ("{\n"
8555             "\t/*\n"
8556             " asdf\n"
8557             "\t*/\n"
8558             "}",
8559             format("{\n"
8560                    "\t/*\n"
8561                    " asdf\n"
8562                    "\t*/\n"
8563                    "}",
8564                    Tab));
8565 
8566   Tab.UseTab = FormatStyle::UT_Never;
8567   EXPECT_EQ("/*\n"
8568             "              a\t\tcomment\n"
8569             "              in multiple lines\n"
8570             "       */",
8571             format("   /*\t \t \n"
8572                    " \t \t a\t\tcomment\t \t\n"
8573                    " \t \t in multiple lines\t\n"
8574                    " \t  */",
8575                    Tab));
8576   EXPECT_EQ("/* some\n"
8577             "   comment */",
8578             format(" \t \t /* some\n"
8579                    " \t \t    comment */",
8580                    Tab));
8581   EXPECT_EQ("int a; /* some\n"
8582             "   comment */",
8583             format(" \t \t int a; /* some\n"
8584                    " \t \t    comment */",
8585                    Tab));
8586 
8587   EXPECT_EQ("int a; /* some\n"
8588             "comment */",
8589             format(" \t \t int\ta; /* some\n"
8590                    " \t \t    comment */",
8591                    Tab));
8592   EXPECT_EQ("f(\"\t\t\"); /* some\n"
8593             "    comment */",
8594             format(" \t \t f(\"\t\t\"); /* some\n"
8595                    " \t \t    comment */",
8596                    Tab));
8597   EXPECT_EQ("{\n"
8598             "  /*\n"
8599             "   * Comment\n"
8600             "   */\n"
8601             "  int i;\n"
8602             "}",
8603             format("{\n"
8604                    "\t/*\n"
8605                    "\t * Comment\n"
8606                    "\t */\n"
8607                    "\t int i;\n"
8608                    "}"));
8609 
8610   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
8611   Tab.TabWidth = 8;
8612   Tab.IndentWidth = 8;
8613   EXPECT_EQ("if (aaaaaaaa && // q\n"
8614             "    bb)         // w\n"
8615             "\t;",
8616             format("if (aaaaaaaa &&// q\n"
8617                    "bb)// w\n"
8618                    ";",
8619                    Tab));
8620   EXPECT_EQ("if (aaa && bbb) // w\n"
8621             "\t;",
8622             format("if(aaa&&bbb)// w\n"
8623                    ";",
8624                    Tab));
8625   verifyFormat("class X {\n"
8626                "\tvoid f() {\n"
8627                "\t\tsomeFunction(parameter1,\n"
8628                "\t\t\t     parameter2);\n"
8629                "\t}\n"
8630                "};",
8631                Tab);
8632   verifyFormat("#define A                        \\\n"
8633                "\tvoid f() {               \\\n"
8634                "\t\tsomeFunction(    \\\n"
8635                "\t\t    parameter1,  \\\n"
8636                "\t\t    parameter2); \\\n"
8637                "\t}",
8638                Tab);
8639   Tab.TabWidth = 4;
8640   Tab.IndentWidth = 8;
8641   verifyFormat("class TabWidth4Indent8 {\n"
8642                "\t\tvoid f() {\n"
8643                "\t\t\t\tsomeFunction(parameter1,\n"
8644                "\t\t\t\t\t\t\t parameter2);\n"
8645                "\t\t}\n"
8646                "};",
8647                Tab);
8648   Tab.TabWidth = 4;
8649   Tab.IndentWidth = 4;
8650   verifyFormat("class TabWidth4Indent4 {\n"
8651                "\tvoid f() {\n"
8652                "\t\tsomeFunction(parameter1,\n"
8653                "\t\t\t\t\t parameter2);\n"
8654                "\t}\n"
8655                "};",
8656                Tab);
8657   Tab.TabWidth = 8;
8658   Tab.IndentWidth = 4;
8659   verifyFormat("class TabWidth8Indent4 {\n"
8660                "    void f() {\n"
8661                "\tsomeFunction(parameter1,\n"
8662                "\t\t     parameter2);\n"
8663                "    }\n"
8664                "};",
8665                Tab);
8666   Tab.TabWidth = 8;
8667   Tab.IndentWidth = 8;
8668   EXPECT_EQ("/*\n"
8669             "\t      a\t\tcomment\n"
8670             "\t      in multiple lines\n"
8671             "       */",
8672             format("   /*\t \t \n"
8673                    " \t \t a\t\tcomment\t \t\n"
8674                    " \t \t in multiple lines\t\n"
8675                    " \t  */",
8676                    Tab));
8677   verifyFormat("{\n"
8678                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8679                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8680                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8681                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8682                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8683                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8684                "};",
8685                Tab);
8686   verifyFormat("enum AA {\n"
8687                "\ta1, // Force multiple lines\n"
8688                "\ta2,\n"
8689                "\ta3\n"
8690                "};",
8691                Tab);
8692   EXPECT_EQ("if (aaaaaaaa && // q\n"
8693             "    bb)         // w\n"
8694             "\t;",
8695             format("if (aaaaaaaa &&// q\n"
8696                    "bb)// w\n"
8697                    ";",
8698                    Tab));
8699   verifyFormat("class X {\n"
8700                "\tvoid f() {\n"
8701                "\t\tsomeFunction(parameter1,\n"
8702                "\t\t\t     parameter2);\n"
8703                "\t}\n"
8704                "};",
8705                Tab);
8706   verifyFormat("{\n"
8707                "\tQ(\n"
8708                "\t    {\n"
8709                "\t\t    int a;\n"
8710                "\t\t    someFunction(aaaaaaaa,\n"
8711                "\t\t\t\t bbbbbbb);\n"
8712                "\t    },\n"
8713                "\t    p);\n"
8714                "}",
8715                Tab);
8716   EXPECT_EQ("{\n"
8717             "\t/* aaaa\n"
8718             "\t   bbbb */\n"
8719             "}",
8720             format("{\n"
8721                    "/* aaaa\n"
8722                    "   bbbb */\n"
8723                    "}",
8724                    Tab));
8725   EXPECT_EQ("{\n"
8726             "\t/*\n"
8727             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8728             "\t  bbbbbbbbbbbbb\n"
8729             "\t*/\n"
8730             "}",
8731             format("{\n"
8732                    "/*\n"
8733                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
8734                    "*/\n"
8735                    "}",
8736                    Tab));
8737   EXPECT_EQ("{\n"
8738             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8739             "\t// bbbbbbbbbbbbb\n"
8740             "}",
8741             format("{\n"
8742                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
8743                    "}",
8744                    Tab));
8745   EXPECT_EQ("{\n"
8746             "\t/*\n"
8747             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8748             "\t  bbbbbbbbbbbbb\n"
8749             "\t*/\n"
8750             "}",
8751             format("{\n"
8752                    "\t/*\n"
8753                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
8754                    "\t*/\n"
8755                    "}",
8756                    Tab));
8757   EXPECT_EQ("{\n"
8758             "\t/*\n"
8759             "\n"
8760             "\t*/\n"
8761             "}",
8762             format("{\n"
8763                    "\t/*\n"
8764                    "\n"
8765                    "\t*/\n"
8766                    "}",
8767                    Tab));
8768   EXPECT_EQ("{\n"
8769             "\t/*\n"
8770             " asdf\n"
8771             "\t*/\n"
8772             "}",
8773             format("{\n"
8774                    "\t/*\n"
8775                    " asdf\n"
8776                    "\t*/\n"
8777                    "}",
8778                    Tab));
8779   EXPECT_EQ("/*\n"
8780             "\t      a\t\tcomment\n"
8781             "\t      in multiple lines\n"
8782             "       */",
8783             format("   /*\t \t \n"
8784                    " \t \t a\t\tcomment\t \t\n"
8785                    " \t \t in multiple lines\t\n"
8786                    " \t  */",
8787                    Tab));
8788   EXPECT_EQ("/* some\n"
8789             "   comment */",
8790             format(" \t \t /* some\n"
8791                    " \t \t    comment */",
8792                    Tab));
8793   EXPECT_EQ("int a; /* some\n"
8794             "   comment */",
8795             format(" \t \t int a; /* some\n"
8796                    " \t \t    comment */",
8797                    Tab));
8798   EXPECT_EQ("int a; /* some\n"
8799             "comment */",
8800             format(" \t \t int\ta; /* some\n"
8801                    " \t \t    comment */",
8802                    Tab));
8803   EXPECT_EQ("f(\"\t\t\"); /* some\n"
8804             "    comment */",
8805             format(" \t \t f(\"\t\t\"); /* some\n"
8806                    " \t \t    comment */",
8807                    Tab));
8808   EXPECT_EQ("{\n"
8809             "  /*\n"
8810             "   * Comment\n"
8811             "   */\n"
8812             "  int i;\n"
8813             "}",
8814             format("{\n"
8815                    "\t/*\n"
8816                    "\t * Comment\n"
8817                    "\t */\n"
8818                    "\t int i;\n"
8819                    "}"));
8820   Tab.AlignConsecutiveAssignments = true;
8821   Tab.AlignConsecutiveDeclarations = true;
8822   Tab.TabWidth = 4;
8823   Tab.IndentWidth = 4;
8824   verifyFormat("class Assign {\n"
8825                "\tvoid f() {\n"
8826                "\t\tint         x      = 123;\n"
8827                "\t\tint         random = 4;\n"
8828                "\t\tstd::string alphabet =\n"
8829                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
8830                "\t}\n"
8831                "};",
8832                Tab);
8833 }
8834 
TEST_F(FormatTest,CalculatesOriginalColumn)8835 TEST_F(FormatTest, CalculatesOriginalColumn) {
8836   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8837             "q\"; /* some\n"
8838             "       comment */",
8839             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8840                    "q\"; /* some\n"
8841                    "       comment */",
8842                    getLLVMStyle()));
8843   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
8844             "/* some\n"
8845             "   comment */",
8846             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
8847                    " /* some\n"
8848                    "    comment */",
8849                    getLLVMStyle()));
8850   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8851             "qqq\n"
8852             "/* some\n"
8853             "   comment */",
8854             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8855                    "qqq\n"
8856                    " /* some\n"
8857                    "    comment */",
8858                    getLLVMStyle()));
8859   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8860             "wwww; /* some\n"
8861             "         comment */",
8862             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8863                    "wwww; /* some\n"
8864                    "         comment */",
8865                    getLLVMStyle()));
8866 }
8867 
TEST_F(FormatTest,ConfigurableSpaceBeforeParens)8868 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
8869   FormatStyle NoSpace = getLLVMStyle();
8870   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
8871 
8872   verifyFormat("while(true)\n"
8873                "  continue;",
8874                NoSpace);
8875   verifyFormat("for(;;)\n"
8876                "  continue;",
8877                NoSpace);
8878   verifyFormat("if(true)\n"
8879                "  f();\n"
8880                "else if(true)\n"
8881                "  f();",
8882                NoSpace);
8883   verifyFormat("do {\n"
8884                "  do_something();\n"
8885                "} while(something());",
8886                NoSpace);
8887   verifyFormat("switch(x) {\n"
8888                "default:\n"
8889                "  break;\n"
8890                "}",
8891                NoSpace);
8892   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
8893   verifyFormat("size_t x = sizeof(x);", NoSpace);
8894   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
8895   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
8896   verifyFormat("alignas(128) char a[128];", NoSpace);
8897   verifyFormat("size_t x = alignof(MyType);", NoSpace);
8898   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
8899   verifyFormat("int f() throw(Deprecated);", NoSpace);
8900   verifyFormat("typedef void (*cb)(int);", NoSpace);
8901   verifyFormat("T A::operator()();", NoSpace);
8902   verifyFormat("X A::operator++(T);", NoSpace);
8903 
8904   FormatStyle Space = getLLVMStyle();
8905   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
8906 
8907   verifyFormat("int f ();", Space);
8908   verifyFormat("void f (int a, T b) {\n"
8909                "  while (true)\n"
8910                "    continue;\n"
8911                "}",
8912                Space);
8913   verifyFormat("if (true)\n"
8914                "  f ();\n"
8915                "else if (true)\n"
8916                "  f ();",
8917                Space);
8918   verifyFormat("do {\n"
8919                "  do_something ();\n"
8920                "} while (something ());",
8921                Space);
8922   verifyFormat("switch (x) {\n"
8923                "default:\n"
8924                "  break;\n"
8925                "}",
8926                Space);
8927   verifyFormat("A::A () : a (1) {}", Space);
8928   verifyFormat("void f () __attribute__ ((asdf));", Space);
8929   verifyFormat("*(&a + 1);\n"
8930                "&((&a)[1]);\n"
8931                "a[(b + c) * d];\n"
8932                "(((a + 1) * 2) + 3) * 4;",
8933                Space);
8934   verifyFormat("#define A(x) x", Space);
8935   verifyFormat("#define A (x) x", Space);
8936   verifyFormat("#if defined(x)\n"
8937                "#endif",
8938                Space);
8939   verifyFormat("auto i = std::make_unique<int> (5);", Space);
8940   verifyFormat("size_t x = sizeof (x);", Space);
8941   verifyFormat("auto f (int x) -> decltype (x);", Space);
8942   verifyFormat("int f (T x) noexcept (x.create ());", Space);
8943   verifyFormat("alignas (128) char a[128];", Space);
8944   verifyFormat("size_t x = alignof (MyType);", Space);
8945   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
8946   verifyFormat("int f () throw (Deprecated);", Space);
8947   verifyFormat("typedef void (*cb) (int);", Space);
8948   verifyFormat("T A::operator() ();", Space);
8949   verifyFormat("X A::operator++ (T);", Space);
8950 }
8951 
TEST_F(FormatTest,ConfigurableSpacesInParentheses)8952 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
8953   FormatStyle Spaces = getLLVMStyle();
8954 
8955   Spaces.SpacesInParentheses = true;
8956   verifyFormat("call( x, y, z );", Spaces);
8957   verifyFormat("call();", Spaces);
8958   verifyFormat("std::function<void( int, int )> callback;", Spaces);
8959   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
8960                Spaces);
8961   verifyFormat("while ( (bool)1 )\n"
8962                "  continue;",
8963                Spaces);
8964   verifyFormat("for ( ;; )\n"
8965                "  continue;",
8966                Spaces);
8967   verifyFormat("if ( true )\n"
8968                "  f();\n"
8969                "else if ( true )\n"
8970                "  f();",
8971                Spaces);
8972   verifyFormat("do {\n"
8973                "  do_something( (int)i );\n"
8974                "} while ( something() );",
8975                Spaces);
8976   verifyFormat("switch ( x ) {\n"
8977                "default:\n"
8978                "  break;\n"
8979                "}",
8980                Spaces);
8981 
8982   Spaces.SpacesInParentheses = false;
8983   Spaces.SpacesInCStyleCastParentheses = true;
8984   verifyFormat("Type *A = ( Type * )P;", Spaces);
8985   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
8986   verifyFormat("x = ( int32 )y;", Spaces);
8987   verifyFormat("int a = ( int )(2.0f);", Spaces);
8988   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
8989   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
8990   verifyFormat("#define x (( int )-1)", Spaces);
8991 
8992   // Run the first set of tests again with:
8993   Spaces.SpacesInParentheses = false;
8994   Spaces.SpaceInEmptyParentheses = true;
8995   Spaces.SpacesInCStyleCastParentheses = true;
8996   verifyFormat("call(x, y, z);", Spaces);
8997   verifyFormat("call( );", Spaces);
8998   verifyFormat("std::function<void(int, int)> callback;", Spaces);
8999   verifyFormat("while (( bool )1)\n"
9000                "  continue;",
9001                Spaces);
9002   verifyFormat("for (;;)\n"
9003                "  continue;",
9004                Spaces);
9005   verifyFormat("if (true)\n"
9006                "  f( );\n"
9007                "else if (true)\n"
9008                "  f( );",
9009                Spaces);
9010   verifyFormat("do {\n"
9011                "  do_something(( int )i);\n"
9012                "} while (something( ));",
9013                Spaces);
9014   verifyFormat("switch (x) {\n"
9015                "default:\n"
9016                "  break;\n"
9017                "}",
9018                Spaces);
9019 
9020   // Run the first set of tests again with:
9021   Spaces.SpaceAfterCStyleCast = true;
9022   verifyFormat("call(x, y, z);", Spaces);
9023   verifyFormat("call( );", Spaces);
9024   verifyFormat("std::function<void(int, int)> callback;", Spaces);
9025   verifyFormat("while (( bool ) 1)\n"
9026                "  continue;",
9027                Spaces);
9028   verifyFormat("for (;;)\n"
9029                "  continue;",
9030                Spaces);
9031   verifyFormat("if (true)\n"
9032                "  f( );\n"
9033                "else if (true)\n"
9034                "  f( );",
9035                Spaces);
9036   verifyFormat("do {\n"
9037                "  do_something(( int ) i);\n"
9038                "} while (something( ));",
9039                Spaces);
9040   verifyFormat("switch (x) {\n"
9041                "default:\n"
9042                "  break;\n"
9043                "}",
9044                Spaces);
9045 
9046   // Run subset of tests again with:
9047   Spaces.SpacesInCStyleCastParentheses = false;
9048   Spaces.SpaceAfterCStyleCast = true;
9049   verifyFormat("while ((bool) 1)\n"
9050                "  continue;",
9051                Spaces);
9052   verifyFormat("do {\n"
9053                "  do_something((int) i);\n"
9054                "} while (something( ));",
9055                Spaces);
9056 }
9057 
TEST_F(FormatTest,ConfigurableSpacesInSquareBrackets)9058 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
9059   verifyFormat("int a[5];");
9060   verifyFormat("a[3] += 42;");
9061 
9062   FormatStyle Spaces = getLLVMStyle();
9063   Spaces.SpacesInSquareBrackets = true;
9064   // Lambdas unchanged.
9065   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
9066   verifyFormat("return [i, args...] {};", Spaces);
9067 
9068   // Not lambdas.
9069   verifyFormat("int a[ 5 ];", Spaces);
9070   verifyFormat("a[ 3 ] += 42;", Spaces);
9071   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
9072   verifyFormat("double &operator[](int i) { return 0; }\n"
9073                "int i;",
9074                Spaces);
9075   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
9076   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
9077   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
9078 }
9079 
TEST_F(FormatTest,ConfigurableSpaceBeforeAssignmentOperators)9080 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
9081   verifyFormat("int a = 5;");
9082   verifyFormat("a += 42;");
9083   verifyFormat("a or_eq 8;");
9084 
9085   FormatStyle Spaces = getLLVMStyle();
9086   Spaces.SpaceBeforeAssignmentOperators = false;
9087   verifyFormat("int a= 5;", Spaces);
9088   verifyFormat("a+= 42;", Spaces);
9089   verifyFormat("a or_eq 8;", Spaces);
9090 }
9091 
TEST_F(FormatTest,AlignConsecutiveAssignments)9092 TEST_F(FormatTest, AlignConsecutiveAssignments) {
9093   FormatStyle Alignment = getLLVMStyle();
9094   Alignment.AlignConsecutiveAssignments = false;
9095   verifyFormat("int a = 5;\n"
9096                "int oneTwoThree = 123;",
9097                Alignment);
9098   verifyFormat("int a = 5;\n"
9099                "int oneTwoThree = 123;",
9100                Alignment);
9101 
9102   Alignment.AlignConsecutiveAssignments = true;
9103   verifyFormat("int a           = 5;\n"
9104                "int oneTwoThree = 123;",
9105                Alignment);
9106   verifyFormat("int a           = method();\n"
9107                "int oneTwoThree = 133;",
9108                Alignment);
9109   verifyFormat("a &= 5;\n"
9110                "bcd *= 5;\n"
9111                "ghtyf += 5;\n"
9112                "dvfvdb -= 5;\n"
9113                "a /= 5;\n"
9114                "vdsvsv %= 5;\n"
9115                "sfdbddfbdfbb ^= 5;\n"
9116                "dvsdsv |= 5;\n"
9117                "int dsvvdvsdvvv = 123;",
9118                Alignment);
9119   verifyFormat("int i = 1, j = 10;\n"
9120                "something = 2000;",
9121                Alignment);
9122   verifyFormat("something = 2000;\n"
9123                "int i = 1, j = 10;\n",
9124                Alignment);
9125   verifyFormat("something = 2000;\n"
9126                "another   = 911;\n"
9127                "int i = 1, j = 10;\n"
9128                "oneMore = 1;\n"
9129                "i       = 2;",
9130                Alignment);
9131   verifyFormat("int a   = 5;\n"
9132                "int one = 1;\n"
9133                "method();\n"
9134                "int oneTwoThree = 123;\n"
9135                "int oneTwo      = 12;",
9136                Alignment);
9137   verifyFormat("int oneTwoThree = 123;\n"
9138                "int oneTwo      = 12;\n"
9139                "method();\n",
9140                Alignment);
9141   verifyFormat("int oneTwoThree = 123; // comment\n"
9142                "int oneTwo      = 12;  // comment",
9143                Alignment);
9144   EXPECT_EQ("int a = 5;\n"
9145             "\n"
9146             "int oneTwoThree = 123;",
9147             format("int a       = 5;\n"
9148                    "\n"
9149                    "int oneTwoThree= 123;",
9150                    Alignment));
9151   EXPECT_EQ("int a   = 5;\n"
9152             "int one = 1;\n"
9153             "\n"
9154             "int oneTwoThree = 123;",
9155             format("int a = 5;\n"
9156                    "int one = 1;\n"
9157                    "\n"
9158                    "int oneTwoThree = 123;",
9159                    Alignment));
9160   EXPECT_EQ("int a   = 5;\n"
9161             "int one = 1;\n"
9162             "\n"
9163             "int oneTwoThree = 123;\n"
9164             "int oneTwo      = 12;",
9165             format("int a = 5;\n"
9166                    "int one = 1;\n"
9167                    "\n"
9168                    "int oneTwoThree = 123;\n"
9169                    "int oneTwo = 12;",
9170                    Alignment));
9171   Alignment.AlignEscapedNewlinesLeft = true;
9172   verifyFormat("#define A               \\\n"
9173                "  int aaaa       = 12;  \\\n"
9174                "  int b          = 23;  \\\n"
9175                "  int ccc        = 234; \\\n"
9176                "  int dddddddddd = 2345;",
9177                Alignment);
9178   Alignment.AlignEscapedNewlinesLeft = false;
9179   verifyFormat("#define A                                                      "
9180                "                \\\n"
9181                "  int aaaa       = 12;                                         "
9182                "                \\\n"
9183                "  int b          = 23;                                         "
9184                "                \\\n"
9185                "  int ccc        = 234;                                        "
9186                "                \\\n"
9187                "  int dddddddddd = 2345;",
9188                Alignment);
9189   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
9190                "k = 4, int l = 5,\n"
9191                "                  int m = 6) {\n"
9192                "  int j      = 10;\n"
9193                "  otherThing = 1;\n"
9194                "}",
9195                Alignment);
9196   verifyFormat("void SomeFunction(int parameter = 0) {\n"
9197                "  int i   = 1;\n"
9198                "  int j   = 2;\n"
9199                "  int big = 10000;\n"
9200                "}",
9201                Alignment);
9202   verifyFormat("class C {\n"
9203                "public:\n"
9204                "  int i            = 1;\n"
9205                "  virtual void f() = 0;\n"
9206                "};",
9207                Alignment);
9208   verifyFormat("int i = 1;\n"
9209                "if (SomeType t = getSomething()) {\n"
9210                "}\n"
9211                "int j   = 2;\n"
9212                "int big = 10000;",
9213                Alignment);
9214   verifyFormat("int j = 7;\n"
9215                "for (int k = 0; k < N; ++k) {\n"
9216                "}\n"
9217                "int j   = 2;\n"
9218                "int big = 10000;\n"
9219                "}",
9220                Alignment);
9221   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9222   verifyFormat("int i = 1;\n"
9223                "LooooooooooongType loooooooooooooooooooooongVariable\n"
9224                "    = someLooooooooooooooooongFunction();\n"
9225                "int j = 2;",
9226                Alignment);
9227   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9228   verifyFormat("int i = 1;\n"
9229                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
9230                "    someLooooooooooooooooongFunction();\n"
9231                "int j = 2;",
9232                Alignment);
9233 
9234   verifyFormat("auto lambda = []() {\n"
9235                "  auto i = 0;\n"
9236                "  return 0;\n"
9237                "};\n"
9238                "int i  = 0;\n"
9239                "auto v = type{\n"
9240                "    i = 1,   //\n"
9241                "    (i = 2), //\n"
9242                "    i = 3    //\n"
9243                "};",
9244                Alignment);
9245 
9246   // FIXME: Should align all three assignments
9247   verifyFormat(
9248       "int i      = 1;\n"
9249       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
9250       "                          loooooooooooooooooooooongParameterB);\n"
9251       "int j = 2;",
9252       Alignment);
9253 
9254   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
9255                "          typename B   = very_long_type_name_1,\n"
9256                "          typename T_2 = very_long_type_name_2>\n"
9257                "auto foo() {}\n",
9258                Alignment);
9259   verifyFormat("int a, b = 1;\n"
9260                "int c  = 2;\n"
9261                "int dd = 3;\n",
9262                Alignment);
9263   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
9264                "float b[1][] = {{3.f}};\n",
9265                Alignment);
9266 }
9267 
TEST_F(FormatTest,AlignConsecutiveDeclarations)9268 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
9269   FormatStyle Alignment = getLLVMStyle();
9270   Alignment.AlignConsecutiveDeclarations = false;
9271   verifyFormat("float const a = 5;\n"
9272                "int oneTwoThree = 123;",
9273                Alignment);
9274   verifyFormat("int a = 5;\n"
9275                "float const oneTwoThree = 123;",
9276                Alignment);
9277 
9278   Alignment.AlignConsecutiveDeclarations = true;
9279   verifyFormat("float const a = 5;\n"
9280                "int         oneTwoThree = 123;",
9281                Alignment);
9282   verifyFormat("int         a = method();\n"
9283                "float const oneTwoThree = 133;",
9284                Alignment);
9285   verifyFormat("int i = 1, j = 10;\n"
9286                "something = 2000;",
9287                Alignment);
9288   verifyFormat("something = 2000;\n"
9289                "int i = 1, j = 10;\n",
9290                Alignment);
9291   verifyFormat("float      something = 2000;\n"
9292                "double     another = 911;\n"
9293                "int        i = 1, j = 10;\n"
9294                "const int *oneMore = 1;\n"
9295                "unsigned   i = 2;",
9296                Alignment);
9297   verifyFormat("float a = 5;\n"
9298                "int   one = 1;\n"
9299                "method();\n"
9300                "const double       oneTwoThree = 123;\n"
9301                "const unsigned int oneTwo = 12;",
9302                Alignment);
9303   verifyFormat("int      oneTwoThree{0}; // comment\n"
9304                "unsigned oneTwo;         // comment",
9305                Alignment);
9306   EXPECT_EQ("float const a = 5;\n"
9307             "\n"
9308             "int oneTwoThree = 123;",
9309             format("float const   a = 5;\n"
9310                    "\n"
9311                    "int           oneTwoThree= 123;",
9312                    Alignment));
9313   EXPECT_EQ("float a = 5;\n"
9314             "int   one = 1;\n"
9315             "\n"
9316             "unsigned oneTwoThree = 123;",
9317             format("float    a = 5;\n"
9318                    "int      one = 1;\n"
9319                    "\n"
9320                    "unsigned oneTwoThree = 123;",
9321                    Alignment));
9322   EXPECT_EQ("float a = 5;\n"
9323             "int   one = 1;\n"
9324             "\n"
9325             "unsigned oneTwoThree = 123;\n"
9326             "int      oneTwo = 12;",
9327             format("float    a = 5;\n"
9328                    "int one = 1;\n"
9329                    "\n"
9330                    "unsigned oneTwoThree = 123;\n"
9331                    "int oneTwo = 12;",
9332                    Alignment));
9333   Alignment.AlignConsecutiveAssignments = true;
9334   verifyFormat("float      something = 2000;\n"
9335                "double     another   = 911;\n"
9336                "int        i = 1, j = 10;\n"
9337                "const int *oneMore = 1;\n"
9338                "unsigned   i       = 2;",
9339                Alignment);
9340   verifyFormat("int      oneTwoThree = {0}; // comment\n"
9341                "unsigned oneTwo      = 0;   // comment",
9342                Alignment);
9343   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
9344             "  int const i   = 1;\n"
9345             "  int *     j   = 2;\n"
9346             "  int       big = 10000;\n"
9347             "\n"
9348             "  unsigned oneTwoThree = 123;\n"
9349             "  int      oneTwo      = 12;\n"
9350             "  method();\n"
9351             "  float k  = 2;\n"
9352             "  int   ll = 10000;\n"
9353             "}",
9354             format("void SomeFunction(int parameter= 0) {\n"
9355                    " int const  i= 1;\n"
9356                    "  int *j=2;\n"
9357                    " int big  =  10000;\n"
9358                    "\n"
9359                    "unsigned oneTwoThree  =123;\n"
9360                    "int oneTwo = 12;\n"
9361                    "  method();\n"
9362                    "float k= 2;\n"
9363                    "int ll=10000;\n"
9364                    "}",
9365                    Alignment));
9366   Alignment.AlignConsecutiveAssignments = false;
9367   Alignment.AlignEscapedNewlinesLeft = true;
9368   verifyFormat("#define A              \\\n"
9369                "  int       aaaa = 12; \\\n"
9370                "  float     b = 23;    \\\n"
9371                "  const int ccc = 234; \\\n"
9372                "  unsigned  dddddddddd = 2345;",
9373                Alignment);
9374   Alignment.AlignEscapedNewlinesLeft = false;
9375   Alignment.ColumnLimit = 30;
9376   verifyFormat("#define A                    \\\n"
9377                "  int       aaaa = 12;       \\\n"
9378                "  float     b = 23;          \\\n"
9379                "  const int ccc = 234;       \\\n"
9380                "  int       dddddddddd = 2345;",
9381                Alignment);
9382   Alignment.ColumnLimit = 80;
9383   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
9384                "k = 4, int l = 5,\n"
9385                "                  int m = 6) {\n"
9386                "  const int j = 10;\n"
9387                "  otherThing = 1;\n"
9388                "}",
9389                Alignment);
9390   verifyFormat("void SomeFunction(int parameter = 0) {\n"
9391                "  int const i = 1;\n"
9392                "  int *     j = 2;\n"
9393                "  int       big = 10000;\n"
9394                "}",
9395                Alignment);
9396   verifyFormat("class C {\n"
9397                "public:\n"
9398                "  int          i = 1;\n"
9399                "  virtual void f() = 0;\n"
9400                "};",
9401                Alignment);
9402   verifyFormat("float i = 1;\n"
9403                "if (SomeType t = getSomething()) {\n"
9404                "}\n"
9405                "const unsigned j = 2;\n"
9406                "int            big = 10000;",
9407                Alignment);
9408   verifyFormat("float j = 7;\n"
9409                "for (int k = 0; k < N; ++k) {\n"
9410                "}\n"
9411                "unsigned j = 2;\n"
9412                "int      big = 10000;\n"
9413                "}",
9414                Alignment);
9415   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9416   verifyFormat("float              i = 1;\n"
9417                "LooooooooooongType loooooooooooooooooooooongVariable\n"
9418                "    = someLooooooooooooooooongFunction();\n"
9419                "int j = 2;",
9420                Alignment);
9421   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
9422   verifyFormat("int                i = 1;\n"
9423                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
9424                "    someLooooooooooooooooongFunction();\n"
9425                "int j = 2;",
9426                Alignment);
9427 
9428   Alignment.AlignConsecutiveAssignments = true;
9429   verifyFormat("auto lambda = []() {\n"
9430                "  auto  ii = 0;\n"
9431                "  float j  = 0;\n"
9432                "  return 0;\n"
9433                "};\n"
9434                "int   i  = 0;\n"
9435                "float i2 = 0;\n"
9436                "auto  v  = type{\n"
9437                "    i = 1,   //\n"
9438                "    (i = 2), //\n"
9439                "    i = 3    //\n"
9440                "};",
9441                Alignment);
9442   Alignment.AlignConsecutiveAssignments = false;
9443 
9444   // FIXME: Should align all three declarations
9445   verifyFormat(
9446       "int      i = 1;\n"
9447       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
9448       "                          loooooooooooooooooooooongParameterB);\n"
9449       "int j = 2;",
9450       Alignment);
9451 
9452   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
9453   // We expect declarations and assignments to align, as long as it doesn't
9454   // exceed the column limit, starting a new alignemnt sequence whenever it
9455   // happens.
9456   Alignment.AlignConsecutiveAssignments = true;
9457   Alignment.ColumnLimit = 30;
9458   verifyFormat("float    ii              = 1;\n"
9459                "unsigned j               = 2;\n"
9460                "int someVerylongVariable = 1;\n"
9461                "AnotherLongType  ll = 123456;\n"
9462                "VeryVeryLongType k  = 2;\n"
9463                "int              myvar = 1;",
9464                Alignment);
9465   Alignment.ColumnLimit = 80;
9466   Alignment.AlignConsecutiveAssignments = false;
9467 
9468   verifyFormat(
9469       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
9470       "          typename LongType, typename B>\n"
9471       "auto foo() {}\n",
9472       Alignment);
9473   verifyFormat("float a, b = 1;\n"
9474                "int   c = 2;\n"
9475                "int   dd = 3;\n",
9476                Alignment);
9477   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
9478                "float b[1][] = {{3.f}};\n",
9479                Alignment);
9480   Alignment.AlignConsecutiveAssignments = true;
9481   verifyFormat("float a, b = 1;\n"
9482                "int   c  = 2;\n"
9483                "int   dd = 3;\n",
9484                Alignment);
9485   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
9486                "float b[1][] = {{3.f}};\n",
9487                Alignment);
9488   Alignment.AlignConsecutiveAssignments = false;
9489 
9490   Alignment.ColumnLimit = 30;
9491   Alignment.BinPackParameters = false;
9492   verifyFormat("void foo(float     a,\n"
9493                "         float     b,\n"
9494                "         int       c,\n"
9495                "         uint32_t *d) {\n"
9496                "  int *  e = 0;\n"
9497                "  float  f = 0;\n"
9498                "  double g = 0;\n"
9499                "}\n"
9500                "void bar(ino_t     a,\n"
9501                "         int       b,\n"
9502                "         uint32_t *c,\n"
9503                "         bool      d) {}\n",
9504                Alignment);
9505   Alignment.BinPackParameters = true;
9506   Alignment.ColumnLimit = 80;
9507 }
9508 
TEST_F(FormatTest,LinuxBraceBreaking)9509 TEST_F(FormatTest, LinuxBraceBreaking) {
9510   FormatStyle LinuxBraceStyle = getLLVMStyle();
9511   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
9512   verifyFormat("namespace a\n"
9513                "{\n"
9514                "class A\n"
9515                "{\n"
9516                "  void f()\n"
9517                "  {\n"
9518                "    if (true) {\n"
9519                "      a();\n"
9520                "      b();\n"
9521                "    } else {\n"
9522                "      a();\n"
9523                "    }\n"
9524                "  }\n"
9525                "  void g() { return; }\n"
9526                "};\n"
9527                "struct B {\n"
9528                "  int x;\n"
9529                "};\n"
9530                "}\n",
9531                LinuxBraceStyle);
9532   verifyFormat("enum X {\n"
9533                "  Y = 0,\n"
9534                "}\n",
9535                LinuxBraceStyle);
9536   verifyFormat("struct S {\n"
9537                "  int Type;\n"
9538                "  union {\n"
9539                "    int x;\n"
9540                "    double y;\n"
9541                "  } Value;\n"
9542                "  class C\n"
9543                "  {\n"
9544                "    MyFavoriteType Value;\n"
9545                "  } Class;\n"
9546                "}\n",
9547                LinuxBraceStyle);
9548 }
9549 
TEST_F(FormatTest,MozillaBraceBreaking)9550 TEST_F(FormatTest, MozillaBraceBreaking) {
9551   FormatStyle MozillaBraceStyle = getLLVMStyle();
9552   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
9553   verifyFormat("namespace a {\n"
9554                "class A\n"
9555                "{\n"
9556                "  void f()\n"
9557                "  {\n"
9558                "    if (true) {\n"
9559                "      a();\n"
9560                "      b();\n"
9561                "    }\n"
9562                "  }\n"
9563                "  void g() { return; }\n"
9564                "};\n"
9565                "enum E\n"
9566                "{\n"
9567                "  A,\n"
9568                "  // foo\n"
9569                "  B,\n"
9570                "  C\n"
9571                "};\n"
9572                "struct B\n"
9573                "{\n"
9574                "  int x;\n"
9575                "};\n"
9576                "}\n",
9577                MozillaBraceStyle);
9578   verifyFormat("struct S\n"
9579                "{\n"
9580                "  int Type;\n"
9581                "  union\n"
9582                "  {\n"
9583                "    int x;\n"
9584                "    double y;\n"
9585                "  } Value;\n"
9586                "  class C\n"
9587                "  {\n"
9588                "    MyFavoriteType Value;\n"
9589                "  } Class;\n"
9590                "}\n",
9591                MozillaBraceStyle);
9592 }
9593 
TEST_F(FormatTest,StroustrupBraceBreaking)9594 TEST_F(FormatTest, StroustrupBraceBreaking) {
9595   FormatStyle StroustrupBraceStyle = getLLVMStyle();
9596   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
9597   verifyFormat("namespace a {\n"
9598                "class A {\n"
9599                "  void f()\n"
9600                "  {\n"
9601                "    if (true) {\n"
9602                "      a();\n"
9603                "      b();\n"
9604                "    }\n"
9605                "  }\n"
9606                "  void g() { return; }\n"
9607                "};\n"
9608                "struct B {\n"
9609                "  int x;\n"
9610                "};\n"
9611                "}\n",
9612                StroustrupBraceStyle);
9613 
9614   verifyFormat("void foo()\n"
9615                "{\n"
9616                "  if (a) {\n"
9617                "    a();\n"
9618                "  }\n"
9619                "  else {\n"
9620                "    b();\n"
9621                "  }\n"
9622                "}\n",
9623                StroustrupBraceStyle);
9624 
9625   verifyFormat("#ifdef _DEBUG\n"
9626                "int foo(int i = 0)\n"
9627                "#else\n"
9628                "int foo(int i = 5)\n"
9629                "#endif\n"
9630                "{\n"
9631                "  return i;\n"
9632                "}",
9633                StroustrupBraceStyle);
9634 
9635   verifyFormat("void foo() {}\n"
9636                "void bar()\n"
9637                "#ifdef _DEBUG\n"
9638                "{\n"
9639                "  foo();\n"
9640                "}\n"
9641                "#else\n"
9642                "{\n"
9643                "}\n"
9644                "#endif",
9645                StroustrupBraceStyle);
9646 
9647   verifyFormat("void foobar() { int i = 5; }\n"
9648                "#ifdef _DEBUG\n"
9649                "void bar() {}\n"
9650                "#else\n"
9651                "void bar() { foobar(); }\n"
9652                "#endif",
9653                StroustrupBraceStyle);
9654 }
9655 
TEST_F(FormatTest,AllmanBraceBreaking)9656 TEST_F(FormatTest, AllmanBraceBreaking) {
9657   FormatStyle AllmanBraceStyle = getLLVMStyle();
9658   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
9659   verifyFormat("namespace a\n"
9660                "{\n"
9661                "class A\n"
9662                "{\n"
9663                "  void f()\n"
9664                "  {\n"
9665                "    if (true)\n"
9666                "    {\n"
9667                "      a();\n"
9668                "      b();\n"
9669                "    }\n"
9670                "  }\n"
9671                "  void g() { return; }\n"
9672                "};\n"
9673                "struct B\n"
9674                "{\n"
9675                "  int x;\n"
9676                "};\n"
9677                "}",
9678                AllmanBraceStyle);
9679 
9680   verifyFormat("void f()\n"
9681                "{\n"
9682                "  if (true)\n"
9683                "  {\n"
9684                "    a();\n"
9685                "  }\n"
9686                "  else if (false)\n"
9687                "  {\n"
9688                "    b();\n"
9689                "  }\n"
9690                "  else\n"
9691                "  {\n"
9692                "    c();\n"
9693                "  }\n"
9694                "}\n",
9695                AllmanBraceStyle);
9696 
9697   verifyFormat("void f()\n"
9698                "{\n"
9699                "  for (int i = 0; i < 10; ++i)\n"
9700                "  {\n"
9701                "    a();\n"
9702                "  }\n"
9703                "  while (false)\n"
9704                "  {\n"
9705                "    b();\n"
9706                "  }\n"
9707                "  do\n"
9708                "  {\n"
9709                "    c();\n"
9710                "  } while (false)\n"
9711                "}\n",
9712                AllmanBraceStyle);
9713 
9714   verifyFormat("void f(int a)\n"
9715                "{\n"
9716                "  switch (a)\n"
9717                "  {\n"
9718                "  case 0:\n"
9719                "    break;\n"
9720                "  case 1:\n"
9721                "  {\n"
9722                "    break;\n"
9723                "  }\n"
9724                "  case 2:\n"
9725                "  {\n"
9726                "  }\n"
9727                "  break;\n"
9728                "  default:\n"
9729                "    break;\n"
9730                "  }\n"
9731                "}\n",
9732                AllmanBraceStyle);
9733 
9734   verifyFormat("enum X\n"
9735                "{\n"
9736                "  Y = 0,\n"
9737                "}\n",
9738                AllmanBraceStyle);
9739   verifyFormat("enum X\n"
9740                "{\n"
9741                "  Y = 0\n"
9742                "}\n",
9743                AllmanBraceStyle);
9744 
9745   verifyFormat("@interface BSApplicationController ()\n"
9746                "{\n"
9747                "@private\n"
9748                "  id _extraIvar;\n"
9749                "}\n"
9750                "@end\n",
9751                AllmanBraceStyle);
9752 
9753   verifyFormat("#ifdef _DEBUG\n"
9754                "int foo(int i = 0)\n"
9755                "#else\n"
9756                "int foo(int i = 5)\n"
9757                "#endif\n"
9758                "{\n"
9759                "  return i;\n"
9760                "}",
9761                AllmanBraceStyle);
9762 
9763   verifyFormat("void foo() {}\n"
9764                "void bar()\n"
9765                "#ifdef _DEBUG\n"
9766                "{\n"
9767                "  foo();\n"
9768                "}\n"
9769                "#else\n"
9770                "{\n"
9771                "}\n"
9772                "#endif",
9773                AllmanBraceStyle);
9774 
9775   verifyFormat("void foobar() { int i = 5; }\n"
9776                "#ifdef _DEBUG\n"
9777                "void bar() {}\n"
9778                "#else\n"
9779                "void bar() { foobar(); }\n"
9780                "#endif",
9781                AllmanBraceStyle);
9782 
9783   // This shouldn't affect ObjC blocks..
9784   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
9785                "  // ...\n"
9786                "  int i;\n"
9787                "}];",
9788                AllmanBraceStyle);
9789   verifyFormat("void (^block)(void) = ^{\n"
9790                "  // ...\n"
9791                "  int i;\n"
9792                "};",
9793                AllmanBraceStyle);
9794   // .. or dict literals.
9795   verifyFormat("void f()\n"
9796                "{\n"
9797                "  [object someMethod:@{ @\"a\" : @\"b\" }];\n"
9798                "}",
9799                AllmanBraceStyle);
9800   verifyFormat("int f()\n"
9801                "{ // comment\n"
9802                "  return 42;\n"
9803                "}",
9804                AllmanBraceStyle);
9805 
9806   AllmanBraceStyle.ColumnLimit = 19;
9807   verifyFormat("void f() { int i; }", AllmanBraceStyle);
9808   AllmanBraceStyle.ColumnLimit = 18;
9809   verifyFormat("void f()\n"
9810                "{\n"
9811                "  int i;\n"
9812                "}",
9813                AllmanBraceStyle);
9814   AllmanBraceStyle.ColumnLimit = 80;
9815 
9816   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
9817   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = true;
9818   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
9819   verifyFormat("void f(bool b)\n"
9820                "{\n"
9821                "  if (b)\n"
9822                "  {\n"
9823                "    return;\n"
9824                "  }\n"
9825                "}\n",
9826                BreakBeforeBraceShortIfs);
9827   verifyFormat("void f(bool b)\n"
9828                "{\n"
9829                "  if (b) return;\n"
9830                "}\n",
9831                BreakBeforeBraceShortIfs);
9832   verifyFormat("void f(bool b)\n"
9833                "{\n"
9834                "  while (b)\n"
9835                "  {\n"
9836                "    return;\n"
9837                "  }\n"
9838                "}\n",
9839                BreakBeforeBraceShortIfs);
9840 }
9841 
TEST_F(FormatTest,GNUBraceBreaking)9842 TEST_F(FormatTest, GNUBraceBreaking) {
9843   FormatStyle GNUBraceStyle = getLLVMStyle();
9844   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
9845   verifyFormat("namespace a\n"
9846                "{\n"
9847                "class A\n"
9848                "{\n"
9849                "  void f()\n"
9850                "  {\n"
9851                "    int a;\n"
9852                "    {\n"
9853                "      int b;\n"
9854                "    }\n"
9855                "    if (true)\n"
9856                "      {\n"
9857                "        a();\n"
9858                "        b();\n"
9859                "      }\n"
9860                "  }\n"
9861                "  void g() { return; }\n"
9862                "}\n"
9863                "}",
9864                GNUBraceStyle);
9865 
9866   verifyFormat("void f()\n"
9867                "{\n"
9868                "  if (true)\n"
9869                "    {\n"
9870                "      a();\n"
9871                "    }\n"
9872                "  else if (false)\n"
9873                "    {\n"
9874                "      b();\n"
9875                "    }\n"
9876                "  else\n"
9877                "    {\n"
9878                "      c();\n"
9879                "    }\n"
9880                "}\n",
9881                GNUBraceStyle);
9882 
9883   verifyFormat("void f()\n"
9884                "{\n"
9885                "  for (int i = 0; i < 10; ++i)\n"
9886                "    {\n"
9887                "      a();\n"
9888                "    }\n"
9889                "  while (false)\n"
9890                "    {\n"
9891                "      b();\n"
9892                "    }\n"
9893                "  do\n"
9894                "    {\n"
9895                "      c();\n"
9896                "    }\n"
9897                "  while (false);\n"
9898                "}\n",
9899                GNUBraceStyle);
9900 
9901   verifyFormat("void f(int a)\n"
9902                "{\n"
9903                "  switch (a)\n"
9904                "    {\n"
9905                "    case 0:\n"
9906                "      break;\n"
9907                "    case 1:\n"
9908                "      {\n"
9909                "        break;\n"
9910                "      }\n"
9911                "    case 2:\n"
9912                "      {\n"
9913                "      }\n"
9914                "      break;\n"
9915                "    default:\n"
9916                "      break;\n"
9917                "    }\n"
9918                "}\n",
9919                GNUBraceStyle);
9920 
9921   verifyFormat("enum X\n"
9922                "{\n"
9923                "  Y = 0,\n"
9924                "}\n",
9925                GNUBraceStyle);
9926 
9927   verifyFormat("@interface BSApplicationController ()\n"
9928                "{\n"
9929                "@private\n"
9930                "  id _extraIvar;\n"
9931                "}\n"
9932                "@end\n",
9933                GNUBraceStyle);
9934 
9935   verifyFormat("#ifdef _DEBUG\n"
9936                "int foo(int i = 0)\n"
9937                "#else\n"
9938                "int foo(int i = 5)\n"
9939                "#endif\n"
9940                "{\n"
9941                "  return i;\n"
9942                "}",
9943                GNUBraceStyle);
9944 
9945   verifyFormat("void foo() {}\n"
9946                "void bar()\n"
9947                "#ifdef _DEBUG\n"
9948                "{\n"
9949                "  foo();\n"
9950                "}\n"
9951                "#else\n"
9952                "{\n"
9953                "}\n"
9954                "#endif",
9955                GNUBraceStyle);
9956 
9957   verifyFormat("void foobar() { int i = 5; }\n"
9958                "#ifdef _DEBUG\n"
9959                "void bar() {}\n"
9960                "#else\n"
9961                "void bar() { foobar(); }\n"
9962                "#endif",
9963                GNUBraceStyle);
9964 }
9965 
TEST_F(FormatTest,WebKitBraceBreaking)9966 TEST_F(FormatTest, WebKitBraceBreaking) {
9967   FormatStyle WebKitBraceStyle = getLLVMStyle();
9968   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
9969   verifyFormat("namespace a {\n"
9970                "class A {\n"
9971                "  void f()\n"
9972                "  {\n"
9973                "    if (true) {\n"
9974                "      a();\n"
9975                "      b();\n"
9976                "    }\n"
9977                "  }\n"
9978                "  void g() { return; }\n"
9979                "};\n"
9980                "enum E {\n"
9981                "  A,\n"
9982                "  // foo\n"
9983                "  B,\n"
9984                "  C\n"
9985                "};\n"
9986                "struct B {\n"
9987                "  int x;\n"
9988                "};\n"
9989                "}\n",
9990                WebKitBraceStyle);
9991   verifyFormat("struct S {\n"
9992                "  int Type;\n"
9993                "  union {\n"
9994                "    int x;\n"
9995                "    double y;\n"
9996                "  } Value;\n"
9997                "  class C {\n"
9998                "    MyFavoriteType Value;\n"
9999                "  } Class;\n"
10000                "};\n",
10001                WebKitBraceStyle);
10002 }
10003 
TEST_F(FormatTest,CatchExceptionReferenceBinding)10004 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
10005   verifyFormat("void f() {\n"
10006                "  try {\n"
10007                "  } catch (const Exception &e) {\n"
10008                "  }\n"
10009                "}\n",
10010                getLLVMStyle());
10011 }
10012 
TEST_F(FormatTest,UnderstandsPragmas)10013 TEST_F(FormatTest, UnderstandsPragmas) {
10014   verifyFormat("#pragma omp reduction(| : var)");
10015   verifyFormat("#pragma omp reduction(+ : var)");
10016 
10017   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
10018             "(including parentheses).",
10019             format("#pragma    mark   Any non-hyphenated or hyphenated string "
10020                    "(including parentheses)."));
10021 }
10022 
TEST_F(FormatTest,UnderstandPragmaOption)10023 TEST_F(FormatTest, UnderstandPragmaOption) {
10024   verifyFormat("#pragma option -C -A");
10025 
10026   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
10027 }
10028 
10029 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
10030   for (size_t i = 1; i < Styles.size(); ++i)                                   \
10031   EXPECT_EQ(Styles[0], Styles[i]) << "Style #" << i << " of " << Styles.size() \
10032                                   << " differs from Style #0"
10033 
TEST_F(FormatTest,GetsPredefinedStyleByName)10034 TEST_F(FormatTest, GetsPredefinedStyleByName) {
10035   SmallVector<FormatStyle, 3> Styles;
10036   Styles.resize(3);
10037 
10038   Styles[0] = getLLVMStyle();
10039   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
10040   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
10041   EXPECT_ALL_STYLES_EQUAL(Styles);
10042 
10043   Styles[0] = getGoogleStyle();
10044   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
10045   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
10046   EXPECT_ALL_STYLES_EQUAL(Styles);
10047 
10048   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
10049   EXPECT_TRUE(
10050       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
10051   EXPECT_TRUE(
10052       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
10053   EXPECT_ALL_STYLES_EQUAL(Styles);
10054 
10055   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
10056   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
10057   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
10058   EXPECT_ALL_STYLES_EQUAL(Styles);
10059 
10060   Styles[0] = getMozillaStyle();
10061   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
10062   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
10063   EXPECT_ALL_STYLES_EQUAL(Styles);
10064 
10065   Styles[0] = getWebKitStyle();
10066   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
10067   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
10068   EXPECT_ALL_STYLES_EQUAL(Styles);
10069 
10070   Styles[0] = getGNUStyle();
10071   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
10072   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
10073   EXPECT_ALL_STYLES_EQUAL(Styles);
10074 
10075   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
10076 }
10077 
TEST_F(FormatTest,GetsCorrectBasedOnStyle)10078 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
10079   SmallVector<FormatStyle, 8> Styles;
10080   Styles.resize(2);
10081 
10082   Styles[0] = getGoogleStyle();
10083   Styles[1] = getLLVMStyle();
10084   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
10085   EXPECT_ALL_STYLES_EQUAL(Styles);
10086 
10087   Styles.resize(5);
10088   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
10089   Styles[1] = getLLVMStyle();
10090   Styles[1].Language = FormatStyle::LK_JavaScript;
10091   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
10092 
10093   Styles[2] = getLLVMStyle();
10094   Styles[2].Language = FormatStyle::LK_JavaScript;
10095   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
10096                                   "BasedOnStyle: Google",
10097                                   &Styles[2])
10098                    .value());
10099 
10100   Styles[3] = getLLVMStyle();
10101   Styles[3].Language = FormatStyle::LK_JavaScript;
10102   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
10103                                   "Language: JavaScript",
10104                                   &Styles[3])
10105                    .value());
10106 
10107   Styles[4] = getLLVMStyle();
10108   Styles[4].Language = FormatStyle::LK_JavaScript;
10109   EXPECT_EQ(0, parseConfiguration("---\n"
10110                                   "BasedOnStyle: LLVM\n"
10111                                   "IndentWidth: 123\n"
10112                                   "---\n"
10113                                   "BasedOnStyle: Google\n"
10114                                   "Language: JavaScript",
10115                                   &Styles[4])
10116                    .value());
10117   EXPECT_ALL_STYLES_EQUAL(Styles);
10118 }
10119 
10120 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
10121   Style.FIELD = false;                                                         \
10122   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
10123   EXPECT_TRUE(Style.FIELD);                                                    \
10124   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
10125   EXPECT_FALSE(Style.FIELD);
10126 
10127 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
10128 
10129 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
10130   Style.STRUCT.FIELD = false;                                                  \
10131   EXPECT_EQ(0,                                                                 \
10132             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
10133                 .value());                                                     \
10134   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
10135   EXPECT_EQ(0,                                                                 \
10136             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
10137                 .value());                                                     \
10138   EXPECT_FALSE(Style.STRUCT.FIELD);
10139 
10140 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
10141   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
10142 
10143 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
10144   EXPECT_NE(VALUE, Style.FIELD);                                               \
10145   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
10146   EXPECT_EQ(VALUE, Style.FIELD)
10147 
TEST_F(FormatTest,ParsesConfigurationBools)10148 TEST_F(FormatTest, ParsesConfigurationBools) {
10149   FormatStyle Style = {};
10150   Style.Language = FormatStyle::LK_Cpp;
10151   CHECK_PARSE_BOOL(AlignEscapedNewlinesLeft);
10152   CHECK_PARSE_BOOL(AlignOperands);
10153   CHECK_PARSE_BOOL(AlignTrailingComments);
10154   CHECK_PARSE_BOOL(AlignConsecutiveAssignments);
10155   CHECK_PARSE_BOOL(AlignConsecutiveDeclarations);
10156   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
10157   CHECK_PARSE_BOOL(AllowShortBlocksOnASingleLine);
10158   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
10159   CHECK_PARSE_BOOL(AllowShortIfStatementsOnASingleLine);
10160   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
10161   CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
10162   CHECK_PARSE_BOOL(BinPackArguments);
10163   CHECK_PARSE_BOOL(BinPackParameters);
10164   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
10165   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
10166   CHECK_PARSE_BOOL(BreakConstructorInitializersBeforeComma);
10167   CHECK_PARSE_BOOL(BreakStringLiterals);
10168   CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
10169   CHECK_PARSE_BOOL(DerivePointerAlignment);
10170   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
10171   CHECK_PARSE_BOOL(DisableFormat);
10172   CHECK_PARSE_BOOL(IndentCaseLabels);
10173   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
10174   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
10175   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
10176   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
10177   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
10178   CHECK_PARSE_BOOL(ReflowComments);
10179   CHECK_PARSE_BOOL(SortIncludes);
10180   CHECK_PARSE_BOOL(SpacesInParentheses);
10181   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
10182   CHECK_PARSE_BOOL(SpacesInAngles);
10183   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
10184   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
10185   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
10186   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
10187   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
10188 
10189   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
10190   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterControlStatement);
10191   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
10192   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
10193   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
10194   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
10195   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
10196   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
10197   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
10198   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
10199   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
10200 }
10201 
10202 #undef CHECK_PARSE_BOOL
10203 
TEST_F(FormatTest,ParsesConfiguration)10204 TEST_F(FormatTest, ParsesConfiguration) {
10205   FormatStyle Style = {};
10206   Style.Language = FormatStyle::LK_Cpp;
10207   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
10208   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
10209               ConstructorInitializerIndentWidth, 1234u);
10210   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
10211   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
10212   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
10213   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
10214               PenaltyBreakBeforeFirstCallParameter, 1234u);
10215   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
10216   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
10217               PenaltyReturnTypeOnItsOwnLine, 1234u);
10218   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
10219               SpacesBeforeTrailingComments, 1234u);
10220   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
10221   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
10222   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
10223 
10224   Style.PointerAlignment = FormatStyle::PAS_Middle;
10225   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
10226               FormatStyle::PAS_Left);
10227   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
10228               FormatStyle::PAS_Right);
10229   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
10230               FormatStyle::PAS_Middle);
10231   // For backward compatibility:
10232   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
10233               FormatStyle::PAS_Left);
10234   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
10235               FormatStyle::PAS_Right);
10236   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
10237               FormatStyle::PAS_Middle);
10238 
10239   Style.Standard = FormatStyle::LS_Auto;
10240   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
10241   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Cpp11);
10242   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
10243   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
10244   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
10245 
10246   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
10247   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
10248               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
10249   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
10250               FormatStyle::BOS_None);
10251   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
10252               FormatStyle::BOS_All);
10253   // For backward compatibility:
10254   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
10255               FormatStyle::BOS_None);
10256   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
10257               FormatStyle::BOS_All);
10258 
10259   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
10260   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
10261               FormatStyle::BAS_Align);
10262   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
10263               FormatStyle::BAS_DontAlign);
10264   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
10265               FormatStyle::BAS_AlwaysBreak);
10266   // For backward compatibility:
10267   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
10268               FormatStyle::BAS_DontAlign);
10269   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
10270               FormatStyle::BAS_Align);
10271 
10272   Style.UseTab = FormatStyle::UT_ForIndentation;
10273   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
10274   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
10275   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
10276   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
10277               FormatStyle::UT_ForContinuationAndIndentation);
10278   // For backward compatibility:
10279   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
10280   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
10281 
10282   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
10283   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
10284               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
10285   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
10286               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
10287   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
10288               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
10289   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
10290               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
10291   // For backward compatibility:
10292   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
10293               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
10294   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
10295               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
10296 
10297   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
10298   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
10299               FormatStyle::SBPO_Never);
10300   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
10301               FormatStyle::SBPO_Always);
10302   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
10303               FormatStyle::SBPO_ControlStatements);
10304   // For backward compatibility:
10305   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
10306               FormatStyle::SBPO_Never);
10307   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
10308               FormatStyle::SBPO_ControlStatements);
10309 
10310   Style.ColumnLimit = 123;
10311   FormatStyle BaseStyle = getLLVMStyle();
10312   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
10313   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
10314 
10315   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
10316   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
10317               FormatStyle::BS_Attach);
10318   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
10319               FormatStyle::BS_Linux);
10320   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
10321               FormatStyle::BS_Mozilla);
10322   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
10323               FormatStyle::BS_Stroustrup);
10324   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
10325               FormatStyle::BS_Allman);
10326   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
10327   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
10328               FormatStyle::BS_WebKit);
10329   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
10330               FormatStyle::BS_Custom);
10331 
10332   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10333   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
10334               FormatStyle::RTBS_None);
10335   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
10336               FormatStyle::RTBS_All);
10337   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
10338               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
10339   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
10340               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
10341   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
10342               AlwaysBreakAfterReturnType,
10343               FormatStyle::RTBS_TopLevelDefinitions);
10344 
10345   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
10346   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
10347               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
10348   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
10349               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
10350   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
10351               AlwaysBreakAfterDefinitionReturnType,
10352               FormatStyle::DRTBS_TopLevel);
10353 
10354   Style.NamespaceIndentation = FormatStyle::NI_All;
10355   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
10356               FormatStyle::NI_None);
10357   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
10358               FormatStyle::NI_Inner);
10359   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
10360               FormatStyle::NI_All);
10361 
10362   // FIXME: This is required because parsing a configuration simply overwrites
10363   // the first N elements of the list instead of resetting it.
10364   Style.ForEachMacros.clear();
10365   std::vector<std::string> BoostForeach;
10366   BoostForeach.push_back("BOOST_FOREACH");
10367   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
10368   std::vector<std::string> BoostAndQForeach;
10369   BoostAndQForeach.push_back("BOOST_FOREACH");
10370   BoostAndQForeach.push_back("Q_FOREACH");
10371   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
10372               BoostAndQForeach);
10373 
10374   Style.IncludeCategories.clear();
10375   std::vector<FormatStyle::IncludeCategory> ExpectedCategories = {{"abc/.*", 2},
10376                                                                   {".*", 1}};
10377   CHECK_PARSE("IncludeCategories:\n"
10378               "  - Regex: abc/.*\n"
10379               "    Priority: 2\n"
10380               "  - Regex: .*\n"
10381               "    Priority: 1",
10382               IncludeCategories, ExpectedCategories);
10383   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeIsMainRegex, "abc$");
10384 }
10385 
TEST_F(FormatTest,ParsesConfigurationWithLanguages)10386 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
10387   FormatStyle Style = {};
10388   Style.Language = FormatStyle::LK_Cpp;
10389   CHECK_PARSE("Language: Cpp\n"
10390               "IndentWidth: 12",
10391               IndentWidth, 12u);
10392   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
10393                                "IndentWidth: 34",
10394                                &Style),
10395             ParseError::Unsuitable);
10396   EXPECT_EQ(12u, Style.IndentWidth);
10397   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
10398   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
10399 
10400   Style.Language = FormatStyle::LK_JavaScript;
10401   CHECK_PARSE("Language: JavaScript\n"
10402               "IndentWidth: 12",
10403               IndentWidth, 12u);
10404   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
10405   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
10406                                "IndentWidth: 34",
10407                                &Style),
10408             ParseError::Unsuitable);
10409   EXPECT_EQ(23u, Style.IndentWidth);
10410   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
10411   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
10412 
10413   CHECK_PARSE("BasedOnStyle: LLVM\n"
10414               "IndentWidth: 67",
10415               IndentWidth, 67u);
10416 
10417   CHECK_PARSE("---\n"
10418               "Language: JavaScript\n"
10419               "IndentWidth: 12\n"
10420               "---\n"
10421               "Language: Cpp\n"
10422               "IndentWidth: 34\n"
10423               "...\n",
10424               IndentWidth, 12u);
10425 
10426   Style.Language = FormatStyle::LK_Cpp;
10427   CHECK_PARSE("---\n"
10428               "Language: JavaScript\n"
10429               "IndentWidth: 12\n"
10430               "---\n"
10431               "Language: Cpp\n"
10432               "IndentWidth: 34\n"
10433               "...\n",
10434               IndentWidth, 34u);
10435   CHECK_PARSE("---\n"
10436               "IndentWidth: 78\n"
10437               "---\n"
10438               "Language: JavaScript\n"
10439               "IndentWidth: 56\n"
10440               "...\n",
10441               IndentWidth, 78u);
10442 
10443   Style.ColumnLimit = 123;
10444   Style.IndentWidth = 234;
10445   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
10446   Style.TabWidth = 345;
10447   EXPECT_FALSE(parseConfiguration("---\n"
10448                                   "IndentWidth: 456\n"
10449                                   "BreakBeforeBraces: Allman\n"
10450                                   "---\n"
10451                                   "Language: JavaScript\n"
10452                                   "IndentWidth: 111\n"
10453                                   "TabWidth: 111\n"
10454                                   "---\n"
10455                                   "Language: Cpp\n"
10456                                   "BreakBeforeBraces: Stroustrup\n"
10457                                   "TabWidth: 789\n"
10458                                   "...\n",
10459                                   &Style));
10460   EXPECT_EQ(123u, Style.ColumnLimit);
10461   EXPECT_EQ(456u, Style.IndentWidth);
10462   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
10463   EXPECT_EQ(789u, Style.TabWidth);
10464 
10465   EXPECT_EQ(parseConfiguration("---\n"
10466                                "Language: JavaScript\n"
10467                                "IndentWidth: 56\n"
10468                                "---\n"
10469                                "IndentWidth: 78\n"
10470                                "...\n",
10471                                &Style),
10472             ParseError::Error);
10473   EXPECT_EQ(parseConfiguration("---\n"
10474                                "Language: JavaScript\n"
10475                                "IndentWidth: 56\n"
10476                                "---\n"
10477                                "Language: JavaScript\n"
10478                                "IndentWidth: 78\n"
10479                                "...\n",
10480                                &Style),
10481             ParseError::Error);
10482 
10483   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
10484 }
10485 
10486 #undef CHECK_PARSE
10487 
TEST_F(FormatTest,UsesLanguageForBasedOnStyle)10488 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
10489   FormatStyle Style = {};
10490   Style.Language = FormatStyle::LK_JavaScript;
10491   Style.BreakBeforeTernaryOperators = true;
10492   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
10493   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
10494 
10495   Style.BreakBeforeTernaryOperators = true;
10496   EXPECT_EQ(0, parseConfiguration("---\n"
10497                                   "BasedOnStyle: Google\n"
10498                                   "---\n"
10499                                   "Language: JavaScript\n"
10500                                   "IndentWidth: 76\n"
10501                                   "...\n",
10502                                   &Style)
10503                    .value());
10504   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
10505   EXPECT_EQ(76u, Style.IndentWidth);
10506   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
10507 }
10508 
TEST_F(FormatTest,ConfigurationRoundTripTest)10509 TEST_F(FormatTest, ConfigurationRoundTripTest) {
10510   FormatStyle Style = getLLVMStyle();
10511   std::string YAML = configurationAsText(Style);
10512   FormatStyle ParsedStyle = {};
10513   ParsedStyle.Language = FormatStyle::LK_Cpp;
10514   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
10515   EXPECT_EQ(Style, ParsedStyle);
10516 }
10517 
TEST_F(FormatTest,WorksFor8bitEncodings)10518 TEST_F(FormatTest, WorksFor8bitEncodings) {
10519   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
10520             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
10521             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
10522             "\"\xef\xee\xf0\xf3...\"",
10523             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
10524                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
10525                    "\xef\xee\xf0\xf3...\"",
10526                    getLLVMStyleWithColumns(12)));
10527 }
10528 
TEST_F(FormatTest,HandlesUTF8BOM)10529 TEST_F(FormatTest, HandlesUTF8BOM) {
10530   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
10531   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
10532             format("\xef\xbb\xbf#include <iostream>"));
10533   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
10534             format("\xef\xbb\xbf\n#include <iostream>"));
10535 }
10536 
10537 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
10538 #if !defined(_MSC_VER)
10539 
TEST_F(FormatTest,CountsUTF8CharactersProperly)10540 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
10541   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
10542                getLLVMStyleWithColumns(35));
10543   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
10544                getLLVMStyleWithColumns(31));
10545   verifyFormat("// Однажды в студёную зимнюю пору...",
10546                getLLVMStyleWithColumns(36));
10547   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
10548   verifyFormat("/* Однажды в студёную зимнюю пору... */",
10549                getLLVMStyleWithColumns(39));
10550   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
10551                getLLVMStyleWithColumns(35));
10552 }
10553 
TEST_F(FormatTest,SplitsUTF8Strings)10554 TEST_F(FormatTest, SplitsUTF8Strings) {
10555   // Non-printable characters' width is currently considered to be the length in
10556   // bytes in UTF8. The characters can be displayed in very different manner
10557   // (zero-width, single width with a substitution glyph, expanded to their code
10558   // (e.g. "<8d>"), so there's no single correct way to handle them.
10559   EXPECT_EQ("\"aaaaÄ\"\n"
10560             "\"\xc2\x8d\";",
10561             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
10562   EXPECT_EQ("\"aaaaaaaÄ\"\n"
10563             "\"\xc2\x8d\";",
10564             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
10565   EXPECT_EQ("\"Однажды, в \"\n"
10566             "\"студёную \"\n"
10567             "\"зимнюю \"\n"
10568             "\"пору,\"",
10569             format("\"Однажды, в студёную зимнюю пору,\"",
10570                    getLLVMStyleWithColumns(13)));
10571   EXPECT_EQ(
10572       "\"一 二 三 \"\n"
10573       "\"四 五六 \"\n"
10574       "\"七 八 九 \"\n"
10575       "\"十\"",
10576       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
10577   EXPECT_EQ("\"一\t二 \"\n"
10578             "\"\t三 \"\n"
10579             "\"四 五\t六 \"\n"
10580             "\"\t七 \"\n"
10581             "\"八九十\tqq\"",
10582             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
10583                    getLLVMStyleWithColumns(11)));
10584 
10585   // UTF8 character in an escape sequence.
10586   EXPECT_EQ("\"aaaaaa\"\n"
10587             "\"\\\xC2\x8D\"",
10588             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
10589 }
10590 
TEST_F(FormatTest,HandlesDoubleWidthCharsInMultiLineStrings)10591 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
10592   EXPECT_EQ("const char *sssss =\n"
10593             "    \"一二三四五六七八\\\n"
10594             " 九 十\";",
10595             format("const char *sssss = \"一二三四五六七八\\\n"
10596                    " 九 十\";",
10597                    getLLVMStyleWithColumns(30)));
10598 }
10599 
TEST_F(FormatTest,SplitsUTF8LineComments)10600 TEST_F(FormatTest, SplitsUTF8LineComments) {
10601   EXPECT_EQ("// aaaaÄ\xc2\x8d",
10602             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
10603   EXPECT_EQ("// Я из лесу\n"
10604             "// вышел; был\n"
10605             "// сильный\n"
10606             "// мороз.",
10607             format("// Я из лесу вышел; был сильный мороз.",
10608                    getLLVMStyleWithColumns(13)));
10609   EXPECT_EQ("// 一二三\n"
10610             "// 四五六七\n"
10611             "// 八  九\n"
10612             "// 十",
10613             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
10614 }
10615 
TEST_F(FormatTest,SplitsUTF8BlockComments)10616 TEST_F(FormatTest, SplitsUTF8BlockComments) {
10617   EXPECT_EQ("/* Гляжу,\n"
10618             " * поднимается\n"
10619             " * медленно в\n"
10620             " * гору\n"
10621             " * Лошадка,\n"
10622             " * везущая\n"
10623             " * хворосту\n"
10624             " * воз. */",
10625             format("/* Гляжу, поднимается медленно в гору\n"
10626                    " * Лошадка, везущая хворосту воз. */",
10627                    getLLVMStyleWithColumns(13)));
10628   EXPECT_EQ(
10629       "/* 一二三\n"
10630       " * 四五六七\n"
10631       " * 八  九\n"
10632       " * 十  */",
10633       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
10634   EXPECT_EQ("/* �������� ��������\n"
10635             " * ��������\n"
10636             " * ������-�� */",
10637             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
10638 }
10639 
10640 #endif // _MSC_VER
10641 
TEST_F(FormatTest,ConstructorInitializerIndentWidth)10642 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
10643   FormatStyle Style = getLLVMStyle();
10644 
10645   Style.ConstructorInitializerIndentWidth = 4;
10646   verifyFormat(
10647       "SomeClass::Constructor()\n"
10648       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
10649       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
10650       Style);
10651 
10652   Style.ConstructorInitializerIndentWidth = 2;
10653   verifyFormat(
10654       "SomeClass::Constructor()\n"
10655       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
10656       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
10657       Style);
10658 
10659   Style.ConstructorInitializerIndentWidth = 0;
10660   verifyFormat(
10661       "SomeClass::Constructor()\n"
10662       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
10663       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
10664       Style);
10665   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
10666   verifyFormat(
10667       "SomeLongTemplateVariableName<\n"
10668       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
10669       Style);
10670   verifyFormat(
10671       "bool smaller = 1 < bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
10672       "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
10673       Style);
10674 }
10675 
TEST_F(FormatTest,BreakConstructorInitializersBeforeComma)10676 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
10677   FormatStyle Style = getLLVMStyle();
10678   Style.BreakConstructorInitializersBeforeComma = true;
10679   Style.ConstructorInitializerIndentWidth = 4;
10680   verifyFormat("SomeClass::Constructor()\n"
10681                "    : a(a)\n"
10682                "    , b(b)\n"
10683                "    , c(c) {}",
10684                Style);
10685   verifyFormat("SomeClass::Constructor()\n"
10686                "    : a(a) {}",
10687                Style);
10688 
10689   Style.ColumnLimit = 0;
10690   verifyFormat("SomeClass::Constructor()\n"
10691                "    : a(a) {}",
10692                Style);
10693   verifyFormat("SomeClass::Constructor() noexcept\n"
10694                "    : a(a) {}",
10695                Style);
10696   verifyFormat("SomeClass::Constructor()\n"
10697                "    : a(a)\n"
10698                "    , b(b)\n"
10699                "    , c(c) {}",
10700                Style);
10701   verifyFormat("SomeClass::Constructor()\n"
10702                "    : a(a) {\n"
10703                "  foo();\n"
10704                "  bar();\n"
10705                "}",
10706                Style);
10707 
10708   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10709   verifyFormat("SomeClass::Constructor()\n"
10710                "    : a(a)\n"
10711                "    , b(b)\n"
10712                "    , c(c) {\n}",
10713                Style);
10714   verifyFormat("SomeClass::Constructor()\n"
10715                "    : a(a) {\n}",
10716                Style);
10717 
10718   Style.ColumnLimit = 80;
10719   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
10720   Style.ConstructorInitializerIndentWidth = 2;
10721   verifyFormat("SomeClass::Constructor()\n"
10722                "  : a(a)\n"
10723                "  , b(b)\n"
10724                "  , c(c) {}",
10725                Style);
10726 
10727   Style.ConstructorInitializerIndentWidth = 0;
10728   verifyFormat("SomeClass::Constructor()\n"
10729                ": a(a)\n"
10730                ", b(b)\n"
10731                ", c(c) {}",
10732                Style);
10733 
10734   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
10735   Style.ConstructorInitializerIndentWidth = 4;
10736   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
10737   verifyFormat(
10738       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
10739       Style);
10740   verifyFormat(
10741       "SomeClass::Constructor()\n"
10742       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
10743       Style);
10744   Style.ConstructorInitializerIndentWidth = 4;
10745   Style.ColumnLimit = 60;
10746   verifyFormat("SomeClass::Constructor()\n"
10747                "    : aaaaaaaa(aaaaaaaa)\n"
10748                "    , aaaaaaaa(aaaaaaaa)\n"
10749                "    , aaaaaaaa(aaaaaaaa) {}",
10750                Style);
10751 }
10752 
TEST_F(FormatTest,Destructors)10753 TEST_F(FormatTest, Destructors) {
10754   verifyFormat("void F(int &i) { i.~int(); }");
10755   verifyFormat("void F(int &i) { i->~int(); }");
10756 }
10757 
TEST_F(FormatTest,FormatsWithWebKitStyle)10758 TEST_F(FormatTest, FormatsWithWebKitStyle) {
10759   FormatStyle Style = getWebKitStyle();
10760 
10761   // Don't indent in outer namespaces.
10762   verifyFormat("namespace outer {\n"
10763                "int i;\n"
10764                "namespace inner {\n"
10765                "    int i;\n"
10766                "} // namespace inner\n"
10767                "} // namespace outer\n"
10768                "namespace other_outer {\n"
10769                "int i;\n"
10770                "}",
10771                Style);
10772 
10773   // Don't indent case labels.
10774   verifyFormat("switch (variable) {\n"
10775                "case 1:\n"
10776                "case 2:\n"
10777                "    doSomething();\n"
10778                "    break;\n"
10779                "default:\n"
10780                "    ++variable;\n"
10781                "}",
10782                Style);
10783 
10784   // Wrap before binary operators.
10785   EXPECT_EQ("void f()\n"
10786             "{\n"
10787             "    if (aaaaaaaaaaaaaaaa\n"
10788             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
10789             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
10790             "        return;\n"
10791             "}",
10792             format("void f() {\n"
10793                    "if (aaaaaaaaaaaaaaaa\n"
10794                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
10795                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
10796                    "return;\n"
10797                    "}",
10798                    Style));
10799 
10800   // Allow functions on a single line.
10801   verifyFormat("void f() { return; }", Style);
10802 
10803   // Constructor initializers are formatted one per line with the "," on the
10804   // new line.
10805   verifyFormat("Constructor()\n"
10806                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
10807                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
10808                "          aaaaaaaaaaaaaa)\n"
10809                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
10810                "{\n"
10811                "}",
10812                Style);
10813   verifyFormat("SomeClass::Constructor()\n"
10814                "    : a(a)\n"
10815                "{\n"
10816                "}",
10817                Style);
10818   EXPECT_EQ("SomeClass::Constructor()\n"
10819             "    : a(a)\n"
10820             "{\n"
10821             "}",
10822             format("SomeClass::Constructor():a(a){}", Style));
10823   verifyFormat("SomeClass::Constructor()\n"
10824                "    : a(a)\n"
10825                "    , b(b)\n"
10826                "    , c(c)\n"
10827                "{\n"
10828                "}",
10829                Style);
10830   verifyFormat("SomeClass::Constructor()\n"
10831                "    : a(a)\n"
10832                "{\n"
10833                "    foo();\n"
10834                "    bar();\n"
10835                "}",
10836                Style);
10837 
10838   // Access specifiers should be aligned left.
10839   verifyFormat("class C {\n"
10840                "public:\n"
10841                "    int i;\n"
10842                "};",
10843                Style);
10844 
10845   // Do not align comments.
10846   verifyFormat("int a; // Do not\n"
10847                "double b; // align comments.",
10848                Style);
10849 
10850   // Do not align operands.
10851   EXPECT_EQ("ASSERT(aaaa\n"
10852             "    || bbbb);",
10853             format("ASSERT ( aaaa\n||bbbb);", Style));
10854 
10855   // Accept input's line breaks.
10856   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
10857             "    || bbbbbbbbbbbbbbb) {\n"
10858             "    i++;\n"
10859             "}",
10860             format("if (aaaaaaaaaaaaaaa\n"
10861                    "|| bbbbbbbbbbbbbbb) { i++; }",
10862                    Style));
10863   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
10864             "    i++;\n"
10865             "}",
10866             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
10867 
10868   // Don't automatically break all macro definitions (llvm.org/PR17842).
10869   verifyFormat("#define aNumber 10", Style);
10870   // However, generally keep the line breaks that the user authored.
10871   EXPECT_EQ("#define aNumber \\\n"
10872             "    10",
10873             format("#define aNumber \\\n"
10874                    " 10",
10875                    Style));
10876 
10877   // Keep empty and one-element array literals on a single line.
10878   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
10879             "                                  copyItems:YES];",
10880             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
10881                    "copyItems:YES];",
10882                    Style));
10883   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
10884             "                                  copyItems:YES];",
10885             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
10886                    "             copyItems:YES];",
10887                    Style));
10888   // FIXME: This does not seem right, there should be more indentation before
10889   // the array literal's entries. Nested blocks have the same problem.
10890   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
10891             "    @\"a\",\n"
10892             "    @\"a\"\n"
10893             "]\n"
10894             "                                  copyItems:YES];",
10895             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
10896                    "     @\"a\",\n"
10897                    "     @\"a\"\n"
10898                    "     ]\n"
10899                    "       copyItems:YES];",
10900                    Style));
10901   EXPECT_EQ(
10902       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
10903       "                                  copyItems:YES];",
10904       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
10905              "   copyItems:YES];",
10906              Style));
10907 
10908   verifyFormat("[self.a b:c c:d];", Style);
10909   EXPECT_EQ("[self.a b:c\n"
10910             "        c:d];",
10911             format("[self.a b:c\n"
10912                    "c:d];",
10913                    Style));
10914 }
10915 
TEST_F(FormatTest,FormatsLambdas)10916 TEST_F(FormatTest, FormatsLambdas) {
10917   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
10918   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
10919   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
10920   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
10921   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
10922   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
10923   verifyFormat("void f() {\n"
10924                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
10925                "}\n");
10926   verifyFormat("void f() {\n"
10927                "  other(x.begin(), //\n"
10928                "        x.end(),   //\n"
10929                "        [&](int, int) { return 1; });\n"
10930                "}\n");
10931   verifyFormat("SomeFunction([]() { // A cool function...\n"
10932                "  return 43;\n"
10933                "});");
10934   EXPECT_EQ("SomeFunction([]() {\n"
10935             "#define A a\n"
10936             "  return 43;\n"
10937             "});",
10938             format("SomeFunction([](){\n"
10939                    "#define A a\n"
10940                    "return 43;\n"
10941                    "});"));
10942   verifyFormat("void f() {\n"
10943                "  SomeFunction([](decltype(x), A *a) {});\n"
10944                "}");
10945   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10946                "    [](const aaaaaaaaaa &a) { return a; });");
10947   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
10948                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
10949                "});");
10950   verifyFormat("Constructor()\n"
10951                "    : Field([] { // comment\n"
10952                "        int i;\n"
10953                "      }) {}");
10954   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
10955                "  return some_parameter.size();\n"
10956                "};");
10957   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
10958                "    [](const string &s) { return s; };");
10959   verifyFormat("int i = aaaaaa ? 1 //\n"
10960                "               : [] {\n"
10961                "                   return 2; //\n"
10962                "                 }();");
10963   verifyFormat("llvm::errs() << \"number of twos is \"\n"
10964                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
10965                "                  return x == 2; // force break\n"
10966                "                });");
10967   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa([=](\n"
10968                "    int iiiiiiiiiiii) {\n"
10969                "  return aaaaaaaaaaaaaaaaaaaaaaa != aaaaaaaaaaaaaaaaaaaaaaa;\n"
10970                "});",
10971                getLLVMStyleWithColumns(60));
10972   verifyFormat("SomeFunction({[&] {\n"
10973                "                // comment\n"
10974                "              },\n"
10975                "              [&] {\n"
10976                "                // comment\n"
10977                "              }});");
10978   verifyFormat("SomeFunction({[&] {\n"
10979                "  // comment\n"
10980                "}});");
10981   verifyFormat("virtual aaaaaaaaaaaaaaaa(std::function<bool()> bbbbbbbbbbbb =\n"
10982                "                             [&]() { return true; },\n"
10983                "                         aaaaa aaaaaaaaa);");
10984 
10985   // Lambdas with return types.
10986   verifyFormat("int c = []() -> int { return 2; }();\n");
10987   verifyFormat("int c = []() -> int * { return 2; }();\n");
10988   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
10989   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
10990   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
10991   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
10992   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
10993   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
10994   verifyFormat("[a, a]() -> a<1> {};");
10995   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
10996                "                   int j) -> int {\n"
10997                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
10998                "};");
10999   verifyFormat(
11000       "aaaaaaaaaaaaaaaaaaaaaa(\n"
11001       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
11002       "      return aaaaaaaaaaaaaaaaa;\n"
11003       "    });",
11004       getLLVMStyleWithColumns(70));
11005   verifyFormat("[]() //\n"
11006                "    -> int {\n"
11007                "  return 1; //\n"
11008                "};");
11009 
11010   // Multiple lambdas in the same parentheses change indentation rules.
11011   verifyFormat("SomeFunction(\n"
11012                "    []() {\n"
11013                "      int i = 42;\n"
11014                "      return i;\n"
11015                "    },\n"
11016                "    []() {\n"
11017                "      int j = 43;\n"
11018                "      return j;\n"
11019                "    });");
11020 
11021   // More complex introducers.
11022   verifyFormat("return [i, args...] {};");
11023 
11024   // Not lambdas.
11025   verifyFormat("constexpr char hello[]{\"hello\"};");
11026   verifyFormat("double &operator[](int i) { return 0; }\n"
11027                "int i;");
11028   verifyFormat("std::unique_ptr<int[]> foo() {}");
11029   verifyFormat("int i = a[a][a]->f();");
11030   verifyFormat("int i = (*b)[a]->f();");
11031 
11032   // Other corner cases.
11033   verifyFormat("void f() {\n"
11034                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
11035                "      );\n"
11036                "}");
11037 
11038   // Lambdas created through weird macros.
11039   verifyFormat("void f() {\n"
11040                "  MACRO((const AA &a) { return 1; });\n"
11041                "  MACRO((AA &a) { return 1; });\n"
11042                "}");
11043 
11044   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
11045                "      doo_dah();\n"
11046                "      doo_dah();\n"
11047                "    })) {\n"
11048                "}");
11049   verifyFormat("auto lambda = []() {\n"
11050                "  int a = 2\n"
11051                "#if A\n"
11052                "          + 2\n"
11053                "#endif\n"
11054                "      ;\n"
11055                "};");
11056 }
11057 
TEST_F(FormatTest,FormatsBlocks)11058 TEST_F(FormatTest, FormatsBlocks) {
11059   FormatStyle ShortBlocks = getLLVMStyle();
11060   ShortBlocks.AllowShortBlocksOnASingleLine = true;
11061   verifyFormat("int (^Block)(int, int);", ShortBlocks);
11062   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
11063   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
11064   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
11065   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
11066   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
11067 
11068   verifyFormat("foo(^{ bar(); });", ShortBlocks);
11069   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
11070   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
11071 
11072   verifyFormat("[operation setCompletionBlock:^{\n"
11073                "  [self onOperationDone];\n"
11074                "}];");
11075   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
11076                "  [self onOperationDone];\n"
11077                "}]};");
11078   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
11079                "  f();\n"
11080                "}];");
11081   verifyFormat("int a = [operation block:^int(int *i) {\n"
11082                "  return 1;\n"
11083                "}];");
11084   verifyFormat("[myObject doSomethingWith:arg1\n"
11085                "                      aaa:^int(int *a) {\n"
11086                "                        return 1;\n"
11087                "                      }\n"
11088                "                      bbb:f(a * bbbbbbbb)];");
11089 
11090   verifyFormat("[operation setCompletionBlock:^{\n"
11091                "  [self.delegate newDataAvailable];\n"
11092                "}];",
11093                getLLVMStyleWithColumns(60));
11094   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
11095                "  NSString *path = [self sessionFilePath];\n"
11096                "  if (path) {\n"
11097                "    // ...\n"
11098                "  }\n"
11099                "});");
11100   verifyFormat("[[SessionService sharedService]\n"
11101                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
11102                "      if (window) {\n"
11103                "        [self windowDidLoad:window];\n"
11104                "      } else {\n"
11105                "        [self errorLoadingWindow];\n"
11106                "      }\n"
11107                "    }];");
11108   verifyFormat("void (^largeBlock)(void) = ^{\n"
11109                "  // ...\n"
11110                "};\n",
11111                getLLVMStyleWithColumns(40));
11112   verifyFormat("[[SessionService sharedService]\n"
11113                "    loadWindowWithCompletionBlock: //\n"
11114                "        ^(SessionWindow *window) {\n"
11115                "          if (window) {\n"
11116                "            [self windowDidLoad:window];\n"
11117                "          } else {\n"
11118                "            [self errorLoadingWindow];\n"
11119                "          }\n"
11120                "        }];",
11121                getLLVMStyleWithColumns(60));
11122   verifyFormat("[myObject doSomethingWith:arg1\n"
11123                "    firstBlock:^(Foo *a) {\n"
11124                "      // ...\n"
11125                "      int i;\n"
11126                "    }\n"
11127                "    secondBlock:^(Bar *b) {\n"
11128                "      // ...\n"
11129                "      int i;\n"
11130                "    }\n"
11131                "    thirdBlock:^Foo(Bar *b) {\n"
11132                "      // ...\n"
11133                "      int i;\n"
11134                "    }];");
11135   verifyFormat("[myObject doSomethingWith:arg1\n"
11136                "               firstBlock:-1\n"
11137                "              secondBlock:^(Bar *b) {\n"
11138                "                // ...\n"
11139                "                int i;\n"
11140                "              }];");
11141 
11142   verifyFormat("f(^{\n"
11143                "  @autoreleasepool {\n"
11144                "    if (a) {\n"
11145                "      g();\n"
11146                "    }\n"
11147                "  }\n"
11148                "});");
11149   verifyFormat("Block b = ^int *(A *a, B *b) {}");
11150 
11151   FormatStyle FourIndent = getLLVMStyle();
11152   FourIndent.ObjCBlockIndentWidth = 4;
11153   verifyFormat("[operation setCompletionBlock:^{\n"
11154                "    [self onOperationDone];\n"
11155                "}];",
11156                FourIndent);
11157 }
11158 
TEST_F(FormatTest,FormatsBlocksWithZeroColumnWidth)11159 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
11160   FormatStyle ZeroColumn = getLLVMStyle();
11161   ZeroColumn.ColumnLimit = 0;
11162 
11163   verifyFormat("[[SessionService sharedService] "
11164                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
11165                "  if (window) {\n"
11166                "    [self windowDidLoad:window];\n"
11167                "  } else {\n"
11168                "    [self errorLoadingWindow];\n"
11169                "  }\n"
11170                "}];",
11171                ZeroColumn);
11172   EXPECT_EQ("[[SessionService sharedService]\n"
11173             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
11174             "      if (window) {\n"
11175             "        [self windowDidLoad:window];\n"
11176             "      } else {\n"
11177             "        [self errorLoadingWindow];\n"
11178             "      }\n"
11179             "    }];",
11180             format("[[SessionService sharedService]\n"
11181                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
11182                    "                if (window) {\n"
11183                    "    [self windowDidLoad:window];\n"
11184                    "  } else {\n"
11185                    "    [self errorLoadingWindow];\n"
11186                    "  }\n"
11187                    "}];",
11188                    ZeroColumn));
11189   verifyFormat("[myObject doSomethingWith:arg1\n"
11190                "    firstBlock:^(Foo *a) {\n"
11191                "      // ...\n"
11192                "      int i;\n"
11193                "    }\n"
11194                "    secondBlock:^(Bar *b) {\n"
11195                "      // ...\n"
11196                "      int i;\n"
11197                "    }\n"
11198                "    thirdBlock:^Foo(Bar *b) {\n"
11199                "      // ...\n"
11200                "      int i;\n"
11201                "    }];",
11202                ZeroColumn);
11203   verifyFormat("f(^{\n"
11204                "  @autoreleasepool {\n"
11205                "    if (a) {\n"
11206                "      g();\n"
11207                "    }\n"
11208                "  }\n"
11209                "});",
11210                ZeroColumn);
11211   verifyFormat("void (^largeBlock)(void) = ^{\n"
11212                "  // ...\n"
11213                "};",
11214                ZeroColumn);
11215 
11216   ZeroColumn.AllowShortBlocksOnASingleLine = true;
11217   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
11218             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
11219   ZeroColumn.AllowShortBlocksOnASingleLine = false;
11220   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
11221             "  int i;\n"
11222             "};",
11223             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
11224 }
11225 
TEST_F(FormatTest,SupportsCRLF)11226 TEST_F(FormatTest, SupportsCRLF) {
11227   EXPECT_EQ("int a;\r\n"
11228             "int b;\r\n"
11229             "int c;\r\n",
11230             format("int a;\r\n"
11231                    "  int b;\r\n"
11232                    "    int c;\r\n",
11233                    getLLVMStyle()));
11234   EXPECT_EQ("int a;\r\n"
11235             "int b;\r\n"
11236             "int c;\r\n",
11237             format("int a;\r\n"
11238                    "  int b;\n"
11239                    "    int c;\r\n",
11240                    getLLVMStyle()));
11241   EXPECT_EQ("int a;\n"
11242             "int b;\n"
11243             "int c;\n",
11244             format("int a;\r\n"
11245                    "  int b;\n"
11246                    "    int c;\n",
11247                    getLLVMStyle()));
11248   EXPECT_EQ("\"aaaaaaa \"\r\n"
11249             "\"bbbbbbb\";\r\n",
11250             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
11251   EXPECT_EQ("#define A \\\r\n"
11252             "  b;      \\\r\n"
11253             "  c;      \\\r\n"
11254             "  d;\r\n",
11255             format("#define A \\\r\n"
11256                    "  b; \\\r\n"
11257                    "  c; d; \r\n",
11258                    getGoogleStyle()));
11259 
11260   EXPECT_EQ("/*\r\n"
11261             "multi line block comments\r\n"
11262             "should not introduce\r\n"
11263             "an extra carriage return\r\n"
11264             "*/\r\n",
11265             format("/*\r\n"
11266                    "multi line block comments\r\n"
11267                    "should not introduce\r\n"
11268                    "an extra carriage return\r\n"
11269                    "*/\r\n"));
11270 }
11271 
TEST_F(FormatTest,MunchSemicolonAfterBlocks)11272 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
11273   verifyFormat("MY_CLASS(C) {\n"
11274                "  int i;\n"
11275                "  int j;\n"
11276                "};");
11277 }
11278 
TEST_F(FormatTest,ConfigurableContinuationIndentWidth)11279 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
11280   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
11281   TwoIndent.ContinuationIndentWidth = 2;
11282 
11283   EXPECT_EQ("int i =\n"
11284             "  longFunction(\n"
11285             "    arg);",
11286             format("int i = longFunction(arg);", TwoIndent));
11287 
11288   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
11289   SixIndent.ContinuationIndentWidth = 6;
11290 
11291   EXPECT_EQ("int i =\n"
11292             "      longFunction(\n"
11293             "            arg);",
11294             format("int i = longFunction(arg);", SixIndent));
11295 }
11296 
TEST_F(FormatTest,SpacesInAngles)11297 TEST_F(FormatTest, SpacesInAngles) {
11298   FormatStyle Spaces = getLLVMStyle();
11299   Spaces.SpacesInAngles = true;
11300 
11301   verifyFormat("static_cast< int >(arg);", Spaces);
11302   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
11303   verifyFormat("f< int, float >();", Spaces);
11304   verifyFormat("template <> g() {}", Spaces);
11305   verifyFormat("template < std::vector< int > > f() {}", Spaces);
11306   verifyFormat("std::function< void(int, int) > fct;", Spaces);
11307   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
11308                Spaces);
11309 
11310   Spaces.Standard = FormatStyle::LS_Cpp03;
11311   Spaces.SpacesInAngles = true;
11312   verifyFormat("A< A< int > >();", Spaces);
11313 
11314   Spaces.SpacesInAngles = false;
11315   verifyFormat("A<A<int> >();", Spaces);
11316 
11317   Spaces.Standard = FormatStyle::LS_Cpp11;
11318   Spaces.SpacesInAngles = true;
11319   verifyFormat("A< A< int > >();", Spaces);
11320 
11321   Spaces.SpacesInAngles = false;
11322   verifyFormat("A<A<int>>();", Spaces);
11323 }
11324 
TEST_F(FormatTest,TripleAngleBrackets)11325 TEST_F(FormatTest, TripleAngleBrackets) {
11326   verifyFormat("f<<<1, 1>>>();");
11327   verifyFormat("f<<<1, 1, 1, s>>>();");
11328   verifyFormat("f<<<a, b, c, d>>>();");
11329   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
11330   verifyFormat("f<param><<<1, 1>>>();");
11331   verifyFormat("f<1><<<1, 1>>>();");
11332   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
11333   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
11334                "aaaaaaaaaaa<<<\n    1, 1>>>();");
11335 }
11336 
TEST_F(FormatTest,MergeLessLessAtEnd)11337 TEST_F(FormatTest, MergeLessLessAtEnd) {
11338   verifyFormat("<<");
11339   EXPECT_EQ("< < <", format("\\\n<<<"));
11340   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
11341                "aaallvm::outs() <<");
11342   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
11343                "aaaallvm::outs()\n    <<");
11344 }
11345 
TEST_F(FormatTest,HandleUnbalancedImplicitBracesAcrossPPBranches)11346 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
11347   std::string code = "#if A\n"
11348                      "#if B\n"
11349                      "a.\n"
11350                      "#endif\n"
11351                      "    a = 1;\n"
11352                      "#else\n"
11353                      "#endif\n"
11354                      "#if C\n"
11355                      "#else\n"
11356                      "#endif\n";
11357   EXPECT_EQ(code, format(code));
11358 }
11359 
TEST_F(FormatTest,HandleConflictMarkers)11360 TEST_F(FormatTest, HandleConflictMarkers) {
11361   // Git/SVN conflict markers.
11362   EXPECT_EQ("int a;\n"
11363             "void f() {\n"
11364             "  callme(some(parameter1,\n"
11365             "<<<<<<< text by the vcs\n"
11366             "              parameter2),\n"
11367             "||||||| text by the vcs\n"
11368             "              parameter2),\n"
11369             "         parameter3,\n"
11370             "======= text by the vcs\n"
11371             "              parameter2, parameter3),\n"
11372             ">>>>>>> text by the vcs\n"
11373             "         otherparameter);\n",
11374             format("int a;\n"
11375                    "void f() {\n"
11376                    "  callme(some(parameter1,\n"
11377                    "<<<<<<< text by the vcs\n"
11378                    "  parameter2),\n"
11379                    "||||||| text by the vcs\n"
11380                    "  parameter2),\n"
11381                    "  parameter3,\n"
11382                    "======= text by the vcs\n"
11383                    "  parameter2,\n"
11384                    "  parameter3),\n"
11385                    ">>>>>>> text by the vcs\n"
11386                    "  otherparameter);\n"));
11387 
11388   // Perforce markers.
11389   EXPECT_EQ("void f() {\n"
11390             "  function(\n"
11391             ">>>> text by the vcs\n"
11392             "      parameter,\n"
11393             "==== text by the vcs\n"
11394             "      parameter,\n"
11395             "==== text by the vcs\n"
11396             "      parameter,\n"
11397             "<<<< text by the vcs\n"
11398             "      parameter);\n",
11399             format("void f() {\n"
11400                    "  function(\n"
11401                    ">>>> text by the vcs\n"
11402                    "  parameter,\n"
11403                    "==== text by the vcs\n"
11404                    "  parameter,\n"
11405                    "==== text by the vcs\n"
11406                    "  parameter,\n"
11407                    "<<<< text by the vcs\n"
11408                    "  parameter);\n"));
11409 
11410   EXPECT_EQ("<<<<<<<\n"
11411             "|||||||\n"
11412             "=======\n"
11413             ">>>>>>>",
11414             format("<<<<<<<\n"
11415                    "|||||||\n"
11416                    "=======\n"
11417                    ">>>>>>>"));
11418 
11419   EXPECT_EQ("<<<<<<<\n"
11420             "|||||||\n"
11421             "int i;\n"
11422             "=======\n"
11423             ">>>>>>>",
11424             format("<<<<<<<\n"
11425                    "|||||||\n"
11426                    "int i;\n"
11427                    "=======\n"
11428                    ">>>>>>>"));
11429 
11430   // FIXME: Handle parsing of macros around conflict markers correctly:
11431   EXPECT_EQ("#define Macro \\\n"
11432             "<<<<<<<\n"
11433             "Something \\\n"
11434             "|||||||\n"
11435             "Else \\\n"
11436             "=======\n"
11437             "Other \\\n"
11438             ">>>>>>>\n"
11439             "    End int i;\n",
11440             format("#define Macro \\\n"
11441                    "<<<<<<<\n"
11442                    "  Something \\\n"
11443                    "|||||||\n"
11444                    "  Else \\\n"
11445                    "=======\n"
11446                    "  Other \\\n"
11447                    ">>>>>>>\n"
11448                    "  End\n"
11449                    "int i;\n"));
11450 }
11451 
TEST_F(FormatTest,DisableRegions)11452 TEST_F(FormatTest, DisableRegions) {
11453   EXPECT_EQ("int i;\n"
11454             "// clang-format off\n"
11455             "  int j;\n"
11456             "// clang-format on\n"
11457             "int k;",
11458             format(" int  i;\n"
11459                    "   // clang-format off\n"
11460                    "  int j;\n"
11461                    " // clang-format on\n"
11462                    "   int   k;"));
11463   EXPECT_EQ("int i;\n"
11464             "/* clang-format off */\n"
11465             "  int j;\n"
11466             "/* clang-format on */\n"
11467             "int k;",
11468             format(" int  i;\n"
11469                    "   /* clang-format off */\n"
11470                    "  int j;\n"
11471                    " /* clang-format on */\n"
11472                    "   int   k;"));
11473 }
11474 
TEST_F(FormatTest,DoNotCrashOnInvalidInput)11475 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
11476   format("? ) =");
11477   verifyNoCrash("#define a\\\n /**/}");
11478 }
11479 
TEST_F(FormatTest,FormatsTableGenCode)11480 TEST_F(FormatTest, FormatsTableGenCode) {
11481   FormatStyle Style = getLLVMStyle();
11482   Style.Language = FormatStyle::LK_TableGen;
11483   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
11484 }
11485 
11486 // Since this test case uses UNIX-style file path. We disable it for MS
11487 // compiler.
11488 #if !defined(_MSC_VER) && !defined(__MINGW32__)
11489 
TEST(FormatStyle,GetStyleOfFile)11490 TEST(FormatStyle, GetStyleOfFile) {
11491   vfs::InMemoryFileSystem FS;
11492   // Test 1: format file in the same directory.
11493   ASSERT_TRUE(
11494       FS.addFile("/a/.clang-format", 0,
11495                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
11496   ASSERT_TRUE(
11497       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
11498   auto Style1 = getStyle("file", "/a/.clang-format", "Google", &FS);
11499   ASSERT_EQ(Style1, getLLVMStyle());
11500 
11501   // Test 2: fallback to default.
11502   ASSERT_TRUE(
11503       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
11504   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", &FS);
11505   ASSERT_EQ(Style2, getMozillaStyle());
11506 
11507   // Test 3: format file in parent directory.
11508   ASSERT_TRUE(
11509       FS.addFile("/c/.clang-format", 0,
11510                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
11511   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
11512                          llvm::MemoryBuffer::getMemBuffer("int i;")));
11513   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", &FS);
11514   ASSERT_EQ(Style3, getGoogleStyle());
11515 }
11516 
11517 #endif // _MSC_VER
11518 
11519 class ReplacementTest : public ::testing::Test {
11520 protected:
createReplacement(SourceLocation Start,unsigned Length,llvm::StringRef ReplacementText)11521   tooling::Replacement createReplacement(SourceLocation Start, unsigned Length,
11522                                          llvm::StringRef ReplacementText) {
11523     return tooling::Replacement(Context.Sources, Start, Length,
11524                                 ReplacementText);
11525   }
11526 
11527   RewriterTestContext Context;
11528 };
11529 
TEST_F(ReplacementTest,FormatCodeAfterReplacements)11530 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
11531   // Column limit is 20.
11532   std::string Code = "Type *a =\n"
11533                      "    new Type();\n"
11534                      "g(iiiii, 0, jjjjj,\n"
11535                      "  0, kkkkk, 0, mm);\n"
11536                      "int  bad     = format   ;";
11537   std::string Expected = "auto a = new Type();\n"
11538                          "g(iiiii, nullptr,\n"
11539                          "  jjjjj, nullptr,\n"
11540                          "  kkkkk, nullptr,\n"
11541                          "  mm);\n"
11542                          "int  bad     = format   ;";
11543   FileID ID = Context.createInMemoryFile("format.cpp", Code);
11544   tooling::Replacements Replaces;
11545   Replaces.insert(tooling::Replacement(
11546       Context.Sources, Context.getLocation(ID, 1, 1), 6, "auto "));
11547   Replaces.insert(tooling::Replacement(
11548       Context.Sources, Context.getLocation(ID, 3, 10), 1, "nullptr"));
11549   Replaces.insert(tooling::Replacement(
11550       Context.Sources, Context.getLocation(ID, 4, 3), 1, "nullptr"));
11551   Replaces.insert(tooling::Replacement(
11552       Context.Sources, Context.getLocation(ID, 4, 13), 1, "nullptr"));
11553 
11554   format::FormatStyle Style = format::getLLVMStyle();
11555   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
11556   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
11557   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
11558       << llvm::toString(FormattedReplaces.takeError()) << "\n";
11559   auto Result = applyAllReplacements(Code, *FormattedReplaces);
11560   EXPECT_TRUE(static_cast<bool>(Result));
11561   EXPECT_EQ(Expected, *Result);
11562 }
11563 
TEST_F(ReplacementTest,SortIncludesAfterReplacement)11564 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
11565   std::string Code = "#include \"a.h\"\n"
11566                      "#include \"c.h\"\n"
11567                      "\n"
11568                      "int main() {\n"
11569                      "  return 0;\n"
11570                      "}";
11571   std::string Expected = "#include \"a.h\"\n"
11572                          "#include \"b.h\"\n"
11573                          "#include \"c.h\"\n"
11574                          "\n"
11575                          "int main() {\n"
11576                          "  return 0;\n"
11577                          "}";
11578   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
11579   tooling::Replacements Replaces;
11580   Replaces.insert(tooling::Replacement(
11581       Context.Sources, Context.getLocation(ID, 1, 1), 0, "#include \"b.h\"\n"));
11582 
11583   format::FormatStyle Style = format::getLLVMStyle();
11584   Style.SortIncludes = true;
11585   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
11586   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
11587       << llvm::toString(FormattedReplaces.takeError()) << "\n";
11588   auto Result = applyAllReplacements(Code, *FormattedReplaces);
11589   EXPECT_TRUE(static_cast<bool>(Result));
11590   EXPECT_EQ(Expected, *Result);
11591 }
11592 
11593 } // end namespace
11594 } // end namespace format
11595 } // end namespace clang
11596