xref: /minix3/external/bsd/llvm/dist/clang/unittests/Format/FormatTest.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
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 "FormatTestUtils.h"
11 #include "clang/Format/Format.h"
12 #include "llvm/Support/Debug.h"
13 #include "gtest/gtest.h"
14 
15 #define DEBUG_TYPE "format-test"
16 
17 namespace clang {
18 namespace format {
19 
getGoogleStyle()20 FormatStyle getGoogleStyle() {
21   return getGoogleStyle(FormatStyle::LK_Cpp);
22 }
23 
24 class FormatTest : public ::testing::Test {
25 protected:
format(llvm::StringRef Code,unsigned Offset,unsigned Length,const FormatStyle & Style)26   std::string format(llvm::StringRef Code, unsigned Offset, unsigned Length,
27                      const FormatStyle &Style) {
28     DEBUG(llvm::errs() << "---\n");
29     DEBUG(llvm::errs() << Code << "\n\n");
30     std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length));
31     tooling::Replacements Replaces = reformat(Style, Code, Ranges);
32     ReplacementCount = Replaces.size();
33     std::string Result = applyAllReplacements(Code, Replaces);
34     EXPECT_NE("", Result);
35     DEBUG(llvm::errs() << "\n" << Result << "\n\n");
36     return Result;
37   }
38 
39   std::string
format(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())40   format(llvm::StringRef Code, const FormatStyle &Style = getLLVMStyle()) {
41     return format(Code, 0, Code.size(), Style);
42   }
43 
getLLVMStyleWithColumns(unsigned ColumnLimit)44   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
45     FormatStyle Style = getLLVMStyle();
46     Style.ColumnLimit = ColumnLimit;
47     return Style;
48   }
49 
getGoogleStyleWithColumns(unsigned ColumnLimit)50   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
51     FormatStyle Style = getGoogleStyle();
52     Style.ColumnLimit = ColumnLimit;
53     return Style;
54   }
55 
verifyFormat(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())56   void verifyFormat(llvm::StringRef Code,
57                     const FormatStyle &Style = getLLVMStyle()) {
58     EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
59   }
60 
verifyGoogleFormat(llvm::StringRef Code)61   void verifyGoogleFormat(llvm::StringRef Code) {
62     verifyFormat(Code, getGoogleStyle());
63   }
64 
verifyIndependentOfContext(llvm::StringRef text)65   void verifyIndependentOfContext(llvm::StringRef text) {
66     verifyFormat(text);
67     verifyFormat(llvm::Twine("void f() { " + text + " }").str());
68   }
69 
70   int ReplacementCount;
71 };
72 
TEST_F(FormatTest,MessUp)73 TEST_F(FormatTest, MessUp) {
74   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
75   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
76   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
77   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
78   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
79 }
80 
81 //===----------------------------------------------------------------------===//
82 // Basic function tests.
83 //===----------------------------------------------------------------------===//
84 
TEST_F(FormatTest,DoesNotChangeCorrectlyFormattedCode)85 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
86   EXPECT_EQ(";", format(";"));
87 }
88 
TEST_F(FormatTest,FormatsGlobalStatementsAt0)89 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
90   EXPECT_EQ("int i;", format("  int i;"));
91   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
92   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
93   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
94 }
95 
TEST_F(FormatTest,FormatsUnwrappedLinesAtFirstFormat)96 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
97   EXPECT_EQ("int i;", format("int\ni;"));
98 }
99 
TEST_F(FormatTest,FormatsNestedBlockStatements)100 TEST_F(FormatTest, FormatsNestedBlockStatements) {
101   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
102 }
103 
TEST_F(FormatTest,FormatsNestedCall)104 TEST_F(FormatTest, FormatsNestedCall) {
105   verifyFormat("Method(f1, f2(f3));");
106   verifyFormat("Method(f1(f2, f3()));");
107   verifyFormat("Method(f1(f2, (f3())));");
108 }
109 
TEST_F(FormatTest,NestedNameSpecifiers)110 TEST_F(FormatTest, NestedNameSpecifiers) {
111   verifyFormat("vector<::Type> v;");
112   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
113   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
114   verifyFormat("bool a = 2 < ::SomeFunction();");
115 }
116 
TEST_F(FormatTest,OnlyGeneratesNecessaryReplacements)117 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
118   EXPECT_EQ("if (a) {\n"
119             "  f();\n"
120             "}",
121             format("if(a){f();}"));
122   EXPECT_EQ(4, ReplacementCount);
123   EXPECT_EQ("if (a) {\n"
124             "  f();\n"
125             "}",
126             format("if (a) {\n"
127                    "  f();\n"
128                    "}"));
129   EXPECT_EQ(0, ReplacementCount);
130 }
131 
TEST_F(FormatTest,RemovesTrailingWhitespaceOfFormattedLine)132 TEST_F(FormatTest, RemovesTrailingWhitespaceOfFormattedLine) {
133   EXPECT_EQ("int a;\nint b;", format("int a; \nint b;", 0, 0, getLLVMStyle()));
134   EXPECT_EQ("int a;", format("int a;         "));
135   EXPECT_EQ("int a;\n", format("int a;  \n   \n   \n "));
136   EXPECT_EQ("int a;\nint b;    ",
137             format("int a;  \nint b;    ", 0, 0, getLLVMStyle()));
138 }
139 
TEST_F(FormatTest,FormatsCorrectRegionForLeadingWhitespace)140 TEST_F(FormatTest, FormatsCorrectRegionForLeadingWhitespace) {
141   EXPECT_EQ("int b;\nint a;",
142             format("int b;\n   int a;", 7, 0, getLLVMStyle()));
143   EXPECT_EQ("int b;\n   int a;",
144             format("int b;\n   int a;", 6, 0, getLLVMStyle()));
145 
146   EXPECT_EQ("#define A  \\\n"
147             "  int a;   \\\n"
148             "  int b;",
149             format("#define A  \\\n"
150                    "  int a;   \\\n"
151                    "    int b;",
152                    26, 0, getLLVMStyleWithColumns(12)));
153   EXPECT_EQ("#define A  \\\n"
154             "  int a;   \\\n"
155             "  int b;",
156             format("#define A  \\\n"
157                    "  int a;   \\\n"
158                    "  int b;",
159                    25, 0, getLLVMStyleWithColumns(12)));
160 }
161 
TEST_F(FormatTest,FormatLineWhenInvokedOnTrailingNewline)162 TEST_F(FormatTest, FormatLineWhenInvokedOnTrailingNewline) {
163   EXPECT_EQ("int  b;\n\nint a;",
164             format("int  b;\n\nint a;", 8, 0, getLLVMStyle()));
165   EXPECT_EQ("int b;\n\nint a;",
166             format("int  b;\n\nint a;", 7, 0, getLLVMStyle()));
167 
168   // This might not strictly be correct, but is likely good in all practical
169   // cases.
170   EXPECT_EQ("int b;\nint a;",
171             format("int  b;int a;", 7, 0, getLLVMStyle()));
172 }
173 
TEST_F(FormatTest,RemovesWhitespaceWhenTriggeredOnEmptyLine)174 TEST_F(FormatTest, RemovesWhitespaceWhenTriggeredOnEmptyLine) {
175   EXPECT_EQ("int  a;\n\n int b;",
176             format("int  a;\n  \n\n int b;", 8, 0, getLLVMStyle()));
177   EXPECT_EQ("int  a;\n\n int b;",
178             format("int  a;\n  \n\n int b;", 9, 0, getLLVMStyle()));
179 }
180 
TEST_F(FormatTest,RemovesEmptyLines)181 TEST_F(FormatTest, RemovesEmptyLines) {
182   EXPECT_EQ("class C {\n"
183             "  int i;\n"
184             "};",
185             format("class C {\n"
186                    " int i;\n"
187                    "\n"
188                    "};"));
189 
190   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
191   EXPECT_EQ("namespace N {\n"
192             "\n"
193             "int i;\n"
194             "}",
195             format("namespace N {\n"
196                    "\n"
197                    "int    i;\n"
198                    "}",
199                    getGoogleStyle()));
200   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
201             "\n"
202             "int i;\n"
203             "}",
204             format("extern /**/ \"C\" /**/ {\n"
205                    "\n"
206                    "int    i;\n"
207                    "}",
208                    getGoogleStyle()));
209 
210   // ...but do keep inlining and removing empty lines for non-block extern "C"
211   // functions.
212   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
213   EXPECT_EQ("extern \"C\" int f() {\n"
214             "  int i = 42;\n"
215             "  return i;\n"
216             "}",
217             format("extern \"C\" int f() {\n"
218                    "\n"
219                    "  int i = 42;\n"
220                    "  return i;\n"
221                    "}",
222                    getGoogleStyle()));
223 
224   // Remove empty lines at the beginning and end of blocks.
225   EXPECT_EQ("void f() {\n"
226             "\n"
227             "  if (a) {\n"
228             "\n"
229             "    f();\n"
230             "  }\n"
231             "}",
232             format("void f() {\n"
233                    "\n"
234                    "  if (a) {\n"
235                    "\n"
236                    "    f();\n"
237                    "\n"
238                    "  }\n"
239                    "\n"
240                    "}",
241                    getLLVMStyle()));
242   EXPECT_EQ("void f() {\n"
243             "  if (a) {\n"
244             "    f();\n"
245             "  }\n"
246             "}",
247             format("void f() {\n"
248                    "\n"
249                    "  if (a) {\n"
250                    "\n"
251                    "    f();\n"
252                    "\n"
253                    "  }\n"
254                    "\n"
255                    "}",
256                    getGoogleStyle()));
257 
258   // Don't remove empty lines in more complex control statements.
259   EXPECT_EQ("void f() {\n"
260             "  if (a) {\n"
261             "    f();\n"
262             "\n"
263             "  } else if (b) {\n"
264             "    f();\n"
265             "  }\n"
266             "}",
267             format("void f() {\n"
268                    "  if (a) {\n"
269                    "    f();\n"
270                    "\n"
271                    "  } else if (b) {\n"
272                    "    f();\n"
273                    "\n"
274                    "  }\n"
275                    "\n"
276                    "}"));
277 
278   // FIXME: This is slightly inconsistent.
279   EXPECT_EQ("namespace {\n"
280             "int i;\n"
281             "}",
282             format("namespace {\n"
283                    "int i;\n"
284                    "\n"
285                    "}"));
286   EXPECT_EQ("namespace {\n"
287             "int i;\n"
288             "\n"
289             "} // namespace",
290             format("namespace {\n"
291                    "int i;\n"
292                    "\n"
293                    "}  // namespace"));
294 }
295 
TEST_F(FormatTest,ReformatsMovedLines)296 TEST_F(FormatTest, ReformatsMovedLines) {
297   EXPECT_EQ(
298       "template <typename T> T *getFETokenInfo() const {\n"
299       "  return static_cast<T *>(FETokenInfo);\n"
300       "}\n"
301       "  int a; // <- Should not be formatted",
302       format(
303           "template<typename T>\n"
304           "T *getFETokenInfo() const { return static_cast<T*>(FETokenInfo); }\n"
305           "  int a; // <- Should not be formatted",
306           9, 5, getLLVMStyle()));
307 }
308 
TEST_F(FormatTest,RecognizesBinaryOperatorKeywords)309 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
310     verifyFormat("x = (a) and (b);");
311     verifyFormat("x = (a) or (b);");
312     verifyFormat("x = (a) bitand (b);");
313     verifyFormat("x = (a) bitor (b);");
314     verifyFormat("x = (a) not_eq (b);");
315     verifyFormat("x = (a) and_eq (b);");
316     verifyFormat("x = (a) or_eq (b);");
317     verifyFormat("x = (a) xor (b);");
318 }
319 
320 //===----------------------------------------------------------------------===//
321 // Tests for control statements.
322 //===----------------------------------------------------------------------===//
323 
TEST_F(FormatTest,FormatIfWithoutCompoundStatement)324 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
325   verifyFormat("if (true)\n  f();\ng();");
326   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
327   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
328 
329   FormatStyle AllowsMergedIf = getLLVMStyle();
330   AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
331   verifyFormat("if (a)\n"
332                "  // comment\n"
333                "  f();",
334                AllowsMergedIf);
335   verifyFormat("if (a)\n"
336                "  ;",
337                AllowsMergedIf);
338   verifyFormat("if (a)\n"
339                "  if (b) return;",
340                AllowsMergedIf);
341 
342   verifyFormat("if (a) // Can't merge this\n"
343                "  f();\n",
344                AllowsMergedIf);
345   verifyFormat("if (a) /* still don't merge */\n"
346                "  f();",
347                AllowsMergedIf);
348   verifyFormat("if (a) { // Never merge this\n"
349                "  f();\n"
350                "}",
351                AllowsMergedIf);
352   verifyFormat("if (a) {/* Never merge this */\n"
353                "  f();\n"
354                "}",
355                AllowsMergedIf);
356 
357   EXPECT_EQ("if (a) return;", format("if(a)\nreturn;", 7, 1, AllowsMergedIf));
358   EXPECT_EQ("if (a) return; // comment",
359             format("if(a)\nreturn; // comment", 20, 1, AllowsMergedIf));
360 
361   AllowsMergedIf.ColumnLimit = 14;
362   verifyFormat("if (a) return;", AllowsMergedIf);
363   verifyFormat("if (aaaaaaaaa)\n"
364                "  return;",
365                AllowsMergedIf);
366 
367   AllowsMergedIf.ColumnLimit = 13;
368   verifyFormat("if (a)\n  return;", AllowsMergedIf);
369 }
370 
TEST_F(FormatTest,FormatLoopsWithoutCompoundStatement)371 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
372   FormatStyle AllowsMergedLoops = getLLVMStyle();
373   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
374   verifyFormat("while (true) continue;", AllowsMergedLoops);
375   verifyFormat("for (;;) continue;", AllowsMergedLoops);
376   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
377   verifyFormat("while (true)\n"
378                "  ;",
379                AllowsMergedLoops);
380   verifyFormat("for (;;)\n"
381                "  ;",
382                AllowsMergedLoops);
383   verifyFormat("for (;;)\n"
384                "  for (;;) continue;",
385                AllowsMergedLoops);
386   verifyFormat("for (;;) // Can't merge this\n"
387                "  continue;",
388                AllowsMergedLoops);
389   verifyFormat("for (;;) /* still don't merge */\n"
390                "  continue;",
391                AllowsMergedLoops);
392 }
393 
TEST_F(FormatTest,FormatShortBracedStatements)394 TEST_F(FormatTest, FormatShortBracedStatements) {
395   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
396   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = true;
397 
398   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = true;
399   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
400 
401   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
402   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
403   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
404   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
405   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
406   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
407   verifyFormat("if (true) { //\n"
408                "  f();\n"
409                "}",
410                AllowSimpleBracedStatements);
411   verifyFormat("if (true) {\n"
412                "  f();\n"
413                "  f();\n"
414                "}",
415                AllowSimpleBracedStatements);
416 
417   verifyFormat("template <int> struct A2 {\n"
418                "  struct B {};\n"
419                "};",
420                AllowSimpleBracedStatements);
421 
422   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = false;
423   verifyFormat("if (true) {\n"
424                "  f();\n"
425                "}",
426                AllowSimpleBracedStatements);
427 
428   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
429   verifyFormat("while (true) {\n"
430                "  f();\n"
431                "}",
432                AllowSimpleBracedStatements);
433   verifyFormat("for (;;) {\n"
434                "  f();\n"
435                "}",
436                AllowSimpleBracedStatements);
437 }
438 
TEST_F(FormatTest,ParseIfElse)439 TEST_F(FormatTest, ParseIfElse) {
440   verifyFormat("if (true)\n"
441                "  if (true)\n"
442                "    if (true)\n"
443                "      f();\n"
444                "    else\n"
445                "      g();\n"
446                "  else\n"
447                "    h();\n"
448                "else\n"
449                "  i();");
450   verifyFormat("if (true)\n"
451                "  if (true)\n"
452                "    if (true) {\n"
453                "      if (true)\n"
454                "        f();\n"
455                "    } else {\n"
456                "      g();\n"
457                "    }\n"
458                "  else\n"
459                "    h();\n"
460                "else {\n"
461                "  i();\n"
462                "}");
463   verifyFormat("void f() {\n"
464                "  if (a) {\n"
465                "  } else {\n"
466                "  }\n"
467                "}");
468 }
469 
TEST_F(FormatTest,ElseIf)470 TEST_F(FormatTest, ElseIf) {
471   verifyFormat("if (a) {\n} else if (b) {\n}");
472   verifyFormat("if (a)\n"
473                "  f();\n"
474                "else if (b)\n"
475                "  g();\n"
476                "else\n"
477                "  h();");
478   verifyFormat("if (a) {\n"
479                "  f();\n"
480                "}\n"
481                "// or else ..\n"
482                "else {\n"
483                "  g()\n"
484                "}");
485 
486   verifyFormat("if (a) {\n"
487                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
488                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
489                "}");
490 }
491 
TEST_F(FormatTest,FormatsForLoop)492 TEST_F(FormatTest, FormatsForLoop) {
493   verifyFormat(
494       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
495       "     ++VeryVeryLongLoopVariable)\n"
496       "  ;");
497   verifyFormat("for (;;)\n"
498                "  f();");
499   verifyFormat("for (;;) {\n}");
500   verifyFormat("for (;;) {\n"
501                "  f();\n"
502                "}");
503   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
504 
505   verifyFormat(
506       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
507       "                                          E = UnwrappedLines.end();\n"
508       "     I != E; ++I) {\n}");
509 
510   verifyFormat(
511       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
512       "     ++IIIII) {\n}");
513   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
514                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
515                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
516   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
517                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
518                "         E = FD->getDeclsInPrototypeScope().end();\n"
519                "     I != E; ++I) {\n}");
520 
521   // FIXME: Not sure whether we want extra identation in line 3 here:
522   verifyFormat(
523       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
524       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
525       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
526       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
527       "     ++aaaaaaaaaaa) {\n}");
528   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
529                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
530                "}");
531   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
532                "         aaaaaaaaaa);\n"
533                "     iter; ++iter) {\n"
534                "}");
535 
536   FormatStyle NoBinPacking = getLLVMStyle();
537   NoBinPacking.BinPackParameters = false;
538   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
539                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
540                "                                           aaaaaaaaaaaaaaaa,\n"
541                "                                           aaaaaaaaaaaaaaaa,\n"
542                "                                           aaaaaaaaaaaaaaaa);\n"
543                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
544                "}",
545                NoBinPacking);
546   verifyFormat(
547       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
548       "                                          E = UnwrappedLines.end();\n"
549       "     I != E;\n"
550       "     ++I) {\n}",
551       NoBinPacking);
552 }
553 
TEST_F(FormatTest,RangeBasedForLoops)554 TEST_F(FormatTest, RangeBasedForLoops) {
555   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
556                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
557   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
558                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
559   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
560                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
561   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
562                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
563 }
564 
TEST_F(FormatTest,ForEachLoops)565 TEST_F(FormatTest, ForEachLoops) {
566   verifyFormat("void f() {\n"
567                "  foreach (Item *item, itemlist) {}\n"
568                "  Q_FOREACH (Item *item, itemlist) {}\n"
569                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
570                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
571                "}");
572 }
573 
TEST_F(FormatTest,FormatsWhileLoop)574 TEST_F(FormatTest, FormatsWhileLoop) {
575   verifyFormat("while (true) {\n}");
576   verifyFormat("while (true)\n"
577                "  f();");
578   verifyFormat("while () {\n}");
579   verifyFormat("while () {\n"
580                "  f();\n"
581                "}");
582 }
583 
TEST_F(FormatTest,FormatsDoWhile)584 TEST_F(FormatTest, FormatsDoWhile) {
585   verifyFormat("do {\n"
586                "  do_something();\n"
587                "} while (something());");
588   verifyFormat("do\n"
589                "  do_something();\n"
590                "while (something());");
591 }
592 
TEST_F(FormatTest,FormatsSwitchStatement)593 TEST_F(FormatTest, FormatsSwitchStatement) {
594   verifyFormat("switch (x) {\n"
595                "case 1:\n"
596                "  f();\n"
597                "  break;\n"
598                "case kFoo:\n"
599                "case ns::kBar:\n"
600                "case kBaz:\n"
601                "  break;\n"
602                "default:\n"
603                "  g();\n"
604                "  break;\n"
605                "}");
606   verifyFormat("switch (x) {\n"
607                "case 1: {\n"
608                "  f();\n"
609                "  break;\n"
610                "}\n"
611                "case 2: {\n"
612                "  break;\n"
613                "}\n"
614                "}");
615   verifyFormat("switch (x) {\n"
616                "case 1: {\n"
617                "  f();\n"
618                "  {\n"
619                "    g();\n"
620                "    h();\n"
621                "  }\n"
622                "  break;\n"
623                "}\n"
624                "}");
625   verifyFormat("switch (x) {\n"
626                "case 1: {\n"
627                "  f();\n"
628                "  if (foo) {\n"
629                "    g();\n"
630                "    h();\n"
631                "  }\n"
632                "  break;\n"
633                "}\n"
634                "}");
635   verifyFormat("switch (x) {\n"
636                "case 1: {\n"
637                "  f();\n"
638                "  g();\n"
639                "} break;\n"
640                "}");
641   verifyFormat("switch (test)\n"
642                "  ;");
643   verifyFormat("switch (x) {\n"
644                "default: {\n"
645                "  // Do nothing.\n"
646                "}\n"
647                "}");
648   verifyFormat("switch (x) {\n"
649                "// comment\n"
650                "// if 1, do f()\n"
651                "case 1:\n"
652                "  f();\n"
653                "}");
654   verifyFormat("switch (x) {\n"
655                "case 1:\n"
656                "  // Do amazing stuff\n"
657                "  {\n"
658                "    f();\n"
659                "    g();\n"
660                "  }\n"
661                "  break;\n"
662                "}");
663   verifyFormat("#define A          \\\n"
664                "  switch (x) {     \\\n"
665                "  case a:          \\\n"
666                "    foo = b;       \\\n"
667                "  }", getLLVMStyleWithColumns(20));
668   verifyFormat("#define OPERATION_CASE(name)           \\\n"
669                "  case OP_name:                        \\\n"
670                "    return operations::Operation##name\n",
671                getLLVMStyleWithColumns(40));
672 
673   verifyGoogleFormat("switch (x) {\n"
674                      "  case 1:\n"
675                      "    f();\n"
676                      "    break;\n"
677                      "  case kFoo:\n"
678                      "  case ns::kBar:\n"
679                      "  case kBaz:\n"
680                      "    break;\n"
681                      "  default:\n"
682                      "    g();\n"
683                      "    break;\n"
684                      "}");
685   verifyGoogleFormat("switch (x) {\n"
686                      "  case 1: {\n"
687                      "    f();\n"
688                      "    break;\n"
689                      "  }\n"
690                      "}");
691   verifyGoogleFormat("switch (test)\n"
692                      "  ;");
693 
694   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
695                      "  case OP_name:              \\\n"
696                      "    return operations::Operation##name\n");
697   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
698                      "  // Get the correction operation class.\n"
699                      "  switch (OpCode) {\n"
700                      "    CASE(Add);\n"
701                      "    CASE(Subtract);\n"
702                      "    default:\n"
703                      "      return operations::Unknown;\n"
704                      "  }\n"
705                      "#undef OPERATION_CASE\n"
706                      "}");
707   verifyFormat("DEBUG({\n"
708                "  switch (x) {\n"
709                "  case A:\n"
710                "    f();\n"
711                "    break;\n"
712                "  // On B:\n"
713                "  case B:\n"
714                "    g();\n"
715                "    break;\n"
716                "  }\n"
717                "});");
718   verifyFormat("switch (a) {\n"
719                "case (b):\n"
720                "  return;\n"
721                "}");
722 
723   verifyFormat("switch (a) {\n"
724                "case some_namespace::\n"
725                "    some_constant:\n"
726                "  return;\n"
727                "}",
728                getLLVMStyleWithColumns(34));
729 }
730 
TEST_F(FormatTest,CaseRanges)731 TEST_F(FormatTest, CaseRanges) {
732   verifyFormat("switch (x) {\n"
733                "case 'A' ... 'Z':\n"
734                "case 1 ... 5:\n"
735                "  break;\n"
736                "}");
737 }
738 
TEST_F(FormatTest,ShortCaseLabels)739 TEST_F(FormatTest, ShortCaseLabels) {
740   FormatStyle Style = getLLVMStyle();
741   Style.AllowShortCaseLabelsOnASingleLine = true;
742   verifyFormat("switch (a) {\n"
743                "case 1: x = 1; break;\n"
744                "case 2: return;\n"
745                "case 3:\n"
746                "case 4:\n"
747                "case 5: return;\n"
748                "case 6: // comment\n"
749                "  return;\n"
750                "case 7:\n"
751                "  // comment\n"
752                "  return;\n"
753                "default: y = 1; break;\n"
754                "}",
755                Style);
756   verifyFormat("switch (a) {\n"
757                "#if FOO\n"
758                "case 0: return 0;\n"
759                "#endif\n"
760                "}",
761                Style);
762   verifyFormat("switch (a) {\n"
763                "case 1: {\n"
764                "}\n"
765                "case 2: {\n"
766                "  return;\n"
767                "}\n"
768                "case 3: {\n"
769                "  x = 1;\n"
770                "  return;\n"
771                "}\n"
772                "case 4:\n"
773                "  if (x)\n"
774                "    return;\n"
775                "}",
776                Style);
777   Style.ColumnLimit = 21;
778   verifyFormat("switch (a) {\n"
779                "case 1: x = 1; break;\n"
780                "case 2: return;\n"
781                "case 3:\n"
782                "case 4:\n"
783                "case 5: return;\n"
784                "default:\n"
785                "  y = 1;\n"
786                "  break;\n"
787                "}",
788                Style);
789 }
790 
TEST_F(FormatTest,FormatsLabels)791 TEST_F(FormatTest, FormatsLabels) {
792   verifyFormat("void f() {\n"
793                "  some_code();\n"
794                "test_label:\n"
795                "  some_other_code();\n"
796                "  {\n"
797                "    some_more_code();\n"
798                "  another_label:\n"
799                "    some_more_code();\n"
800                "  }\n"
801                "}");
802   verifyFormat("some_code();\n"
803                "test_label:\n"
804                "some_other_code();");
805 }
806 
807 //===----------------------------------------------------------------------===//
808 // Tests for comments.
809 //===----------------------------------------------------------------------===//
810 
TEST_F(FormatTest,UnderstandsSingleLineComments)811 TEST_F(FormatTest, UnderstandsSingleLineComments) {
812   verifyFormat("//* */");
813   verifyFormat("// line 1\n"
814                "// line 2\n"
815                "void f() {}\n");
816 
817   verifyFormat("void f() {\n"
818                "  // Doesn't do anything\n"
819                "}");
820   verifyFormat("SomeObject\n"
821                "    // Calling someFunction on SomeObject\n"
822                "    .someFunction();");
823   verifyFormat("auto result = SomeObject\n"
824                "                  // Calling someFunction on SomeObject\n"
825                "                  .someFunction();");
826   verifyFormat("void f(int i,  // some comment (probably for i)\n"
827                "       int j,  // some comment (probably for j)\n"
828                "       int k); // some comment (probably for k)");
829   verifyFormat("void f(int i,\n"
830                "       // some comment (probably for j)\n"
831                "       int j,\n"
832                "       // some comment (probably for k)\n"
833                "       int k);");
834 
835   verifyFormat("int i    // This is a fancy variable\n"
836                "    = 5; // with nicely aligned comment.");
837 
838   verifyFormat("// Leading comment.\n"
839                "int a; // Trailing comment.");
840   verifyFormat("int a; // Trailing comment\n"
841                "       // on 2\n"
842                "       // or 3 lines.\n"
843                "int b;");
844   verifyFormat("int a; // Trailing comment\n"
845                "\n"
846                "// Leading comment.\n"
847                "int b;");
848   verifyFormat("int a;    // Comment.\n"
849                "          // More details.\n"
850                "int bbbb; // Another comment.");
851   verifyFormat(
852       "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
853       "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   // comment\n"
854       "int cccccccccccccccccccccccccccccc;       // comment\n"
855       "int ddd;                     // looooooooooooooooooooooooong comment\n"
856       "int aaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
857       "int bbbbbbbbbbbbbbbbbbbbb;   // comment\n"
858       "int ccccccccccccccccccc;     // comment");
859 
860   verifyFormat("#include \"a\"     // comment\n"
861                "#include \"a/b/c\" // comment");
862   verifyFormat("#include <a>     // comment\n"
863                "#include <a/b/c> // comment");
864   EXPECT_EQ("#include \"a\"     // comment\n"
865             "#include \"a/b/c\" // comment",
866             format("#include \\\n"
867                    "  \"a\" // comment\n"
868                    "#include \"a/b/c\" // comment"));
869 
870   verifyFormat("enum E {\n"
871                "  // comment\n"
872                "  VAL_A, // comment\n"
873                "  VAL_B\n"
874                "};");
875 
876   verifyFormat(
877       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
878       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // Trailing comment");
879   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
880                "    // Comment inside a statement.\n"
881                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
882   verifyFormat("SomeFunction(a,\n"
883                "             // comment\n"
884                "             b + x);");
885   verifyFormat("SomeFunction(a, a,\n"
886                "             // comment\n"
887                "             b + x);");
888   verifyFormat(
889       "bool aaaaaaaaaaaaa = // comment\n"
890       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
891       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
892 
893   verifyFormat("int aaaa; // aaaaa\n"
894                "int aa;   // aaaaaaa",
895                getLLVMStyleWithColumns(20));
896 
897   EXPECT_EQ("void f() { // This does something ..\n"
898             "}\n"
899             "int a; // This is unrelated",
900             format("void f()    {     // This does something ..\n"
901                    "  }\n"
902                    "int   a;     // This is unrelated"));
903   EXPECT_EQ("class C {\n"
904             "  void f() { // This does something ..\n"
905             "  }          // awesome..\n"
906             "\n"
907             "  int a; // This is unrelated\n"
908             "};",
909             format("class C{void f()    { // This does something ..\n"
910                    "      } // awesome..\n"
911                    " \n"
912                    "int a;    // This is unrelated\n"
913                    "};"));
914 
915   EXPECT_EQ("int i; // single line trailing comment",
916             format("int i;\\\n// single line trailing comment"));
917 
918   verifyGoogleFormat("int a;  // Trailing comment.");
919 
920   verifyFormat("someFunction(anotherFunction( // Force break.\n"
921                "    parameter));");
922 
923   verifyGoogleFormat("#endif  // HEADER_GUARD");
924 
925   verifyFormat("const char *test[] = {\n"
926                "    // A\n"
927                "    \"aaaa\",\n"
928                "    // B\n"
929                "    \"aaaaa\"};");
930   verifyGoogleFormat(
931       "aaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
932       "    aaaaaaaaaaaaaaaaaaaaaa);  // 81_cols_with_this_comment");
933   EXPECT_EQ("D(a, {\n"
934             "  // test\n"
935             "  int a;\n"
936             "});",
937             format("D(a, {\n"
938                    "// test\n"
939                    "int a;\n"
940                    "});"));
941 
942   EXPECT_EQ("lineWith(); // comment\n"
943             "// at start\n"
944             "otherLine();",
945             format("lineWith();   // comment\n"
946                    "// at start\n"
947                    "otherLine();"));
948   EXPECT_EQ("lineWith(); // comment\n"
949             "            // at start\n"
950             "otherLine();",
951             format("lineWith();   // comment\n"
952                    " // at start\n"
953                    "otherLine();"));
954 
955   EXPECT_EQ("lineWith(); // comment\n"
956             "// at start\n"
957             "otherLine(); // comment",
958             format("lineWith();   // comment\n"
959                    "// at start\n"
960                    "otherLine();   // comment"));
961   EXPECT_EQ("lineWith();\n"
962             "// at start\n"
963             "otherLine(); // comment",
964             format("lineWith();\n"
965                    " // at start\n"
966                    "otherLine();   // comment"));
967   EXPECT_EQ("// first\n"
968             "// at start\n"
969             "otherLine(); // comment",
970             format("// first\n"
971                    " // at start\n"
972                    "otherLine();   // comment"));
973   EXPECT_EQ("f();\n"
974             "// first\n"
975             "// at start\n"
976             "otherLine(); // comment",
977             format("f();\n"
978                    "// first\n"
979                    " // at start\n"
980                    "otherLine();   // comment"));
981   verifyFormat("f(); // comment\n"
982                "// first\n"
983                "// at start\n"
984                "otherLine();");
985   EXPECT_EQ("f(); // comment\n"
986             "// first\n"
987             "// at start\n"
988             "otherLine();",
989             format("f();   // comment\n"
990                    "// first\n"
991                    " // at start\n"
992                    "otherLine();"));
993   EXPECT_EQ("f(); // comment\n"
994             "     // first\n"
995             "// at start\n"
996             "otherLine();",
997             format("f();   // comment\n"
998                    " // first\n"
999                    "// at start\n"
1000                    "otherLine();"));
1001   EXPECT_EQ("void f() {\n"
1002             "  lineWith(); // comment\n"
1003             "  // at start\n"
1004             "}",
1005             format("void              f() {\n"
1006                    "  lineWith(); // comment\n"
1007                    "  // at start\n"
1008                    "}"));
1009 
1010   verifyFormat(
1011       "#define A                                                  \\\n"
1012       "  int i; /* iiiiiiiiiiiiiiiiiiiii */                       \\\n"
1013       "  int jjjjjjjjjjjjjjjjjjjjjjjj; /* */",
1014       getLLVMStyleWithColumns(60));
1015   verifyFormat(
1016       "#define A                                                   \\\n"
1017       "  int i;                        /* iiiiiiiiiiiiiiiiiiiii */ \\\n"
1018       "  int jjjjjjjjjjjjjjjjjjjjjjjj; /* */",
1019       getLLVMStyleWithColumns(61));
1020 
1021   verifyFormat("if ( // This is some comment\n"
1022                "    x + 3) {\n"
1023                "}");
1024   EXPECT_EQ("if ( // This is some comment\n"
1025             "     // spanning two lines\n"
1026             "    x + 3) {\n"
1027             "}",
1028             format("if( // This is some comment\n"
1029                    "     // spanning two lines\n"
1030                    " x + 3) {\n"
1031                    "}"));
1032 }
1033 
TEST_F(FormatTest,KeepsParameterWithTrailingCommentsOnTheirOwnLine)1034 TEST_F(FormatTest, KeepsParameterWithTrailingCommentsOnTheirOwnLine) {
1035   EXPECT_EQ("SomeFunction(a,\n"
1036             "             b, // comment\n"
1037             "             c);",
1038             format("SomeFunction(a,\n"
1039                    "          b, // comment\n"
1040                    "      c);"));
1041   EXPECT_EQ("SomeFunction(a, b,\n"
1042             "             // comment\n"
1043             "             c);",
1044             format("SomeFunction(a,\n"
1045                    "          b,\n"
1046                   "  // comment\n"
1047                    "      c);"));
1048   EXPECT_EQ("SomeFunction(a, b, // comment (unclear relation)\n"
1049             "             c);",
1050             format("SomeFunction(a, b, // comment (unclear relation)\n"
1051                    "      c);"));
1052   EXPECT_EQ("SomeFunction(a, // comment\n"
1053             "             b,\n"
1054             "             c); // comment",
1055             format("SomeFunction(a,     // comment\n"
1056                    "          b,\n"
1057                    "      c); // comment"));
1058 }
1059 
TEST_F(FormatTest,CanFormatCommentsLocally)1060 TEST_F(FormatTest, CanFormatCommentsLocally) {
1061   EXPECT_EQ("int a;    // comment\n"
1062             "int    b; // comment",
1063             format("int   a; // comment\n"
1064                    "int    b; // comment",
1065                    0, 0, getLLVMStyle()));
1066   EXPECT_EQ("int   a; // comment\n"
1067             "         // line 2\n"
1068             "int b;",
1069             format("int   a; // comment\n"
1070                    "            // line 2\n"
1071                    "int b;",
1072                    28, 0, getLLVMStyle()));
1073   EXPECT_EQ("int aaaaaa; // comment\n"
1074             "int b;\n"
1075             "int c; // unrelated comment",
1076             format("int aaaaaa; // comment\n"
1077                    "int b;\n"
1078                    "int   c; // unrelated comment",
1079                    31, 0, getLLVMStyle()));
1080 
1081   EXPECT_EQ("int a; // This\n"
1082             "       // is\n"
1083             "       // a",
1084             format("int a;      // This\n"
1085                    "            // is\n"
1086                    "            // a",
1087                    0, 0, getLLVMStyle()));
1088   EXPECT_EQ("int a; // This\n"
1089             "       // is\n"
1090             "       // a\n"
1091             "// This is b\n"
1092             "int b;",
1093             format("int a; // This\n"
1094                    "     // is\n"
1095                    "     // a\n"
1096                    "// This is b\n"
1097                    "int b;",
1098                    0, 0, getLLVMStyle()));
1099   EXPECT_EQ("int a; // This\n"
1100             "       // is\n"
1101             "       // a\n"
1102             "\n"
1103             "  // This is unrelated",
1104             format("int a; // This\n"
1105                    "     // is\n"
1106                    "     // a\n"
1107                    "\n"
1108                    "  // This is unrelated",
1109                    0, 0, getLLVMStyle()));
1110   EXPECT_EQ("int a;\n"
1111             "// This is\n"
1112             "// not formatted.   ",
1113             format("int a;\n"
1114                    "// This is\n"
1115                    "// not formatted.   ",
1116                    0, 0, getLLVMStyle()));
1117 }
1118 
TEST_F(FormatTest,RemovesTrailingWhitespaceOfComments)1119 TEST_F(FormatTest, RemovesTrailingWhitespaceOfComments) {
1120   EXPECT_EQ("// comment", format("// comment  "));
1121   EXPECT_EQ("int aaaaaaa, bbbbbbb; // comment",
1122             format("int aaaaaaa, bbbbbbb; // comment                   ",
1123                    getLLVMStyleWithColumns(33)));
1124   EXPECT_EQ("// comment\\\n", format("// comment\\\n  \t \v   \f   "));
1125   EXPECT_EQ("// comment    \\\n", format("// comment    \\\n  \t \v   \f   "));
1126 }
1127 
TEST_F(FormatTest,UnderstandsBlockComments)1128 TEST_F(FormatTest, UnderstandsBlockComments) {
1129   verifyFormat("f(/*noSpaceAfterParameterNamingComment=*/true);");
1130   verifyFormat("void f() { g(/*aaa=*/x, /*bbb=*/!y); }");
1131   EXPECT_EQ("f(aaaaaaaaaaaaaaaaaaaaaaaaa, /* Trailing comment for aa... */\n"
1132             "  bbbbbbbbbbbbbbbbbbbbbbbbb);",
1133             format("f(aaaaaaaaaaaaaaaaaaaaaaaaa ,   \\\n"
1134                    "/* Trailing comment for aa... */\n"
1135                    "  bbbbbbbbbbbbbbbbbbbbbbbbb);"));
1136   EXPECT_EQ(
1137       "f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1138       "  /* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);",
1139       format("f(aaaaaaaaaaaaaaaaaaaaaaaaa    ,   \n"
1140              "/* Leading comment for bb... */   bbbbbbbbbbbbbbbbbbbbbbbbb);"));
1141   EXPECT_EQ(
1142       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1143       "    aaaaaaaaaaaaaaaaaa,\n"
1144       "    aaaaaaaaaaaaaaaaaa) { /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
1145       "}",
1146       format("void      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1147              "                      aaaaaaaaaaaaaaaaaa  ,\n"
1148              "    aaaaaaaaaaaaaaaaaa) {   /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
1149              "}"));
1150 
1151   FormatStyle NoBinPacking = getLLVMStyle();
1152   NoBinPacking.BinPackParameters = false;
1153   verifyFormat("aaaaaaaa(/* parameter 1 */ aaaaaa,\n"
1154                "         /* parameter 2 */ aaaaaa,\n"
1155                "         /* parameter 3 */ aaaaaa,\n"
1156                "         /* parameter 4 */ aaaaaa);",
1157                NoBinPacking);
1158 
1159   // Aligning block comments in macros.
1160   verifyGoogleFormat("#define A        \\\n"
1161                      "  int i;   /*a*/ \\\n"
1162                      "  int jjj; /*b*/");
1163 }
1164 
TEST_F(FormatTest,AlignsBlockComments)1165 TEST_F(FormatTest, AlignsBlockComments) {
1166   EXPECT_EQ("/*\n"
1167             " * Really multi-line\n"
1168             " * comment.\n"
1169             " */\n"
1170             "void f() {}",
1171             format("  /*\n"
1172                    "   * Really multi-line\n"
1173                    "   * comment.\n"
1174                    "   */\n"
1175                    "  void f() {}"));
1176   EXPECT_EQ("class C {\n"
1177             "  /*\n"
1178             "   * Another multi-line\n"
1179             "   * comment.\n"
1180             "   */\n"
1181             "  void f() {}\n"
1182             "};",
1183             format("class C {\n"
1184                    "/*\n"
1185                    " * Another multi-line\n"
1186                    " * comment.\n"
1187                    " */\n"
1188                    "void f() {}\n"
1189                    "};"));
1190   EXPECT_EQ("/*\n"
1191             "  1. This is a comment with non-trivial formatting.\n"
1192             "     1.1. We have to indent/outdent all lines equally\n"
1193             "         1.1.1. to keep the formatting.\n"
1194             " */",
1195             format("  /*\n"
1196                    "    1. This is a comment with non-trivial formatting.\n"
1197                    "       1.1. We have to indent/outdent all lines equally\n"
1198                    "           1.1.1. to keep the formatting.\n"
1199                    "   */"));
1200   EXPECT_EQ("/*\n"
1201             "Don't try to outdent if there's not enough indentation.\n"
1202             "*/",
1203             format("  /*\n"
1204                    " Don't try to outdent if there's not enough indentation.\n"
1205                    " */"));
1206 
1207   EXPECT_EQ("int i; /* Comment with empty...\n"
1208             "        *\n"
1209             "        * line. */",
1210             format("int i; /* Comment with empty...\n"
1211                    "        *\n"
1212                    "        * line. */"));
1213   EXPECT_EQ("int foobar = 0; /* comment */\n"
1214             "int bar = 0;    /* multiline\n"
1215             "                   comment 1 */\n"
1216             "int baz = 0;    /* multiline\n"
1217             "                   comment 2 */\n"
1218             "int bzz = 0;    /* multiline\n"
1219             "                   comment 3 */",
1220             format("int foobar = 0; /* comment */\n"
1221                    "int bar = 0;    /* multiline\n"
1222                    "                   comment 1 */\n"
1223                    "int baz = 0; /* multiline\n"
1224                    "                comment 2 */\n"
1225                    "int bzz = 0;         /* multiline\n"
1226                    "                        comment 3 */"));
1227   EXPECT_EQ("int foobar = 0; /* comment */\n"
1228             "int bar = 0;    /* multiline\n"
1229             "   comment */\n"
1230             "int baz = 0;    /* multiline\n"
1231             "comment */",
1232             format("int foobar = 0; /* comment */\n"
1233                    "int bar = 0; /* multiline\n"
1234                    "comment */\n"
1235                    "int baz = 0;        /* multiline\n"
1236                    "comment */"));
1237 }
1238 
TEST_F(FormatTest,CorrectlyHandlesLengthOfBlockComments)1239 TEST_F(FormatTest, CorrectlyHandlesLengthOfBlockComments) {
1240   EXPECT_EQ("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1241             "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */",
1242             format("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1243                    "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */"));
1244   EXPECT_EQ(
1245       "void ffffffffffff(\n"
1246       "    int aaaaaaaa, int bbbbbbbb,\n"
1247       "    int cccccccccccc) { /*\n"
1248       "                           aaaaaaaaaa\n"
1249       "                           aaaaaaaaaaaaa\n"
1250       "                           bbbbbbbbbbbbbb\n"
1251       "                           bbbbbbbbbb\n"
1252       "                         */\n"
1253       "}",
1254       format("void ffffffffffff(int aaaaaaaa, int bbbbbbbb, int cccccccccccc)\n"
1255              "{ /*\n"
1256              "     aaaaaaaaaa aaaaaaaaaaaaa\n"
1257              "     bbbbbbbbbbbbbb bbbbbbbbbb\n"
1258              "   */\n"
1259              "}",
1260              getLLVMStyleWithColumns(40)));
1261 }
1262 
TEST_F(FormatTest,DontBreakNonTrailingBlockComments)1263 TEST_F(FormatTest, DontBreakNonTrailingBlockComments) {
1264   EXPECT_EQ("void ffffffffff(\n"
1265             "    int aaaaa /* test */);",
1266             format("void ffffffffff(int aaaaa /* test */);",
1267                    getLLVMStyleWithColumns(35)));
1268 }
1269 
TEST_F(FormatTest,SplitsLongCxxComments)1270 TEST_F(FormatTest, SplitsLongCxxComments) {
1271   EXPECT_EQ("// A comment that\n"
1272             "// doesn't fit on\n"
1273             "// one line",
1274             format("// A comment that doesn't fit on one line",
1275                    getLLVMStyleWithColumns(20)));
1276   EXPECT_EQ("// a b c d\n"
1277             "// e f  g\n"
1278             "// h i j k",
1279             format("// a b c d e f  g h i j k",
1280                    getLLVMStyleWithColumns(10)));
1281   EXPECT_EQ("// a b c d\n"
1282             "// e f  g\n"
1283             "// h i j k",
1284             format("\\\n// a b c d e f  g h i j k",
1285                    getLLVMStyleWithColumns(10)));
1286   EXPECT_EQ("if (true) // A comment that\n"
1287             "          // doesn't fit on\n"
1288             "          // one line",
1289             format("if (true) // A comment that doesn't fit on one line   ",
1290                    getLLVMStyleWithColumns(30)));
1291   EXPECT_EQ("//    Don't_touch_leading_whitespace",
1292             format("//    Don't_touch_leading_whitespace",
1293                    getLLVMStyleWithColumns(20)));
1294   EXPECT_EQ("// Add leading\n"
1295             "// whitespace",
1296             format("//Add leading whitespace", getLLVMStyleWithColumns(20)));
1297   EXPECT_EQ("// whitespace", format("//whitespace", getLLVMStyle()));
1298   EXPECT_EQ("// Even if it makes the line exceed the column\n"
1299             "// limit",
1300             format("//Even if it makes the line exceed the column limit",
1301                    getLLVMStyleWithColumns(51)));
1302   EXPECT_EQ("//--But not here", format("//--But not here", getLLVMStyle()));
1303 
1304   EXPECT_EQ("// aa bb cc dd",
1305             format("// aa bb             cc dd                   ",
1306                    getLLVMStyleWithColumns(15)));
1307 
1308   EXPECT_EQ("// A comment before\n"
1309             "// a macro\n"
1310             "// definition\n"
1311             "#define a b",
1312             format("// A comment before a macro definition\n"
1313                    "#define a b",
1314                    getLLVMStyleWithColumns(20)));
1315   EXPECT_EQ("void ffffff(\n"
1316             "    int aaaaaaaaa,  // wwww\n"
1317             "    int bbbbbbbbbb, // xxxxxxx\n"
1318             "                    // yyyyyyyyyy\n"
1319             "    int c, int d, int e) {}",
1320             format("void ffffff(\n"
1321                    "    int aaaaaaaaa, // wwww\n"
1322                    "    int bbbbbbbbbb, // xxxxxxx yyyyyyyyyy\n"
1323                    "    int c, int d, int e) {}",
1324                    getLLVMStyleWithColumns(40)));
1325   EXPECT_EQ("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1326             format("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1327                    getLLVMStyleWithColumns(20)));
1328   EXPECT_EQ(
1329       "#define XXX // a b c d\n"
1330       "            // e f g h",
1331       format("#define XXX // a b c d e f g h", getLLVMStyleWithColumns(22)));
1332   EXPECT_EQ(
1333       "#define XXX // q w e r\n"
1334       "            // t y u i",
1335       format("#define XXX //q w e r t y u i", getLLVMStyleWithColumns(22)));
1336 }
1337 
TEST_F(FormatTest,PreservesHangingIndentInCxxComments)1338 TEST_F(FormatTest, PreservesHangingIndentInCxxComments) {
1339   EXPECT_EQ("//     A comment\n"
1340             "//     that doesn't\n"
1341             "//     fit on one\n"
1342             "//     line",
1343             format("//     A comment that doesn't fit on one line",
1344                    getLLVMStyleWithColumns(20)));
1345   EXPECT_EQ("///     A comment\n"
1346             "///     that doesn't\n"
1347             "///     fit on one\n"
1348             "///     line",
1349             format("///     A comment that doesn't fit on one line",
1350                    getLLVMStyleWithColumns(20)));
1351 }
1352 
TEST_F(FormatTest,DontSplitLineCommentsWithEscapedNewlines)1353 TEST_F(FormatTest, DontSplitLineCommentsWithEscapedNewlines) {
1354   EXPECT_EQ("// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1355             "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1356             "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1357             format("// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1358                    "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1359                    "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
1360   EXPECT_EQ("int a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1361             "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1362             "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1363             format("int a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1364                    "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1365                    "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1366                    getLLVMStyleWithColumns(50)));
1367   // FIXME: One day we might want to implement adjustment of leading whitespace
1368   // of the consecutive lines in this kind of comment:
1369   EXPECT_EQ("double\n"
1370             "    a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1371             "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1372             "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1373             format("double a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1374                    "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1375                    "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1376                    getLLVMStyleWithColumns(49)));
1377 }
1378 
TEST_F(FormatTest,DontSplitLineCommentsWithPragmas)1379 TEST_F(FormatTest, DontSplitLineCommentsWithPragmas) {
1380   FormatStyle Pragmas = getLLVMStyleWithColumns(30);
1381   Pragmas.CommentPragmas = "^ IWYU pragma:";
1382   EXPECT_EQ(
1383       "// IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb",
1384       format("// IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb", Pragmas));
1385   EXPECT_EQ(
1386       "/* IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb */",
1387       format("/* IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb */", Pragmas));
1388 }
1389 
TEST_F(FormatTest,PriorityOfCommentBreaking)1390 TEST_F(FormatTest, PriorityOfCommentBreaking) {
1391   EXPECT_EQ("if (xxx ==\n"
1392             "        yyy && // aaaaaaaaaaaa bbbbbbbbb\n"
1393             "    zzz)\n"
1394             "  q();",
1395             format("if (xxx == yyy && // aaaaaaaaaaaa bbbbbbbbb\n"
1396                    "    zzz) q();",
1397                    getLLVMStyleWithColumns(40)));
1398   EXPECT_EQ("if (xxxxxxxxxx ==\n"
1399             "        yyy && // aaaaaa bbbbbbbb cccc\n"
1400             "    zzz)\n"
1401             "  q();",
1402             format("if (xxxxxxxxxx == yyy && // aaaaaa bbbbbbbb cccc\n"
1403                    "    zzz) q();",
1404                    getLLVMStyleWithColumns(40)));
1405   EXPECT_EQ("if (xxxxxxxxxx &&\n"
1406             "        yyy || // aaaaaa bbbbbbbb cccc\n"
1407             "    zzz)\n"
1408             "  q();",
1409             format("if (xxxxxxxxxx && yyy || // aaaaaa bbbbbbbb cccc\n"
1410                    "    zzz) q();",
1411                    getLLVMStyleWithColumns(40)));
1412   EXPECT_EQ("fffffffff(\n"
1413             "    &xxx, // aaaaaaaaaaaa bbbbbbbbbbb\n"
1414             "    zzz);",
1415             format("fffffffff(&xxx, // aaaaaaaaaaaa bbbbbbbbbbb\n"
1416                    " zzz);",
1417                    getLLVMStyleWithColumns(40)));
1418 }
1419 
TEST_F(FormatTest,MultiLineCommentsInDefines)1420 TEST_F(FormatTest, MultiLineCommentsInDefines) {
1421   EXPECT_EQ("#define A(x) /* \\\n"
1422             "  a comment     \\\n"
1423             "  inside */     \\\n"
1424             "  f();",
1425             format("#define A(x) /* \\\n"
1426                    "  a comment     \\\n"
1427                    "  inside */     \\\n"
1428                    "  f();",
1429                    getLLVMStyleWithColumns(17)));
1430   EXPECT_EQ("#define A(      \\\n"
1431             "    x) /*       \\\n"
1432             "  a comment     \\\n"
1433             "  inside */     \\\n"
1434             "  f();",
1435             format("#define A(      \\\n"
1436                    "    x) /*       \\\n"
1437                    "  a comment     \\\n"
1438                    "  inside */     \\\n"
1439                    "  f();",
1440                    getLLVMStyleWithColumns(17)));
1441 }
1442 
TEST_F(FormatTest,ParsesCommentsAdjacentToPPDirectives)1443 TEST_F(FormatTest, ParsesCommentsAdjacentToPPDirectives) {
1444   EXPECT_EQ("namespace {}\n// Test\n#define A",
1445             format("namespace {}\n   // Test\n#define A"));
1446   EXPECT_EQ("namespace {}\n/* Test */\n#define A",
1447             format("namespace {}\n   /* Test */\n#define A"));
1448   EXPECT_EQ("namespace {}\n/* Test */ #define A",
1449             format("namespace {}\n   /* Test */    #define A"));
1450 }
1451 
TEST_F(FormatTest,SplitsLongLinesInComments)1452 TEST_F(FormatTest, SplitsLongLinesInComments) {
1453   EXPECT_EQ("/* This is a long\n"
1454             " * comment that\n"
1455             " * doesn't\n"
1456             " * fit on one line.\n"
1457             " */",
1458             format("/* "
1459                    "This is a long                                         "
1460                    "comment that "
1461                    "doesn't                                    "
1462                    "fit on one line.  */",
1463                    getLLVMStyleWithColumns(20)));
1464   EXPECT_EQ("/* a b c d\n"
1465             " * e f  g\n"
1466             " * h i j k\n"
1467             " */",
1468             format("/* a b c d e f  g h i j k */",
1469                    getLLVMStyleWithColumns(10)));
1470   EXPECT_EQ("/* a b c d\n"
1471             " * e f  g\n"
1472             " * h i j k\n"
1473             " */",
1474             format("\\\n/* a b c d e f  g h i j k */",
1475                    getLLVMStyleWithColumns(10)));
1476   EXPECT_EQ("/*\n"
1477             "This is a long\n"
1478             "comment that doesn't\n"
1479             "fit on one line.\n"
1480             "*/",
1481             format("/*\n"
1482                    "This is a long                                         "
1483                    "comment that doesn't                                    "
1484                    "fit on one line.                                      \n"
1485                    "*/", getLLVMStyleWithColumns(20)));
1486   EXPECT_EQ("/*\n"
1487             " * This is a long\n"
1488             " * comment that\n"
1489             " * doesn't fit on\n"
1490             " * one line.\n"
1491             " */",
1492             format("/*      \n"
1493                    " * This is a long "
1494                    "   comment that     "
1495                    "   doesn't fit on   "
1496                    "   one line.                                            \n"
1497                    " */", getLLVMStyleWithColumns(20)));
1498   EXPECT_EQ("/*\n"
1499             " * This_is_a_comment_with_words_that_dont_fit_on_one_line\n"
1500             " * so_it_should_be_broken\n"
1501             " * wherever_a_space_occurs\n"
1502             " */",
1503             format("/*\n"
1504                    " * This_is_a_comment_with_words_that_dont_fit_on_one_line "
1505                    "   so_it_should_be_broken "
1506                    "   wherever_a_space_occurs                             \n"
1507                    " */",
1508                    getLLVMStyleWithColumns(20)));
1509   EXPECT_EQ("/*\n"
1510             " *    This_comment_can_not_be_broken_into_lines\n"
1511             " */",
1512             format("/*\n"
1513                    " *    This_comment_can_not_be_broken_into_lines\n"
1514                    " */",
1515                    getLLVMStyleWithColumns(20)));
1516   EXPECT_EQ("{\n"
1517             "  /*\n"
1518             "  This is another\n"
1519             "  long comment that\n"
1520             "  doesn't fit on one\n"
1521             "  line    1234567890\n"
1522             "  */\n"
1523             "}",
1524             format("{\n"
1525                    "/*\n"
1526                    "This is another     "
1527                    "  long comment that "
1528                    "  doesn't fit on one"
1529                    "  line    1234567890\n"
1530                    "*/\n"
1531                    "}", getLLVMStyleWithColumns(20)));
1532   EXPECT_EQ("{\n"
1533             "  /*\n"
1534             "   * This        i s\n"
1535             "   * another comment\n"
1536             "   * t hat  doesn' t\n"
1537             "   * fit on one l i\n"
1538             "   * n e\n"
1539             "   */\n"
1540             "}",
1541             format("{\n"
1542                    "/*\n"
1543                    " * This        i s"
1544                    "   another comment"
1545                    "   t hat  doesn' t"
1546                    "   fit on one l i"
1547                    "   n e\n"
1548                    " */\n"
1549                    "}", getLLVMStyleWithColumns(20)));
1550   EXPECT_EQ("/*\n"
1551             " * This is a long\n"
1552             " * comment that\n"
1553             " * doesn't fit on\n"
1554             " * one line\n"
1555             " */",
1556             format("   /*\n"
1557                    "    * This is a long comment that doesn't fit on one line\n"
1558                    "    */", getLLVMStyleWithColumns(20)));
1559   EXPECT_EQ("{\n"
1560             "  if (something) /* This is a\n"
1561             "                    long\n"
1562             "                    comment */\n"
1563             "    ;\n"
1564             "}",
1565             format("{\n"
1566                    "  if (something) /* This is a long comment */\n"
1567                    "    ;\n"
1568                    "}",
1569                    getLLVMStyleWithColumns(30)));
1570 
1571   EXPECT_EQ("/* A comment before\n"
1572             " * a macro\n"
1573             " * definition */\n"
1574             "#define a b",
1575             format("/* A comment before a macro definition */\n"
1576                    "#define a b",
1577                    getLLVMStyleWithColumns(20)));
1578 
1579   EXPECT_EQ("/* some comment\n"
1580             "     *   a comment\n"
1581             "* that we break\n"
1582             " * another comment\n"
1583             "* we have to break\n"
1584             "* a left comment\n"
1585             " */",
1586             format("  /* some comment\n"
1587                    "       *   a comment that we break\n"
1588                    "   * another comment we have to break\n"
1589                    "* a left comment\n"
1590                    "   */",
1591                    getLLVMStyleWithColumns(20)));
1592 
1593   EXPECT_EQ("/*\n"
1594             "\n"
1595             "\n"
1596             "    */\n",
1597             format("  /*       \n"
1598                    "      \n"
1599                    "               \n"
1600                    "      */\n"));
1601 
1602   EXPECT_EQ("/* a a */",
1603             format("/* a a            */", getLLVMStyleWithColumns(15)));
1604   EXPECT_EQ("/* a a bc  */",
1605             format("/* a a            bc  */", getLLVMStyleWithColumns(15)));
1606   EXPECT_EQ("/* aaa aaa\n"
1607             " * aaaaa */",
1608             format("/* aaa aaa aaaaa       */", getLLVMStyleWithColumns(15)));
1609   EXPECT_EQ("/* aaa aaa\n"
1610             " * aaaaa     */",
1611             format("/* aaa aaa aaaaa     */", getLLVMStyleWithColumns(15)));
1612 }
1613 
TEST_F(FormatTest,SplitsLongLinesInCommentsInPreprocessor)1614 TEST_F(FormatTest, SplitsLongLinesInCommentsInPreprocessor) {
1615   EXPECT_EQ("#define X          \\\n"
1616             "  /*               \\\n"
1617             "   Test            \\\n"
1618             "   Macro comment   \\\n"
1619             "   with a long     \\\n"
1620             "   line            \\\n"
1621             "   */              \\\n"
1622             "  A + B",
1623             format("#define X \\\n"
1624                    "  /*\n"
1625                    "   Test\n"
1626                    "   Macro comment with a long  line\n"
1627                    "   */ \\\n"
1628                    "  A + B",
1629                    getLLVMStyleWithColumns(20)));
1630   EXPECT_EQ("#define X          \\\n"
1631             "  /* Macro comment \\\n"
1632             "     with a long   \\\n"
1633             "     line */       \\\n"
1634             "  A + B",
1635             format("#define X \\\n"
1636                    "  /* Macro comment with a long\n"
1637                    "     line */ \\\n"
1638                    "  A + B",
1639                    getLLVMStyleWithColumns(20)));
1640   EXPECT_EQ("#define X          \\\n"
1641             "  /* Macro comment \\\n"
1642             "   * with a long   \\\n"
1643             "   * line */       \\\n"
1644             "  A + B",
1645             format("#define X \\\n"
1646                    "  /* Macro comment with a long  line */ \\\n"
1647                    "  A + B",
1648                    getLLVMStyleWithColumns(20)));
1649 }
1650 
TEST_F(FormatTest,CommentsInStaticInitializers)1651 TEST_F(FormatTest, CommentsInStaticInitializers) {
1652   EXPECT_EQ(
1653       "static SomeType type = {aaaaaaaaaaaaaaaaaaaa, /* comment */\n"
1654       "                        aaaaaaaaaaaaaaaaaaaa /* comment */,\n"
1655       "                        /* comment */ aaaaaaaaaaaaaaaaaaaa,\n"
1656       "                        aaaaaaaaaaaaaaaaaaaa, // comment\n"
1657       "                        aaaaaaaaaaaaaaaaaaaa};",
1658       format("static SomeType type = { aaaaaaaaaaaaaaaaaaaa  ,  /* comment */\n"
1659              "                   aaaaaaaaaaaaaaaaaaaa   /* comment */ ,\n"
1660              "                     /* comment */   aaaaaaaaaaaaaaaaaaaa ,\n"
1661              "              aaaaaaaaaaaaaaaaaaaa ,   // comment\n"
1662              "                  aaaaaaaaaaaaaaaaaaaa };"));
1663   verifyFormat("static SomeType type = {aaaaaaaaaaa, // comment for aa...\n"
1664                "                        bbbbbbbbbbb, ccccccccccc};");
1665   verifyFormat("static SomeType type = {aaaaaaaaaaa,\n"
1666                "                        // comment for bb....\n"
1667                "                        bbbbbbbbbbb, ccccccccccc};");
1668   verifyGoogleFormat(
1669       "static SomeType type = {aaaaaaaaaaa,  // comment for aa...\n"
1670       "                        bbbbbbbbbbb, ccccccccccc};");
1671   verifyGoogleFormat("static SomeType type = {aaaaaaaaaaa,\n"
1672                      "                        // comment for bb....\n"
1673                      "                        bbbbbbbbbbb, ccccccccccc};");
1674 
1675   verifyFormat("S s = {{a, b, c},  // Group #1\n"
1676                "       {d, e, f},  // Group #2\n"
1677                "       {g, h, i}}; // Group #3");
1678   verifyFormat("S s = {{// Group #1\n"
1679                "        a, b, c},\n"
1680                "       {// Group #2\n"
1681                "        d, e, f},\n"
1682                "       {// Group #3\n"
1683                "        g, h, i}};");
1684 
1685   EXPECT_EQ("S s = {\n"
1686             "    // Some comment\n"
1687             "    a,\n"
1688             "\n"
1689             "    // Comment after empty line\n"
1690             "    b}",
1691             format("S s =    {\n"
1692                    "      // Some comment\n"
1693                    "  a,\n"
1694                    "  \n"
1695                    "     // Comment after empty line\n"
1696                    "      b\n"
1697                    "}"));
1698   EXPECT_EQ("S s = {\n"
1699             "    /* Some comment */\n"
1700             "    a,\n"
1701             "\n"
1702             "    /* Comment after empty line */\n"
1703             "    b}",
1704             format("S s =    {\n"
1705                    "      /* Some comment */\n"
1706                    "  a,\n"
1707                    "  \n"
1708                    "     /* Comment after empty line */\n"
1709                    "      b\n"
1710                    "}"));
1711   verifyFormat("const uint8_t aaaaaaaaaaaaaaaaaaaaaa[0] = {\n"
1712                "    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1713                "    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1714                "    0x00, 0x00, 0x00, 0x00};            // comment\n");
1715 }
1716 
TEST_F(FormatTest,IgnoresIf0Contents)1717 TEST_F(FormatTest, IgnoresIf0Contents) {
1718   EXPECT_EQ("#if 0\n"
1719             "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1720             "#endif\n"
1721             "void f() {}",
1722             format("#if 0\n"
1723                    "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1724                    "#endif\n"
1725                    "void f(  ) {  }"));
1726   EXPECT_EQ("#if false\n"
1727             "void f(  ) {  }\n"
1728             "#endif\n"
1729             "void g() {}\n",
1730             format("#if false\n"
1731                    "void f(  ) {  }\n"
1732                    "#endif\n"
1733                    "void g(  ) {  }\n"));
1734   EXPECT_EQ("enum E {\n"
1735             "  One,\n"
1736             "  Two,\n"
1737             "#if 0\n"
1738             "Three,\n"
1739             "      Four,\n"
1740             "#endif\n"
1741             "  Five\n"
1742             "};",
1743             format("enum E {\n"
1744                    "  One,Two,\n"
1745                    "#if 0\n"
1746                    "Three,\n"
1747                    "      Four,\n"
1748                    "#endif\n"
1749                    "  Five};"));
1750   EXPECT_EQ("enum F {\n"
1751             "  One,\n"
1752             "#if 1\n"
1753             "  Two,\n"
1754             "#if 0\n"
1755             "Three,\n"
1756             "      Four,\n"
1757             "#endif\n"
1758             "  Five\n"
1759             "#endif\n"
1760             "};",
1761             format("enum F {\n"
1762                    "One,\n"
1763                    "#if 1\n"
1764                    "Two,\n"
1765                    "#if 0\n"
1766                    "Three,\n"
1767                    "      Four,\n"
1768                    "#endif\n"
1769                    "Five\n"
1770                    "#endif\n"
1771                    "};"));
1772   EXPECT_EQ("enum G {\n"
1773             "  One,\n"
1774             "#if 0\n"
1775             "Two,\n"
1776             "#else\n"
1777             "  Three,\n"
1778             "#endif\n"
1779             "  Four\n"
1780             "};",
1781             format("enum G {\n"
1782                    "One,\n"
1783                    "#if 0\n"
1784                    "Two,\n"
1785                    "#else\n"
1786                    "Three,\n"
1787                    "#endif\n"
1788                    "Four\n"
1789                    "};"));
1790   EXPECT_EQ("enum H {\n"
1791             "  One,\n"
1792             "#if 0\n"
1793             "#ifdef Q\n"
1794             "Two,\n"
1795             "#else\n"
1796             "Three,\n"
1797             "#endif\n"
1798             "#endif\n"
1799             "  Four\n"
1800             "};",
1801             format("enum H {\n"
1802                    "One,\n"
1803                    "#if 0\n"
1804                    "#ifdef Q\n"
1805                    "Two,\n"
1806                    "#else\n"
1807                    "Three,\n"
1808                    "#endif\n"
1809                    "#endif\n"
1810                    "Four\n"
1811                    "};"));
1812   EXPECT_EQ("enum I {\n"
1813             "  One,\n"
1814             "#if /* test */ 0 || 1\n"
1815             "Two,\n"
1816             "Three,\n"
1817             "#endif\n"
1818             "  Four\n"
1819             "};",
1820             format("enum I {\n"
1821                    "One,\n"
1822                    "#if /* test */ 0 || 1\n"
1823                    "Two,\n"
1824                    "Three,\n"
1825                    "#endif\n"
1826                    "Four\n"
1827                    "};"));
1828   EXPECT_EQ("enum J {\n"
1829             "  One,\n"
1830             "#if 0\n"
1831             "#if 0\n"
1832             "Two,\n"
1833             "#else\n"
1834             "Three,\n"
1835             "#endif\n"
1836             "Four,\n"
1837             "#endif\n"
1838             "  Five\n"
1839             "};",
1840             format("enum J {\n"
1841                    "One,\n"
1842                    "#if 0\n"
1843                    "#if 0\n"
1844                    "Two,\n"
1845                    "#else\n"
1846                    "Three,\n"
1847                    "#endif\n"
1848                    "Four,\n"
1849                    "#endif\n"
1850                    "Five\n"
1851                    "};"));
1852 
1853 }
1854 
1855 //===----------------------------------------------------------------------===//
1856 // Tests for classes, namespaces, etc.
1857 //===----------------------------------------------------------------------===//
1858 
TEST_F(FormatTest,DoesNotBreakSemiAfterClassDecl)1859 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1860   verifyFormat("class A {};");
1861 }
1862 
TEST_F(FormatTest,UnderstandsAccessSpecifiers)1863 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1864   verifyFormat("class A {\n"
1865                "public:\n"
1866                "public: // comment\n"
1867                "protected:\n"
1868                "private:\n"
1869                "  void f() {}\n"
1870                "};");
1871   verifyGoogleFormat("class A {\n"
1872                      " public:\n"
1873                      " protected:\n"
1874                      " private:\n"
1875                      "  void f() {}\n"
1876                      "};");
1877   verifyFormat("class A {\n"
1878                "public slots:\n"
1879                "  void f() {}\n"
1880                "public Q_SLOTS:\n"
1881                "  void f() {}\n"
1882                "};");
1883 }
1884 
TEST_F(FormatTest,SeparatesLogicalBlocks)1885 TEST_F(FormatTest, SeparatesLogicalBlocks) {
1886   EXPECT_EQ("class A {\n"
1887             "public:\n"
1888             "  void f();\n"
1889             "\n"
1890             "private:\n"
1891             "  void g() {}\n"
1892             "  // test\n"
1893             "protected:\n"
1894             "  int h;\n"
1895             "};",
1896             format("class A {\n"
1897                    "public:\n"
1898                    "void f();\n"
1899                    "private:\n"
1900                    "void g() {}\n"
1901                    "// test\n"
1902                    "protected:\n"
1903                    "int h;\n"
1904                    "};"));
1905   EXPECT_EQ("class A {\n"
1906             "protected:\n"
1907             "public:\n"
1908             "  void f();\n"
1909             "};",
1910             format("class A {\n"
1911                    "protected:\n"
1912                    "\n"
1913                    "public:\n"
1914                    "\n"
1915                    "  void f();\n"
1916                    "};"));
1917 }
1918 
TEST_F(FormatTest,FormatsClasses)1919 TEST_F(FormatTest, FormatsClasses) {
1920   verifyFormat("class A : public B {};");
1921   verifyFormat("class A : public ::B {};");
1922 
1923   verifyFormat(
1924       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1925       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1926   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
1927                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1928                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1929   verifyFormat(
1930       "class A : public B, public C, public D, public E, public F {};");
1931   verifyFormat("class AAAAAAAAAAAA : public B,\n"
1932                "                     public C,\n"
1933                "                     public D,\n"
1934                "                     public E,\n"
1935                "                     public F,\n"
1936                "                     public G {};");
1937 
1938   verifyFormat("class\n"
1939                "    ReallyReallyLongClassName {\n"
1940                "  int i;\n"
1941                "};",
1942                getLLVMStyleWithColumns(32));
1943   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
1944                "                           aaaaaaaaaaaaaaaa> {};");
1945   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
1946                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
1947                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
1948   verifyFormat("template <class R, class C>\n"
1949                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
1950                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
1951   verifyFormat("class ::A::B {};");
1952 }
1953 
TEST_F(FormatTest,FormatsVariableDeclarationsAfterStructOrClass)1954 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
1955   verifyFormat("class A {\n} a, b;");
1956   verifyFormat("struct A {\n} a, b;");
1957   verifyFormat("union A {\n} a;");
1958 }
1959 
TEST_F(FormatTest,FormatsEnum)1960 TEST_F(FormatTest, FormatsEnum) {
1961   verifyFormat("enum {\n"
1962                "  Zero,\n"
1963                "  One = 1,\n"
1964                "  Two = One + 1,\n"
1965                "  Three = (One + Two),\n"
1966                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1967                "  Five = (One, Two, Three, Four, 5)\n"
1968                "};");
1969   verifyGoogleFormat("enum {\n"
1970                      "  Zero,\n"
1971                      "  One = 1,\n"
1972                      "  Two = One + 1,\n"
1973                      "  Three = (One + Two),\n"
1974                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1975                      "  Five = (One, Two, Three, Four, 5)\n"
1976                      "};");
1977   verifyFormat("enum Enum {};");
1978   verifyFormat("enum {};");
1979   verifyFormat("enum X E {} d;");
1980   verifyFormat("enum __attribute__((...)) E {} d;");
1981   verifyFormat("enum __declspec__((...)) E {} d;");
1982   verifyFormat("enum X f() {\n  a();\n  return 42;\n}");
1983   verifyFormat("enum {\n"
1984                "  Bar = Foo<int, int>::value\n"
1985                "};",
1986                getLLVMStyleWithColumns(30));
1987 
1988   verifyFormat("enum ShortEnum { A, B, C };");
1989   verifyGoogleFormat("enum ShortEnum { A, B, C };");
1990 
1991   EXPECT_EQ("enum KeepEmptyLines {\n"
1992             "  ONE,\n"
1993             "\n"
1994             "  TWO,\n"
1995             "\n"
1996             "  THREE\n"
1997             "}",
1998             format("enum KeepEmptyLines {\n"
1999                    "  ONE,\n"
2000                    "\n"
2001                    "  TWO,\n"
2002                    "\n"
2003                    "\n"
2004                    "  THREE\n"
2005                    "}"));
2006   verifyFormat("enum E { // comment\n"
2007                "  ONE,\n"
2008                "  TWO\n"
2009                "};\n"
2010                "int i;");
2011 }
2012 
TEST_F(FormatTest,FormatsEnumsWithErrors)2013 TEST_F(FormatTest, FormatsEnumsWithErrors) {
2014   verifyFormat("enum Type {\n"
2015                "  One = 0; // These semicolons should be commas.\n"
2016                "  Two = 1;\n"
2017                "};");
2018   verifyFormat("namespace n {\n"
2019                "enum Type {\n"
2020                "  One,\n"
2021                "  Two, // missing };\n"
2022                "  int i;\n"
2023                "}\n"
2024                "void g() {}");
2025 }
2026 
TEST_F(FormatTest,FormatsEnumStruct)2027 TEST_F(FormatTest, FormatsEnumStruct) {
2028   verifyFormat("enum struct {\n"
2029                "  Zero,\n"
2030                "  One = 1,\n"
2031                "  Two = One + 1,\n"
2032                "  Three = (One + Two),\n"
2033                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2034                "  Five = (One, Two, Three, Four, 5)\n"
2035                "};");
2036   verifyFormat("enum struct Enum {};");
2037   verifyFormat("enum struct {};");
2038   verifyFormat("enum struct X E {} d;");
2039   verifyFormat("enum struct __attribute__((...)) E {} d;");
2040   verifyFormat("enum struct __declspec__((...)) E {} d;");
2041   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
2042 }
2043 
TEST_F(FormatTest,FormatsEnumClass)2044 TEST_F(FormatTest, FormatsEnumClass) {
2045   verifyFormat("enum class {\n"
2046                "  Zero,\n"
2047                "  One = 1,\n"
2048                "  Two = One + 1,\n"
2049                "  Three = (One + Two),\n"
2050                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2051                "  Five = (One, Two, Three, Four, 5)\n"
2052                "};");
2053   verifyFormat("enum class Enum {};");
2054   verifyFormat("enum class {};");
2055   verifyFormat("enum class X E {} d;");
2056   verifyFormat("enum class __attribute__((...)) E {} d;");
2057   verifyFormat("enum class __declspec__((...)) E {} d;");
2058   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
2059 }
2060 
TEST_F(FormatTest,FormatsEnumTypes)2061 TEST_F(FormatTest, FormatsEnumTypes) {
2062   verifyFormat("enum X : int {\n"
2063                "  A, // Force multiple lines.\n"
2064                "  B\n"
2065                "};");
2066   verifyFormat("enum X : int { A, B };");
2067   verifyFormat("enum X : std::uint32_t { A, B };");
2068 }
2069 
TEST_F(FormatTest,FormatsNSEnums)2070 TEST_F(FormatTest, FormatsNSEnums) {
2071   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
2072   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
2073                      "  // Information about someDecentlyLongValue.\n"
2074                      "  someDecentlyLongValue,\n"
2075                      "  // Information about anotherDecentlyLongValue.\n"
2076                      "  anotherDecentlyLongValue,\n"
2077                      "  // Information about aThirdDecentlyLongValue.\n"
2078                      "  aThirdDecentlyLongValue\n"
2079                      "};");
2080   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
2081                      "  a = 1,\n"
2082                      "  b = 2,\n"
2083                      "  c = 3,\n"
2084                      "};");
2085   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
2086                      "  a = 1,\n"
2087                      "  b = 2,\n"
2088                      "  c = 3,\n"
2089                      "};");
2090   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
2091                      "  a = 1,\n"
2092                      "  b = 2,\n"
2093                      "  c = 3,\n"
2094                      "};");
2095 }
2096 
TEST_F(FormatTest,FormatsBitfields)2097 TEST_F(FormatTest, FormatsBitfields) {
2098   verifyFormat("struct Bitfields {\n"
2099                "  unsigned sClass : 8;\n"
2100                "  unsigned ValueKind : 2;\n"
2101                "};");
2102   verifyFormat("struct A {\n"
2103                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
2104                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
2105                "};");
2106 }
2107 
TEST_F(FormatTest,FormatsNamespaces)2108 TEST_F(FormatTest, FormatsNamespaces) {
2109   verifyFormat("namespace some_namespace {\n"
2110                "class A {};\n"
2111                "void f() { f(); }\n"
2112                "}");
2113   verifyFormat("namespace {\n"
2114                "class A {};\n"
2115                "void f() { f(); }\n"
2116                "}");
2117   verifyFormat("inline namespace X {\n"
2118                "class A {};\n"
2119                "void f() { f(); }\n"
2120                "}");
2121   verifyFormat("using namespace some_namespace;\n"
2122                "class A {};\n"
2123                "void f() { f(); }");
2124 
2125   // This code is more common than we thought; if we
2126   // layout this correctly the semicolon will go into
2127   // its own line, which is undesirable.
2128   verifyFormat("namespace {};");
2129   verifyFormat("namespace {\n"
2130                "class A {};\n"
2131                "};");
2132 
2133   verifyFormat("namespace {\n"
2134                "int SomeVariable = 0; // comment\n"
2135                "} // namespace");
2136   EXPECT_EQ("#ifndef HEADER_GUARD\n"
2137             "#define HEADER_GUARD\n"
2138             "namespace my_namespace {\n"
2139             "int i;\n"
2140             "} // my_namespace\n"
2141             "#endif // HEADER_GUARD",
2142             format("#ifndef HEADER_GUARD\n"
2143                    " #define HEADER_GUARD\n"
2144                    "   namespace my_namespace {\n"
2145                    "int i;\n"
2146                    "}    // my_namespace\n"
2147                    "#endif    // HEADER_GUARD"));
2148 
2149   FormatStyle Style = getLLVMStyle();
2150   Style.NamespaceIndentation = FormatStyle::NI_All;
2151   EXPECT_EQ("namespace out {\n"
2152             "  int i;\n"
2153             "  namespace in {\n"
2154             "    int i;\n"
2155             "  } // namespace\n"
2156             "} // namespace",
2157             format("namespace out {\n"
2158                    "int i;\n"
2159                    "namespace in {\n"
2160                    "int i;\n"
2161                    "} // namespace\n"
2162                    "} // namespace",
2163                    Style));
2164 
2165   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2166   EXPECT_EQ("namespace out {\n"
2167             "int i;\n"
2168             "namespace in {\n"
2169             "  int i;\n"
2170             "} // namespace\n"
2171             "} // namespace",
2172             format("namespace out {\n"
2173                    "int i;\n"
2174                    "namespace in {\n"
2175                    "int i;\n"
2176                    "} // namespace\n"
2177                    "} // namespace",
2178                    Style));
2179 }
2180 
TEST_F(FormatTest,FormatsExternC)2181 TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
2182 
TEST_F(FormatTest,FormatsInlineASM)2183 TEST_F(FormatTest, FormatsInlineASM) {
2184   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
2185   verifyFormat("asm(\"nop\" ::: \"memory\");");
2186   verifyFormat(
2187       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
2188       "    \"cpuid\\n\\t\"\n"
2189       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
2190       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
2191       "    : \"a\"(value));");
2192   EXPECT_EQ(
2193       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
2194       "  __asm {\n"
2195       "        mov     edx,[that] // vtable in edx\n"
2196       "        mov     eax,methodIndex\n"
2197       "        call    [edx][eax*4] // stdcall\n"
2198       "  }\n"
2199       "}",
2200       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
2201              "    __asm {\n"
2202              "        mov     edx,[that] // vtable in edx\n"
2203              "        mov     eax,methodIndex\n"
2204              "        call    [edx][eax*4] // stdcall\n"
2205              "    }\n"
2206              "}"));
2207   verifyFormat("void function() {\n"
2208                "  // comment\n"
2209                "  asm(\"\");\n"
2210                "}");
2211 }
2212 
TEST_F(FormatTest,FormatTryCatch)2213 TEST_F(FormatTest, FormatTryCatch) {
2214   verifyFormat("try {\n"
2215                "  throw a * b;\n"
2216                "} catch (int a) {\n"
2217                "  // Do nothing.\n"
2218                "} catch (...) {\n"
2219                "  exit(42);\n"
2220                "}");
2221 
2222   // Function-level try statements.
2223   verifyFormat("int f() try { return 4; } catch (...) {\n"
2224                "  return 5;\n"
2225                "}");
2226   verifyFormat("class A {\n"
2227                "  int a;\n"
2228                "  A() try : a(0) {\n"
2229                "  } catch (...) {\n"
2230                "    throw;\n"
2231                "  }\n"
2232                "};\n");
2233 }
2234 
TEST_F(FormatTest,IncompleteTryCatchBlocks)2235 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
2236   verifyFormat("try {\n"
2237                "  f();\n"
2238                "} catch {\n"
2239                "  g();\n"
2240                "}");
2241   verifyFormat("try {\n"
2242                "  f();\n"
2243                "} catch (A a) MACRO(x) {\n"
2244                "  g();\n"
2245                "} catch (B b) MACRO(x) {\n"
2246                "  g();\n"
2247                "}");
2248 }
2249 
TEST_F(FormatTest,FormatTryCatchBraceStyles)2250 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
2251   FormatStyle Style = getLLVMStyle();
2252   Style.BreakBeforeBraces = FormatStyle::BS_Attach;
2253   verifyFormat("try {\n"
2254                "  // something\n"
2255                "} catch (...) {\n"
2256                "  // something\n"
2257                "}",
2258                Style);
2259   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
2260   verifyFormat("try {\n"
2261                "  // something\n"
2262                "}\n"
2263                "catch (...) {\n"
2264                "  // something\n"
2265                "}",
2266                Style);
2267   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
2268   verifyFormat("try\n"
2269                "{\n"
2270                "  // something\n"
2271                "}\n"
2272                "catch (...)\n"
2273                "{\n"
2274                "  // something\n"
2275                "}",
2276                Style);
2277   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2278   verifyFormat("try\n"
2279                "  {\n"
2280                "    // something\n"
2281                "  }\n"
2282                "catch (...)\n"
2283                "  {\n"
2284                "    // something\n"
2285                "  }",
2286                Style);
2287 }
2288 
TEST_F(FormatTest,FormatObjCTryCatch)2289 TEST_F(FormatTest, FormatObjCTryCatch) {
2290   verifyFormat("@try {\n"
2291                "  f();\n"
2292                "}\n"
2293                "@catch (NSException e) {\n"
2294                "  @throw;\n"
2295                "}\n"
2296                "@finally {\n"
2297                "  exit(42);\n"
2298                "}");
2299 }
2300 
TEST_F(FormatTest,StaticInitializers)2301 TEST_F(FormatTest, StaticInitializers) {
2302   verifyFormat("static SomeClass SC = {1, 'a'};");
2303 
2304   verifyFormat(
2305       "static SomeClass WithALoooooooooooooooooooongName = {\n"
2306       "    100000000, \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
2307 
2308   // Here, everything other than the "}" would fit on a line.
2309   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
2310                "    10000000000000000000000000};");
2311   EXPECT_EQ("S s = {a,\n"
2312             "\n"
2313             "       b};",
2314             format("S s = {\n"
2315                    "  a,\n"
2316                    "\n"
2317                    "  b\n"
2318                    "};"));
2319 
2320   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
2321   // line. However, the formatting looks a bit off and this probably doesn't
2322   // happen often in practice.
2323   verifyFormat("static int Variable[1] = {\n"
2324                "    {1000000000000000000000000000000000000}};",
2325                getLLVMStyleWithColumns(40));
2326 }
2327 
TEST_F(FormatTest,DesignatedInitializers)2328 TEST_F(FormatTest, DesignatedInitializers) {
2329   verifyFormat("const struct A a = {.a = 1, .b = 2};");
2330   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
2331                "                    .bbbbbbbbbb = 2,\n"
2332                "                    .cccccccccc = 3,\n"
2333                "                    .dddddddddd = 4,\n"
2334                "                    .eeeeeeeeee = 5};");
2335   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2336                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
2337                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
2338                "    .ccccccccccccccccccccccccccc = 3,\n"
2339                "    .ddddddddddddddddddddddddddd = 4,\n"
2340                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
2341 
2342   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
2343 }
2344 
TEST_F(FormatTest,NestedStaticInitializers)2345 TEST_F(FormatTest, NestedStaticInitializers) {
2346   verifyFormat("static A x = {{{}}};\n");
2347   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
2348                "               {init1, init2, init3, init4}}};",
2349                getLLVMStyleWithColumns(50));
2350 
2351   verifyFormat("somes Status::global_reps[3] = {\n"
2352                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2353                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2354                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
2355                getLLVMStyleWithColumns(60));
2356   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
2357                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2358                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2359                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
2360   verifyFormat(
2361       "CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
2362       "                  {rect.fRight - rect.fLeft, rect.fBottom - rect.fTop}};");
2363 
2364   verifyFormat(
2365       "SomeArrayOfSomeType a = {\n"
2366       "    {{1, 2, 3},\n"
2367       "     {1, 2, 3},\n"
2368       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
2369       "      333333333333333333333333333333},\n"
2370       "     {1, 2, 3},\n"
2371       "     {1, 2, 3}}};");
2372   verifyFormat(
2373       "SomeArrayOfSomeType a = {\n"
2374       "    {{1, 2, 3}},\n"
2375       "    {{1, 2, 3}},\n"
2376       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
2377       "      333333333333333333333333333333}},\n"
2378       "    {{1, 2, 3}},\n"
2379       "    {{1, 2, 3}}};");
2380 
2381   verifyFormat(
2382       "struct {\n"
2383       "  unsigned bit;\n"
2384       "  const char *const name;\n"
2385       "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
2386       "                 {kOsWin, \"Windows\"},\n"
2387       "                 {kOsLinux, \"Linux\"},\n"
2388       "                 {kOsCrOS, \"Chrome OS\"}};");
2389   verifyFormat(
2390       "struct {\n"
2391       "  unsigned bit;\n"
2392       "  const char *const name;\n"
2393       "} kBitsToOs[] = {\n"
2394       "    {kOsMac, \"Mac\"},\n"
2395       "    {kOsWin, \"Windows\"},\n"
2396       "    {kOsLinux, \"Linux\"},\n"
2397       "    {kOsCrOS, \"Chrome OS\"},\n"
2398       "};");
2399 }
2400 
TEST_F(FormatTest,FormatsSmallMacroDefinitionsInSingleLine)2401 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
2402   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
2403                "                      \\\n"
2404                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
2405 }
2406 
TEST_F(FormatTest,DoesNotBreakPureVirtualFunctionDefinition)2407 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
2408   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
2409                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
2410 }
2411 
TEST_F(FormatTest,BreaksStringLiteralsOnlyInDefine)2412 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
2413   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
2414                getLLVMStyleWithColumns(40));
2415   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
2416                getLLVMStyleWithColumns(40));
2417   EXPECT_EQ("#define Q                              \\\n"
2418             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
2419             "  \"aaaaaaaa.cpp\"",
2420             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
2421                    getLLVMStyleWithColumns(40)));
2422 }
2423 
TEST_F(FormatTest,UnderstandsLinePPDirective)2424 TEST_F(FormatTest, UnderstandsLinePPDirective) {
2425   EXPECT_EQ("# 123 \"A string literal\"",
2426             format("   #     123    \"A string literal\""));
2427 }
2428 
TEST_F(FormatTest,LayoutUnknownPPDirective)2429 TEST_F(FormatTest, LayoutUnknownPPDirective) {
2430   EXPECT_EQ("#;", format("#;"));
2431   verifyFormat("#\n;\n;\n;");
2432 }
2433 
TEST_F(FormatTest,UnescapedEndOfLineEndsPPDirective)2434 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
2435   EXPECT_EQ("#line 42 \"test\"\n",
2436             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
2437   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
2438                                     getLLVMStyleWithColumns(12)));
2439 }
2440 
TEST_F(FormatTest,EndOfFileEndsPPDirective)2441 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
2442   EXPECT_EQ("#line 42 \"test\"",
2443             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
2444   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
2445 }
2446 
TEST_F(FormatTest,DoesntRemoveUnknownTokens)2447 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
2448   verifyFormat("#define A \\x20");
2449   verifyFormat("#define A \\ x20");
2450   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
2451   verifyFormat("#define A ''");
2452   verifyFormat("#define A ''qqq");
2453   verifyFormat("#define A `qqq");
2454   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
2455   EXPECT_EQ("const char *c = STRINGIFY(\n"
2456             "\\na : b);",
2457             format("const char * c = STRINGIFY(\n"
2458                    "\\na : b);"));
2459 }
2460 
TEST_F(FormatTest,IndentsPPDirectiveInReducedSpace)2461 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
2462   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
2463   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
2464   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
2465   // FIXME: We never break before the macro name.
2466   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
2467 
2468   verifyFormat("#define A A\n#define A A");
2469   verifyFormat("#define A(X) A\n#define A A");
2470 
2471   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
2472   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
2473 }
2474 
TEST_F(FormatTest,HandlePreprocessorDirectiveContext)2475 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
2476   EXPECT_EQ("// somecomment\n"
2477             "#include \"a.h\"\n"
2478             "#define A(  \\\n"
2479             "    A, B)\n"
2480             "#include \"b.h\"\n"
2481             "// somecomment\n",
2482             format("  // somecomment\n"
2483                    "  #include \"a.h\"\n"
2484                    "#define A(A,\\\n"
2485                    "    B)\n"
2486                    "    #include \"b.h\"\n"
2487                    " // somecomment\n",
2488                    getLLVMStyleWithColumns(13)));
2489 }
2490 
TEST_F(FormatTest,LayoutSingleHash)2491 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
2492 
TEST_F(FormatTest,LayoutCodeInMacroDefinitions)2493 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
2494   EXPECT_EQ("#define A    \\\n"
2495             "  c;         \\\n"
2496             "  e;\n"
2497             "f;",
2498             format("#define A c; e;\n"
2499                    "f;",
2500                    getLLVMStyleWithColumns(14)));
2501 }
2502 
TEST_F(FormatTest,LayoutRemainingTokens)2503 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
2504 
TEST_F(FormatTest,AlwaysFormatsEntireMacroDefinitions)2505 TEST_F(FormatTest, AlwaysFormatsEntireMacroDefinitions) {
2506   EXPECT_EQ("int  i;\n"
2507             "#define A \\\n"
2508             "  int i;  \\\n"
2509             "  int j\n"
2510             "int  k;",
2511             format("int  i;\n"
2512                    "#define A  \\\n"
2513                    " int   i    ;  \\\n"
2514                    " int   j\n"
2515                    "int  k;",
2516                    8, 0, getGoogleStyle())); // 8: position of "#define".
2517   EXPECT_EQ("int  i;\n"
2518             "#define A \\\n"
2519             "  int i;  \\\n"
2520             "  int j\n"
2521             "int  k;",
2522             format("int  i;\n"
2523                    "#define A  \\\n"
2524                    " int   i    ;  \\\n"
2525                    " int   j\n"
2526                    "int  k;",
2527                    45, 0, getGoogleStyle())); // 45: position of "j".
2528 }
2529 
TEST_F(FormatTest,MacroDefinitionInsideStatement)2530 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
2531   EXPECT_EQ("int x,\n"
2532             "#define A\n"
2533             "    y;",
2534             format("int x,\n#define A\ny;"));
2535 }
2536 
TEST_F(FormatTest,HashInMacroDefinition)2537 TEST_F(FormatTest, HashInMacroDefinition) {
2538   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
2539   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
2540   verifyFormat("#define A  \\\n"
2541                "  {        \\\n"
2542                "    f(#c); \\\n"
2543                "  }",
2544                getLLVMStyleWithColumns(11));
2545 
2546   verifyFormat("#define A(X)         \\\n"
2547                "  void function##X()",
2548                getLLVMStyleWithColumns(22));
2549 
2550   verifyFormat("#define A(a, b, c)   \\\n"
2551                "  void a##b##c()",
2552                getLLVMStyleWithColumns(22));
2553 
2554   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
2555 }
2556 
TEST_F(FormatTest,RespectWhitespaceInMacroDefinitions)2557 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
2558   EXPECT_EQ("#define A (x)", format("#define A (x)"));
2559   EXPECT_EQ("#define A(x)", format("#define A(x)"));
2560 }
2561 
TEST_F(FormatTest,EmptyLinesInMacroDefinitions)2562 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
2563   EXPECT_EQ("#define A b;", format("#define A \\\n"
2564                                    "          \\\n"
2565                                    "  b;",
2566                                    getLLVMStyleWithColumns(25)));
2567   EXPECT_EQ("#define A \\\n"
2568             "          \\\n"
2569             "  a;      \\\n"
2570             "  b;",
2571             format("#define A \\\n"
2572                    "          \\\n"
2573                    "  a;      \\\n"
2574                    "  b;",
2575                    getLLVMStyleWithColumns(11)));
2576   EXPECT_EQ("#define A \\\n"
2577             "  a;      \\\n"
2578             "          \\\n"
2579             "  b;",
2580             format("#define A \\\n"
2581                    "  a;      \\\n"
2582                    "          \\\n"
2583                    "  b;",
2584                    getLLVMStyleWithColumns(11)));
2585 }
2586 
TEST_F(FormatTest,MacroDefinitionsWithIncompleteCode)2587 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
2588   verifyFormat("#define A :");
2589   verifyFormat("#define SOMECASES  \\\n"
2590                "  case 1:          \\\n"
2591                "  case 2\n",
2592                getLLVMStyleWithColumns(20));
2593   verifyFormat("#define A template <typename T>");
2594   verifyFormat("#define STR(x) #x\n"
2595                "f(STR(this_is_a_string_literal{));");
2596   verifyFormat("#pragma omp threadprivate( \\\n"
2597                "    y)), // expected-warning",
2598                getLLVMStyleWithColumns(28));
2599 }
2600 
TEST_F(FormatTest,MacrosWithoutTrailingSemicolon)2601 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
2602   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
2603   EXPECT_EQ("class A : public QObject {\n"
2604             "  Q_OBJECT\n"
2605             "\n"
2606             "  A() {}\n"
2607             "};",
2608             format("class A  :  public QObject {\n"
2609                    "     Q_OBJECT\n"
2610                    "\n"
2611                    "  A() {\n}\n"
2612                    "}  ;"));
2613   EXPECT_EQ("SOME_MACRO\n"
2614             "namespace {\n"
2615             "void f();\n"
2616             "}",
2617             format("SOME_MACRO\n"
2618                    "  namespace    {\n"
2619                    "void   f(  );\n"
2620                    "}"));
2621   // Only if the identifier contains at least 5 characters.
2622   EXPECT_EQ("HTTP f();",
2623             format("HTTP\nf();"));
2624   EXPECT_EQ("MACRO\nf();",
2625             format("MACRO\nf();"));
2626   // Only if everything is upper case.
2627   EXPECT_EQ("class A : public QObject {\n"
2628             "  Q_Object A() {}\n"
2629             "};",
2630             format("class A  :  public QObject {\n"
2631                    "     Q_Object\n"
2632                    "  A() {\n}\n"
2633                    "}  ;"));
2634 
2635   // Only if the next line can actually start an unwrapped line.
2636   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
2637             format("SOME_WEIRD_LOG_MACRO\n"
2638                    "<< SomeThing;"));
2639 
2640   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
2641                "(n, buffers))\n", getChromiumStyle(FormatStyle::LK_Cpp));
2642 }
2643 
TEST_F(FormatTest,MacroCallsWithoutTrailingSemicolon)2644 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
2645   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
2646             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
2647             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
2648             "class X {};\n"
2649             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
2650             "int *createScopDetectionPass() { return 0; }",
2651             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
2652                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
2653                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
2654                    "  class X {};\n"
2655                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
2656                    "  int *createScopDetectionPass() { return 0; }"));
2657   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
2658   // braces, so that inner block is indented one level more.
2659   EXPECT_EQ("int q() {\n"
2660             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
2661             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
2662             "  IPC_END_MESSAGE_MAP()\n"
2663             "}",
2664             format("int q() {\n"
2665                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
2666                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
2667                    "  IPC_END_MESSAGE_MAP()\n"
2668                    "}"));
2669 
2670   // Same inside macros.
2671   EXPECT_EQ("#define LIST(L) \\\n"
2672             "  L(A)          \\\n"
2673             "  L(B)          \\\n"
2674             "  L(C)",
2675             format("#define LIST(L) \\\n"
2676                    "  L(A) \\\n"
2677                    "  L(B) \\\n"
2678                    "  L(C)",
2679                    getGoogleStyle()));
2680 
2681   // These must not be recognized as macros.
2682   EXPECT_EQ("int q() {\n"
2683             "  f(x);\n"
2684             "  f(x) {}\n"
2685             "  f(x)->g();\n"
2686             "  f(x)->*g();\n"
2687             "  f(x).g();\n"
2688             "  f(x) = x;\n"
2689             "  f(x) += x;\n"
2690             "  f(x) -= x;\n"
2691             "  f(x) *= x;\n"
2692             "  f(x) /= x;\n"
2693             "  f(x) %= x;\n"
2694             "  f(x) &= x;\n"
2695             "  f(x) |= x;\n"
2696             "  f(x) ^= x;\n"
2697             "  f(x) >>= x;\n"
2698             "  f(x) <<= x;\n"
2699             "  f(x)[y].z();\n"
2700             "  LOG(INFO) << x;\n"
2701             "  ifstream(x) >> x;\n"
2702             "}\n",
2703             format("int q() {\n"
2704                    "  f(x)\n;\n"
2705                    "  f(x)\n {}\n"
2706                    "  f(x)\n->g();\n"
2707                    "  f(x)\n->*g();\n"
2708                    "  f(x)\n.g();\n"
2709                    "  f(x)\n = x;\n"
2710                    "  f(x)\n += x;\n"
2711                    "  f(x)\n -= x;\n"
2712                    "  f(x)\n *= x;\n"
2713                    "  f(x)\n /= x;\n"
2714                    "  f(x)\n %= x;\n"
2715                    "  f(x)\n &= x;\n"
2716                    "  f(x)\n |= x;\n"
2717                    "  f(x)\n ^= x;\n"
2718                    "  f(x)\n >>= x;\n"
2719                    "  f(x)\n <<= x;\n"
2720                    "  f(x)\n[y].z();\n"
2721                    "  LOG(INFO)\n << x;\n"
2722                    "  ifstream(x)\n >> x;\n"
2723                    "}\n"));
2724   EXPECT_EQ("int q() {\n"
2725             "  F(x)\n"
2726             "  if (1) {\n"
2727             "  }\n"
2728             "  F(x)\n"
2729             "  while (1) {\n"
2730             "  }\n"
2731             "  F(x)\n"
2732             "  G(x);\n"
2733             "  F(x)\n"
2734             "  try {\n"
2735             "    Q();\n"
2736             "  } catch (...) {\n"
2737             "  }\n"
2738             "}\n",
2739             format("int q() {\n"
2740                    "F(x)\n"
2741                    "if (1) {}\n"
2742                    "F(x)\n"
2743                    "while (1) {}\n"
2744                    "F(x)\n"
2745                    "G(x);\n"
2746                    "F(x)\n"
2747                    "try { Q(); } catch (...) {}\n"
2748                    "}\n"));
2749   EXPECT_EQ("class A {\n"
2750             "  A() : t(0) {}\n"
2751             "  A(int i) noexcept() : {}\n"
2752             "  A(X x)\n" // FIXME: function-level try blocks are broken.
2753             "  try : t(0) {\n"
2754             "  } catch (...) {\n"
2755             "  }\n"
2756             "};",
2757             format("class A {\n"
2758                    "  A()\n : t(0) {}\n"
2759                    "  A(int i)\n noexcept() : {}\n"
2760                    "  A(X x)\n"
2761                    "  try : t(0) {} catch (...) {}\n"
2762                    "};"));
2763   EXPECT_EQ(
2764       "class SomeClass {\n"
2765       "public:\n"
2766       "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2767       "};",
2768       format("class SomeClass {\n"
2769              "public:\n"
2770              "  SomeClass()\n"
2771              "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2772              "};"));
2773   EXPECT_EQ(
2774       "class SomeClass {\n"
2775       "public:\n"
2776       "  SomeClass()\n"
2777       "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2778       "};",
2779       format("class SomeClass {\n"
2780              "public:\n"
2781              "  SomeClass()\n"
2782              "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2783              "};", getLLVMStyleWithColumns(40)));
2784 }
2785 
TEST_F(FormatTest,LayoutMacroDefinitionsStatementsSpanningBlocks)2786 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
2787   verifyFormat("#define A \\\n"
2788                "  f({     \\\n"
2789                "    g();  \\\n"
2790                "  });", getLLVMStyleWithColumns(11));
2791 }
2792 
TEST_F(FormatTest,IndentPreprocessorDirectivesAtZero)2793 TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
2794   EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
2795 }
2796 
TEST_F(FormatTest,FormatHashIfNotAtStartOfLine)2797 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
2798   verifyFormat("{\n  { a #c; }\n}");
2799 }
2800 
TEST_F(FormatTest,FormatUnbalancedStructuralElements)2801 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
2802   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
2803             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
2804   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
2805             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
2806 }
2807 
TEST_F(FormatTest,EscapedNewlineAtStartOfToken)2808 TEST_F(FormatTest, EscapedNewlineAtStartOfToken) {
2809   EXPECT_EQ(
2810       "#define A \\\n  int i;  \\\n  int j;",
2811       format("#define A \\\nint i;\\\n  int j;", getLLVMStyleWithColumns(11)));
2812   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
2813 }
2814 
TEST_F(FormatTest,NoEscapedNewlineHandlingInBlockComments)2815 TEST_F(FormatTest, NoEscapedNewlineHandlingInBlockComments) {
2816   EXPECT_EQ("/* \\  \\  \\\n*/", format("\\\n/* \\  \\  \\\n*/"));
2817 }
2818 
TEST_F(FormatTest,DontCrashOnBlockComments)2819 TEST_F(FormatTest, DontCrashOnBlockComments) {
2820   EXPECT_EQ(
2821       "int xxxxxxxxx; /* "
2822       "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\n"
2823       "zzzzzz\n"
2824       "0*/",
2825       format("int xxxxxxxxx;                          /* "
2826              "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy zzzzzz\n"
2827              "0*/"));
2828 }
2829 
TEST_F(FormatTest,CalculateSpaceOnConsecutiveLinesInMacro)2830 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
2831   verifyFormat("#define A \\\n"
2832                "  int v(  \\\n"
2833                "      a); \\\n"
2834                "  int i;",
2835                getLLVMStyleWithColumns(11));
2836 }
2837 
TEST_F(FormatTest,MixingPreprocessorDirectivesAndNormalCode)2838 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
2839   EXPECT_EQ(
2840       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
2841       "                      \\\n"
2842       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
2843       "\n"
2844       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
2845       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
2846       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
2847              "\\\n"
2848              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
2849              "  \n"
2850              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
2851              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
2852 }
2853 
TEST_F(FormatTest,LayoutStatementsAroundPreprocessorDirectives)2854 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
2855   EXPECT_EQ("int\n"
2856             "#define A\n"
2857             "    a;",
2858             format("int\n#define A\na;"));
2859   verifyFormat("functionCallTo(\n"
2860                "    someOtherFunction(\n"
2861                "        withSomeParameters, whichInSequence,\n"
2862                "        areLongerThanALine(andAnotherCall,\n"
2863                "#define A B\n"
2864                "                           withMoreParamters,\n"
2865                "                           whichStronglyInfluenceTheLayout),\n"
2866                "        andMoreParameters),\n"
2867                "    trailing);",
2868                getLLVMStyleWithColumns(69));
2869   verifyFormat("Foo::Foo()\n"
2870                "#ifdef BAR\n"
2871                "    : baz(0)\n"
2872                "#endif\n"
2873                "{\n"
2874                "}");
2875   verifyFormat("void f() {\n"
2876                "  if (true)\n"
2877                "#ifdef A\n"
2878                "    f(42);\n"
2879                "  x();\n"
2880                "#else\n"
2881                "    g();\n"
2882                "  x();\n"
2883                "#endif\n"
2884                "}");
2885   verifyFormat("void f(param1, param2,\n"
2886                "       param3,\n"
2887                "#ifdef A\n"
2888                "       param4(param5,\n"
2889                "#ifdef A1\n"
2890                "              param6,\n"
2891                "#ifdef A2\n"
2892                "              param7),\n"
2893                "#else\n"
2894                "              param8),\n"
2895                "       param9,\n"
2896                "#endif\n"
2897                "       param10,\n"
2898                "#endif\n"
2899                "       param11)\n"
2900                "#else\n"
2901                "       param12)\n"
2902                "#endif\n"
2903                "{\n"
2904                "  x();\n"
2905                "}",
2906                getLLVMStyleWithColumns(28));
2907   verifyFormat("#if 1\n"
2908                "int i;");
2909   verifyFormat(
2910       "#if 1\n"
2911       "#endif\n"
2912       "#if 1\n"
2913       "#else\n"
2914       "#endif\n");
2915   verifyFormat("DEBUG({\n"
2916                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2917                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2918                "});\n"
2919                "#if a\n"
2920                "#else\n"
2921                "#endif");
2922 }
2923 
TEST_F(FormatTest,GraciouslyHandleIncorrectPreprocessorConditions)2924 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
2925   verifyFormat("#endif\n"
2926                "#if B");
2927 }
2928 
TEST_F(FormatTest,FormatsJoinedLinesOnSubsequentRuns)2929 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
2930   FormatStyle SingleLine = getLLVMStyle();
2931   SingleLine.AllowShortIfStatementsOnASingleLine = true;
2932   verifyFormat(
2933       "#if 0\n"
2934       "#elif 1\n"
2935       "#endif\n"
2936       "void foo() {\n"
2937       "  if (test) foo2();\n"
2938       "}",
2939       SingleLine);
2940 }
2941 
TEST_F(FormatTest,LayoutBlockInsideParens)2942 TEST_F(FormatTest, LayoutBlockInsideParens) {
2943   EXPECT_EQ("functionCall({ int i; });", format(" functionCall ( {int i;} );"));
2944   EXPECT_EQ("functionCall({\n"
2945             "  int i;\n"
2946             "  int j;\n"
2947             "});",
2948             format(" functionCall ( {int i;int j;} );"));
2949   EXPECT_EQ("functionCall({\n"
2950             "  int i;\n"
2951             "  int j;\n"
2952             "}, aaaa, bbbb, cccc);",
2953             format(" functionCall ( {int i;int j;},  aaaa,   bbbb, cccc);"));
2954   EXPECT_EQ("functionCall(\n"
2955             "    {\n"
2956             "      int i;\n"
2957             "      int j;\n"
2958             "    },\n"
2959             "    aaaa, bbbb, // comment\n"
2960             "    cccc);",
2961             format(" functionCall ( {int i;int j;},  aaaa,   bbbb, // comment\n"
2962                    "cccc);"));
2963   EXPECT_EQ("functionCall(aaaa, bbbb, { int i; });",
2964             format(" functionCall (aaaa,   bbbb, {int i;});"));
2965   EXPECT_EQ("functionCall(aaaa, bbbb, {\n"
2966             "  int i;\n"
2967             "  int j;\n"
2968             "});",
2969             format(" functionCall (aaaa,   bbbb, {int i;int j;});"));
2970   EXPECT_EQ("functionCall(aaaa, bbbb, { int i; });",
2971             format(" functionCall (aaaa,   bbbb, {int i;});"));
2972   verifyFormat(
2973       "Aaa(\n"  // FIXME: There shouldn't be a linebreak here.
2974       "    {\n"
2975       "      int i; // break\n"
2976       "    },\n"
2977       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
2978       "                                     ccccccccccccccccc));");
2979   verifyFormat("DEBUG({\n"
2980                "  if (a)\n"
2981                "    f();\n"
2982                "});");
2983 }
2984 
TEST_F(FormatTest,LayoutBlockInsideStatement)2985 TEST_F(FormatTest, LayoutBlockInsideStatement) {
2986   EXPECT_EQ("SOME_MACRO { int i; }\n"
2987             "int i;",
2988             format("  SOME_MACRO  {int i;}  int i;"));
2989 }
2990 
TEST_F(FormatTest,LayoutNestedBlocks)2991 TEST_F(FormatTest, LayoutNestedBlocks) {
2992   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
2993                "  struct s {\n"
2994                "    int i;\n"
2995                "  };\n"
2996                "  s kBitsToOs[] = {{10}};\n"
2997                "  for (int i = 0; i < 10; ++i)\n"
2998                "    return;\n"
2999                "}");
3000   verifyFormat("call(parameter, {\n"
3001                "  something();\n"
3002                "  // Comment using all columns.\n"
3003                "  somethingelse();\n"
3004                "});",
3005                getLLVMStyleWithColumns(40));
3006   verifyFormat("DEBUG( //\n"
3007                "    { f(); }, a);");
3008   verifyFormat("DEBUG( //\n"
3009                "    {\n"
3010                "      f(); //\n"
3011                "    },\n"
3012                "    a);");
3013 
3014   EXPECT_EQ("call(parameter, {\n"
3015             "  something();\n"
3016             "  // Comment too\n"
3017             "  // looooooooooong.\n"
3018             "  somethingElse();\n"
3019             "});",
3020             format("call(parameter, {\n"
3021                    "  something();\n"
3022                    "  // Comment too looooooooooong.\n"
3023                    "  somethingElse();\n"
3024                    "});",
3025                    getLLVMStyleWithColumns(29)));
3026   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
3027   EXPECT_EQ("DEBUG({ // comment\n"
3028             "  int i;\n"
3029             "});",
3030             format("DEBUG({ // comment\n"
3031                    "int  i;\n"
3032                    "});"));
3033   EXPECT_EQ("DEBUG({\n"
3034             "  int i;\n"
3035             "\n"
3036             "  // comment\n"
3037             "  int j;\n"
3038             "});",
3039             format("DEBUG({\n"
3040                    "  int  i;\n"
3041                    "\n"
3042                    "  // comment\n"
3043                    "  int  j;\n"
3044                    "});"));
3045 
3046   verifyFormat("DEBUG({\n"
3047                "  if (a)\n"
3048                "    return;\n"
3049                "});");
3050   verifyGoogleFormat("DEBUG({\n"
3051                      "  if (a) return;\n"
3052                      "});");
3053   FormatStyle Style = getGoogleStyle();
3054   Style.ColumnLimit = 45;
3055   verifyFormat("Debug(aaaaa, {\n"
3056                "  if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
3057                "}, a);",
3058                Style);
3059 }
3060 
TEST_F(FormatTest,IndividualStatementsOfNestedBlocks)3061 TEST_F(FormatTest, IndividualStatementsOfNestedBlocks) {
3062   EXPECT_EQ("DEBUG({\n"
3063             "  int i;\n"
3064             "  int        j;\n"
3065             "});",
3066             format("DEBUG(   {\n"
3067                    "  int        i;\n"
3068                    "  int        j;\n"
3069                    "}   )  ;",
3070                    20, 1, getLLVMStyle()));
3071   EXPECT_EQ("DEBUG(   {\n"
3072             "  int        i;\n"
3073             "  int j;\n"
3074             "}   )  ;",
3075             format("DEBUG(   {\n"
3076                    "  int        i;\n"
3077                    "  int        j;\n"
3078                    "}   )  ;",
3079                    41, 1, getLLVMStyle()));
3080   EXPECT_EQ("DEBUG(   {\n"
3081             "    int        i;\n"
3082             "    int j;\n"
3083             "}   )  ;",
3084             format("DEBUG(   {\n"
3085                    "    int        i;\n"
3086                    "    int        j;\n"
3087                    "}   )  ;",
3088                    41, 1, getLLVMStyle()));
3089   EXPECT_EQ("DEBUG({\n"
3090             "  int i;\n"
3091             "  int j;\n"
3092             "});",
3093             format("DEBUG(   {\n"
3094                    "    int        i;\n"
3095                    "    int        j;\n"
3096                    "}   )  ;",
3097                    20, 1, getLLVMStyle()));
3098 
3099   EXPECT_EQ("Debug({\n"
3100             "        if (aaaaaaaaaaaaaaaaaaaaaaaa)\n"
3101             "          return;\n"
3102             "      },\n"
3103             "      a);",
3104             format("Debug({\n"
3105                    "        if (aaaaaaaaaaaaaaaaaaaaaaaa)\n"
3106                    "             return;\n"
3107                    "      },\n"
3108                    "      a);",
3109                    50, 1, getLLVMStyle()));
3110   EXPECT_EQ("DEBUG({\n"
3111             "  DEBUG({\n"
3112             "    int a;\n"
3113             "    int b;\n"
3114             "  }) ;\n"
3115             "});",
3116             format("DEBUG({\n"
3117                    "  DEBUG({\n"
3118                    "    int a;\n"
3119                    "    int    b;\n" // Format this line only.
3120                    "  }) ;\n"        // Don't touch this line.
3121                    "});",
3122                    35, 0, getLLVMStyle()));
3123   EXPECT_EQ("DEBUG({\n"
3124             "  int a; //\n"
3125             "});",
3126             format("DEBUG({\n"
3127                    "    int a; //\n"
3128                    "});",
3129                    0, 0, getLLVMStyle()));
3130 }
3131 
TEST_F(FormatTest,PutEmptyBlocksIntoOneLine)3132 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
3133   EXPECT_EQ("{}", format("{}"));
3134   verifyFormat("enum E {};");
3135   verifyFormat("enum E {}");
3136 }
3137 
3138 //===----------------------------------------------------------------------===//
3139 // Line break tests.
3140 //===----------------------------------------------------------------------===//
3141 
TEST_F(FormatTest,PreventConfusingIndents)3142 TEST_F(FormatTest, PreventConfusingIndents) {
3143   verifyFormat(
3144       "void f() {\n"
3145       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
3146       "                         parameter, parameter, parameter)),\n"
3147       "                     SecondLongCall(parameter));\n"
3148       "}");
3149   verifyFormat(
3150       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3151       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
3152       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3153       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
3154   verifyFormat(
3155       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3156       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
3157       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3158       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
3159   verifyFormat(
3160       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
3161       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
3162       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
3163       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
3164   verifyFormat("int a = bbbb && ccc && fffff(\n"
3165                "#define A Just forcing a new line\n"
3166                "                           ddd);");
3167 }
3168 
TEST_F(FormatTest,LineBreakingInBinaryExpressions)3169 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
3170   verifyFormat(
3171       "bool aaaaaaa =\n"
3172       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
3173       "    bbbbbbbb();");
3174   verifyFormat(
3175       "bool aaaaaaa =\n"
3176       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
3177       "    bbbbbbbb();");
3178 
3179   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
3180                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
3181                "    ccccccccc == ddddddddddd;");
3182   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
3183                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
3184                "    ccccccccc == ddddddddddd;");
3185   verifyFormat(
3186       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
3187       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
3188       "    ccccccccc == ddddddddddd;");
3189 
3190   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
3191                "                 aaaaaa) &&\n"
3192                "         bbbbbb && cccccc;");
3193   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
3194                "                 aaaaaa) >>\n"
3195                "         bbbbbb;");
3196   verifyFormat("Whitespaces.addUntouchableComment(\n"
3197                "    SourceMgr.getSpellingColumnNumber(\n"
3198                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
3199                "    1);");
3200 
3201   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3202                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
3203                "    cccccc) {\n}");
3204   verifyFormat("b = a &&\n"
3205                "    // Comment\n"
3206                "    b.c && d;");
3207 
3208   // If the LHS of a comparison is not a binary expression itself, the
3209   // additional linebreak confuses many people.
3210   verifyFormat(
3211       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3212       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
3213       "}");
3214   verifyFormat(
3215       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3216       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
3217       "}");
3218   verifyFormat(
3219       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
3220       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
3221       "}");
3222   // Even explicit parentheses stress the precedence enough to make the
3223   // additional break unnecessary.
3224   verifyFormat(
3225       "if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3226       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
3227       "}");
3228   // This cases is borderline, but with the indentation it is still readable.
3229   verifyFormat(
3230       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3231       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3232       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
3233       "}",
3234       getLLVMStyleWithColumns(75));
3235 
3236   // If the LHS is a binary expression, we should still use the additional break
3237   // as otherwise the formatting hides the operator precedence.
3238   verifyFormat(
3239       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3240       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3241       "    5) {\n"
3242       "}");
3243 
3244   FormatStyle OnePerLine = getLLVMStyle();
3245   OnePerLine.BinPackParameters = false;
3246   verifyFormat(
3247       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3248       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3249       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
3250       OnePerLine);
3251 }
3252 
TEST_F(FormatTest,ExpressionIndentation)3253 TEST_F(FormatTest, ExpressionIndentation) {
3254   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3255                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3256                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3257                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3258                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
3259                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
3260                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3261                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
3262                "                 ccccccccccccccccccccccccccccccccccccccccc;");
3263   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3264                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3265                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3266                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
3267   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3268                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3269                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3270                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
3271   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3272                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3273                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3274                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
3275   verifyFormat("if () {\n"
3276                "} else if (aaaaa &&\n"
3277                "           bbbbb > // break\n"
3278                "               ccccc) {\n"
3279                "}");
3280 
3281   // Presence of a trailing comment used to change indentation of b.
3282   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
3283                "       b;\n"
3284                "return aaaaaaaaaaaaaaaaaaa +\n"
3285                "       b; //",
3286                getLLVMStyleWithColumns(30));
3287 }
3288 
TEST_F(FormatTest,ExpressionIndentationBreakingBeforeOperators)3289 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
3290   // Not sure what the best system is here. Like this, the LHS can be found
3291   // immediately above an operator (everything with the same or a higher
3292   // indent). The RHS is aligned right of the operator and so compasses
3293   // everything until something with the same indent as the operator is found.
3294   // FIXME: Is this a good system?
3295   FormatStyle Style = getLLVMStyle();
3296   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
3297   verifyFormat(
3298       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3299       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3300       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3301       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3302       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3303       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3304       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3305       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3306       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
3307       Style);
3308   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3309                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3310                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3311                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
3312                Style);
3313   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3314                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3315                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3316                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
3317                Style);
3318   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3319                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3320                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3321                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
3322                Style);
3323   verifyFormat("if () {\n"
3324                "} else if (aaaaa\n"
3325                "           && bbbbb // break\n"
3326                "                  > ccccc) {\n"
3327                "}",
3328                Style);
3329   verifyFormat("return (a)\n"
3330                "       // comment\n"
3331                "       + b;",
3332                Style);
3333   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3334                "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3335                "             + cc;",
3336                Style);
3337 
3338   // Forced by comments.
3339   verifyFormat(
3340       "unsigned ContentSize =\n"
3341       "    sizeof(int16_t)   // DWARF ARange version number\n"
3342       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
3343       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
3344       "    + sizeof(int8_t); // Segment Size (in bytes)");
3345 
3346   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
3347                "       == boost::fusion::at_c<1>(iiii).second;",
3348                Style);
3349 
3350   Style.ColumnLimit = 60;
3351   verifyFormat("zzzzzzzzzz\n"
3352                "    = bbbbbbbbbbbbbbbbb\n"
3353                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
3354                Style);
3355 }
3356 
TEST_F(FormatTest,NoOperandAlignment)3357 TEST_F(FormatTest, NoOperandAlignment) {
3358   FormatStyle Style = getLLVMStyle();
3359   Style.AlignOperands = false;
3360   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
3361   verifyFormat(
3362       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3363       "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3364       "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3365       "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3366       "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3367       "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3368       "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3369       "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3370       "        > ccccccccccccccccccccccccccccccccccccccccc;",
3371       Style);
3372 
3373   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3374                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3375                "    + cc;",
3376                Style);
3377   verifyFormat("int a = aa\n"
3378                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3379                "        * cccccccccccccccccccccccccccccccccccc;",
3380                Style);
3381 
3382   Style.AlignAfterOpenBracket = false;
3383   verifyFormat("return (a > b\n"
3384                "    // comment1\n"
3385                "    // comment2\n"
3386                "    || c);",
3387                Style);
3388 }
3389 
TEST_F(FormatTest,BreakingBeforeNonAssigmentOperators)3390 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
3391   FormatStyle Style = getLLVMStyle();
3392   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
3393   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3394                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3395                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
3396                Style);
3397 }
3398 
TEST_F(FormatTest,ConstructorInitializers)3399 TEST_F(FormatTest, ConstructorInitializers) {
3400   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
3401   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
3402                getLLVMStyleWithColumns(45));
3403   verifyFormat("Constructor()\n"
3404                "    : Inttializer(FitsOnTheLine) {}",
3405                getLLVMStyleWithColumns(44));
3406   verifyFormat("Constructor()\n"
3407                "    : Inttializer(FitsOnTheLine) {}",
3408                getLLVMStyleWithColumns(43));
3409 
3410   verifyFormat(
3411       "SomeClass::Constructor()\n"
3412       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
3413 
3414   verifyFormat(
3415       "SomeClass::Constructor()\n"
3416       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3417       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
3418   verifyFormat(
3419       "SomeClass::Constructor()\n"
3420       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3421       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
3422 
3423   verifyFormat("Constructor()\n"
3424                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3425                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3426                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3427                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
3428 
3429   verifyFormat("Constructor()\n"
3430                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3431                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
3432 
3433   verifyFormat("Constructor(int Parameter = 0)\n"
3434                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
3435                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
3436   verifyFormat("Constructor()\n"
3437                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
3438                "}",
3439                getLLVMStyleWithColumns(60));
3440   verifyFormat("Constructor()\n"
3441                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3442                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
3443 
3444   // Here a line could be saved by splitting the second initializer onto two
3445   // lines, but that is not desirable.
3446   verifyFormat("Constructor()\n"
3447                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
3448                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
3449                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
3450 
3451   FormatStyle OnePerLine = getLLVMStyle();
3452   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
3453   verifyFormat("SomeClass::Constructor()\n"
3454                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3455                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3456                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
3457                OnePerLine);
3458   verifyFormat("SomeClass::Constructor()\n"
3459                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
3460                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3461                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
3462                OnePerLine);
3463   verifyFormat("MyClass::MyClass(int var)\n"
3464                "    : some_var_(var),            // 4 space indent\n"
3465                "      some_other_var_(var + 1) { // lined up\n"
3466                "}",
3467                OnePerLine);
3468   verifyFormat("Constructor()\n"
3469                "    : aaaaa(aaaaaa),\n"
3470                "      aaaaa(aaaaaa),\n"
3471                "      aaaaa(aaaaaa),\n"
3472                "      aaaaa(aaaaaa),\n"
3473                "      aaaaa(aaaaaa) {}",
3474                OnePerLine);
3475   verifyFormat("Constructor()\n"
3476                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
3477                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
3478                OnePerLine);
3479 
3480   EXPECT_EQ("Constructor()\n"
3481             "    : // Comment forcing unwanted break.\n"
3482             "      aaaa(aaaa) {}",
3483             format("Constructor() :\n"
3484                    "    // Comment forcing unwanted break.\n"
3485                    "    aaaa(aaaa) {}"));
3486 }
3487 
TEST_F(FormatTest,MemoizationTests)3488 TEST_F(FormatTest, MemoizationTests) {
3489   // This breaks if the memoization lookup does not take \c Indent and
3490   // \c LastSpace into account.
3491   verifyFormat(
3492       "extern CFRunLoopTimerRef\n"
3493       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
3494       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
3495       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
3496       "                     CFRunLoopTimerContext *context) {}");
3497 
3498   // Deep nesting somewhat works around our memoization.
3499   verifyFormat(
3500       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3501       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3502       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3503       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3504       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
3505       getLLVMStyleWithColumns(65));
3506   verifyFormat(
3507       "aaaaa(\n"
3508       "    aaaaa,\n"
3509       "    aaaaa(\n"
3510       "        aaaaa,\n"
3511       "        aaaaa(\n"
3512       "            aaaaa,\n"
3513       "            aaaaa(\n"
3514       "                aaaaa,\n"
3515       "                aaaaa(\n"
3516       "                    aaaaa,\n"
3517       "                    aaaaa(\n"
3518       "                        aaaaa,\n"
3519       "                        aaaaa(\n"
3520       "                            aaaaa,\n"
3521       "                            aaaaa(\n"
3522       "                                aaaaa,\n"
3523       "                                aaaaa(\n"
3524       "                                    aaaaa,\n"
3525       "                                    aaaaa(\n"
3526       "                                        aaaaa,\n"
3527       "                                        aaaaa(\n"
3528       "                                            aaaaa,\n"
3529       "                                            aaaaa(\n"
3530       "                                                aaaaa,\n"
3531       "                                                aaaaa))))))))))));",
3532       getLLVMStyleWithColumns(65));
3533   verifyFormat(
3534       "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"
3535       "                                  a),\n"
3536       "                                a),\n"
3537       "                              a),\n"
3538       "                            a),\n"
3539       "                          a),\n"
3540       "                        a),\n"
3541       "                      a),\n"
3542       "                    a),\n"
3543       "                  a),\n"
3544       "                a),\n"
3545       "              a),\n"
3546       "            a),\n"
3547       "          a),\n"
3548       "        a),\n"
3549       "      a),\n"
3550       "    a),\n"
3551       "  a)",
3552       getLLVMStyleWithColumns(65));
3553 
3554   // This test takes VERY long when memoization is broken.
3555   FormatStyle OnePerLine = getLLVMStyle();
3556   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
3557   OnePerLine.BinPackParameters = false;
3558   std::string input = "Constructor()\n"
3559                       "    : aaaa(a,\n";
3560   for (unsigned i = 0, e = 80; i != e; ++i) {
3561     input += "           a,\n";
3562   }
3563   input += "           a) {}";
3564   verifyFormat(input, OnePerLine);
3565 }
3566 
TEST_F(FormatTest,BreaksAsHighAsPossible)3567 TEST_F(FormatTest, BreaksAsHighAsPossible) {
3568   verifyFormat(
3569       "void f() {\n"
3570       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
3571       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
3572       "    f();\n"
3573       "}");
3574   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
3575                "    Intervals[i - 1].getRange().getLast()) {\n}");
3576 }
3577 
TEST_F(FormatTest,BreaksFunctionDeclarations)3578 TEST_F(FormatTest, BreaksFunctionDeclarations) {
3579   // Principially, we break function declarations in a certain order:
3580   // 1) break amongst arguments.
3581   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
3582                "                              Cccccccccccccc cccccccccccccc);");
3583   verifyFormat(
3584       "template <class TemplateIt>\n"
3585       "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
3586       "                            TemplateIt *stop) {}");
3587 
3588   // 2) break after return type.
3589   verifyFormat(
3590       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3591       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
3592       getGoogleStyle());
3593 
3594   // 3) break after (.
3595   verifyFormat(
3596       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
3597       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
3598       getGoogleStyle());
3599 
3600   // 4) break before after nested name specifiers.
3601   verifyFormat(
3602       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3603       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
3604       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
3605       getGoogleStyle());
3606 
3607   // However, there are exceptions, if a sufficient amount of lines can be
3608   // saved.
3609   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
3610   // more adjusting.
3611   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
3612                "                                  Cccccccccccccc cccccccccc,\n"
3613                "                                  Cccccccccccccc cccccccccc,\n"
3614                "                                  Cccccccccccccc cccccccccc,\n"
3615                "                                  Cccccccccccccc cccccccccc);");
3616   verifyFormat(
3617       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3618       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3619       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3620       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
3621       getGoogleStyle());
3622   verifyFormat(
3623       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
3624       "                                          Cccccccccccccc cccccccccc,\n"
3625       "                                          Cccccccccccccc cccccccccc,\n"
3626       "                                          Cccccccccccccc cccccccccc,\n"
3627       "                                          Cccccccccccccc cccccccccc,\n"
3628       "                                          Cccccccccccccc cccccccccc,\n"
3629       "                                          Cccccccccccccc cccccccccc);");
3630   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
3631                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3632                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3633                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3634                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
3635 
3636   // Break after multi-line parameters.
3637   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3638                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3639                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3640                "    bbbb bbbb);");
3641   verifyFormat("void SomeLoooooooooooongFunction(\n"
3642                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
3643                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3644                "    int bbbbbbbbbbbbb);");
3645 
3646   // Treat overloaded operators like other functions.
3647   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
3648                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
3649   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
3650                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
3651   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
3652                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
3653   verifyGoogleFormat(
3654       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
3655       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
3656   verifyGoogleFormat(
3657       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
3658       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
3659   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3660                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
3661   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
3662                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
3663   verifyGoogleFormat(
3664       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
3665       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3666       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
3667 }
3668 
TEST_F(FormatTest,TrailingReturnType)3669 TEST_F(FormatTest, TrailingReturnType) {
3670   verifyFormat("auto foo() -> int;\n");
3671   verifyFormat("struct S {\n"
3672                "  auto bar() const -> int;\n"
3673                "};");
3674   verifyFormat("template <size_t Order, typename T>\n"
3675                "auto load_img(const std::string &filename)\n"
3676                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
3677   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
3678                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
3679   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
3680 
3681   // Not trailing return types.
3682   verifyFormat("void f() { auto a = b->c(); }");
3683 }
3684 
TEST_F(FormatTest,BreaksFunctionDeclarationsWithTrailingTokens)3685 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
3686   // Avoid breaking before trailing 'const' or other trailing annotations, if
3687   // they are not function-like.
3688   FormatStyle Style = getGoogleStyle();
3689   Style.ColumnLimit = 47;
3690   verifyFormat("void someLongFunction(\n"
3691                "    int someLoooooooooooooongParameter) const {\n}",
3692                getLLVMStyleWithColumns(47));
3693   verifyFormat("LoooooongReturnType\n"
3694                "someLoooooooongFunction() const {}",
3695                getLLVMStyleWithColumns(47));
3696   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
3697                "    const {}",
3698                Style);
3699   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
3700                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
3701   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
3702                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
3703   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
3704                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
3705   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
3706                "                   aaaaaaaaaaa aaaaa) const override;");
3707   verifyGoogleFormat(
3708       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
3709       "    const override;");
3710 
3711   // Even if the first parameter has to be wrapped.
3712   verifyFormat("void someLongFunction(\n"
3713                "    int someLongParameter) const {}",
3714                getLLVMStyleWithColumns(46));
3715   verifyFormat("void someLongFunction(\n"
3716                "    int someLongParameter) const {}",
3717                Style);
3718   verifyFormat("void someLongFunction(\n"
3719                "    int someLongParameter) override {}",
3720                Style);
3721   verifyFormat("void someLongFunction(\n"
3722                "    int someLongParameter) OVERRIDE {}",
3723                Style);
3724   verifyFormat("void someLongFunction(\n"
3725                "    int someLongParameter) final {}",
3726                Style);
3727   verifyFormat("void someLongFunction(\n"
3728                "    int someLongParameter) FINAL {}",
3729                Style);
3730   verifyFormat("void someLongFunction(\n"
3731                "    int parameter) const override {}",
3732                Style);
3733 
3734   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
3735   verifyFormat("void someLongFunction(\n"
3736                "    int someLongParameter) const\n"
3737                "{\n"
3738                "}",
3739                Style);
3740 
3741   // Unless these are unknown annotations.
3742   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
3743                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3744                "    LONG_AND_UGLY_ANNOTATION;");
3745 
3746   // Breaking before function-like trailing annotations is fine to keep them
3747   // close to their arguments.
3748   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3749                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
3750   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
3751                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
3752   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
3753                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
3754   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
3755                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
3756   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
3757 
3758   verifyFormat(
3759       "void aaaaaaaaaaaaaaaaaa()\n"
3760       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
3761       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
3762   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3763                "    __attribute__((unused));");
3764   verifyGoogleFormat(
3765       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3766       "    GUARDED_BY(aaaaaaaaaaaa);");
3767   verifyGoogleFormat(
3768       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3769       "    GUARDED_BY(aaaaaaaaaaaa);");
3770   verifyGoogleFormat(
3771       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
3772       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3773 }
3774 
TEST_F(FormatTest,BreaksDesireably)3775 TEST_F(FormatTest, BreaksDesireably) {
3776   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
3777                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
3778                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
3779   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3780                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
3781                "}");
3782 
3783   verifyFormat(
3784       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3785       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
3786 
3787   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3788                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3789                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
3790 
3791   verifyFormat(
3792       "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3793       "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
3794       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3795       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
3796 
3797   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3798                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3799 
3800   verifyFormat(
3801       "void f() {\n"
3802       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
3803       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
3804       "}");
3805   verifyFormat(
3806       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3807       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
3808   verifyFormat(
3809       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3810       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
3811   verifyFormat(
3812       "aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3813       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3814       "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3815 
3816   // Indent consistently independent of call expression.
3817   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
3818                "    dddddddddddddddddddddddddddddd));\n"
3819                "aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
3820                "    dddddddddddddddddddddddddddddd));");
3821 
3822   // This test case breaks on an incorrect memoization, i.e. an optimization not
3823   // taking into account the StopAt value.
3824   verifyFormat(
3825       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
3826       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
3827       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
3828       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3829 
3830   verifyFormat("{\n  {\n    {\n"
3831                "      Annotation.SpaceRequiredBefore =\n"
3832                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
3833                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
3834                "    }\n  }\n}");
3835 
3836   // Break on an outer level if there was a break on an inner level.
3837   EXPECT_EQ("f(g(h(a, // comment\n"
3838             "      b, c),\n"
3839             "    d, e),\n"
3840             "  x, y);",
3841             format("f(g(h(a, // comment\n"
3842                    "    b, c), d, e), x, y);"));
3843 
3844   // Prefer breaking similar line breaks.
3845   verifyFormat(
3846       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
3847       "                             NSTrackingMouseEnteredAndExited |\n"
3848       "                             NSTrackingActiveAlways;");
3849 }
3850 
TEST_F(FormatTest,FormatsDeclarationsOnePerLine)3851 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
3852   FormatStyle NoBinPacking = getGoogleStyle();
3853   NoBinPacking.BinPackParameters = false;
3854   NoBinPacking.BinPackArguments = true;
3855   verifyFormat("void f() {\n"
3856                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
3857                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
3858                "}",
3859                NoBinPacking);
3860   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
3861                "       int aaaaaaaaaaaaaaaaaaaa,\n"
3862                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
3863                NoBinPacking);
3864 }
3865 
TEST_F(FormatTest,FormatsOneParameterPerLineIfNecessary)3866 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
3867   FormatStyle NoBinPacking = getGoogleStyle();
3868   NoBinPacking.BinPackParameters = false;
3869   NoBinPacking.BinPackArguments = false;
3870   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
3871                "  aaaaaaaaaaaaaaaaaaaa,\n"
3872                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
3873                NoBinPacking);
3874   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
3875                "        aaaaaaaaaaaaa,\n"
3876                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
3877                NoBinPacking);
3878   verifyFormat(
3879       "aaaaaaaa(aaaaaaaaaaaaa,\n"
3880       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3881       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
3882       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3883       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
3884       NoBinPacking);
3885   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
3886                "    .aaaaaaaaaaaaaaaaaa();",
3887                NoBinPacking);
3888   verifyFormat("void f() {\n"
3889                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3890                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
3891                "}",
3892                NoBinPacking);
3893 
3894   verifyFormat(
3895       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3896       "             aaaaaaaaaaaa,\n"
3897       "             aaaaaaaaaaaa);",
3898       NoBinPacking);
3899   verifyFormat(
3900       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
3901       "                               ddddddddddddddddddddddddddddd),\n"
3902       "             test);",
3903       NoBinPacking);
3904 
3905   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
3906                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
3907                "            aaaaaaaaaaaaaaaaaaaaaaa> aaaaaaaaaaaaaaaaaa;",
3908                NoBinPacking);
3909   verifyFormat("a(\"a\"\n"
3910                "  \"a\",\n"
3911                "  a);");
3912 
3913   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
3914   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
3915                "                aaaaaaaaa,\n"
3916                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
3917                NoBinPacking);
3918   verifyFormat(
3919       "void f() {\n"
3920       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
3921       "      .aaaaaaa();\n"
3922       "}",
3923       NoBinPacking);
3924   verifyFormat(
3925       "template <class SomeType, class SomeOtherType>\n"
3926       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
3927       NoBinPacking);
3928 }
3929 
TEST_F(FormatTest,AdaptiveOnePerLineFormatting)3930 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
3931   FormatStyle Style = getLLVMStyleWithColumns(15);
3932   Style.ExperimentalAutoDetectBinPacking = true;
3933   EXPECT_EQ("aaa(aaaa,\n"
3934             "    aaaa,\n"
3935             "    aaaa);\n"
3936             "aaa(aaaa,\n"
3937             "    aaaa,\n"
3938             "    aaaa);",
3939             format("aaa(aaaa,\n" // one-per-line
3940                    "  aaaa,\n"
3941                    "    aaaa  );\n"
3942                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
3943                    Style));
3944   EXPECT_EQ("aaa(aaaa, aaaa,\n"
3945             "    aaaa);\n"
3946             "aaa(aaaa, aaaa,\n"
3947             "    aaaa);",
3948             format("aaa(aaaa,  aaaa,\n" // bin-packed
3949                    "    aaaa  );\n"
3950                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
3951                    Style));
3952 }
3953 
TEST_F(FormatTest,FormatsBuilderPattern)3954 TEST_F(FormatTest, FormatsBuilderPattern) {
3955   verifyFormat(
3956       "return llvm::StringSwitch<Reference::Kind>(name)\n"
3957       "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
3958       "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
3959       "    .StartsWith(\".init\", ORDER_INIT)\n"
3960       "    .StartsWith(\".fini\", ORDER_FINI)\n"
3961       "    .StartsWith(\".hash\", ORDER_HASH)\n"
3962       "    .Default(ORDER_TEXT);\n");
3963 
3964   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
3965                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
3966   verifyFormat(
3967       "aaaaaaa->aaaaaaa->aaaaaaaaaaaaaaaa(\n"
3968       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3969       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
3970   verifyFormat(
3971       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
3972       "    aaaaaaaaaaaaaa);");
3973   verifyFormat(
3974       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
3975       "    aaaaaa->aaaaaaaaaaaa()\n"
3976       "        ->aaaaaaaaaaaaaaaa(\n"
3977       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3978       "        ->aaaaaaaaaaaaaaaaa();");
3979   verifyGoogleFormat(
3980       "void f() {\n"
3981       "  someo->Add((new util::filetools::Handler(dir))\n"
3982       "                 ->OnEvent1(NewPermanentCallback(\n"
3983       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
3984       "                 ->OnEvent2(NewPermanentCallback(\n"
3985       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
3986       "                 ->OnEvent3(NewPermanentCallback(\n"
3987       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
3988       "                 ->OnEvent5(NewPermanentCallback(\n"
3989       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
3990       "                 ->OnEvent6(NewPermanentCallback(\n"
3991       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
3992       "}");
3993 
3994   verifyFormat(
3995       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
3996   verifyFormat("aaaaaaaaaaaaaaa()\n"
3997                "    .aaaaaaaaaaaaaaa()\n"
3998                "    .aaaaaaaaaaaaaaa()\n"
3999                "    .aaaaaaaaaaaaaaa()\n"
4000                "    .aaaaaaaaaaaaaaa();");
4001   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
4002                "    .aaaaaaaaaaaaaaa()\n"
4003                "    .aaaaaaaaaaaaaaa()\n"
4004                "    .aaaaaaaaaaaaaaa();");
4005   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
4006                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
4007                "    .aaaaaaaaaaaaaaa();");
4008   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
4009                "    ->aaaaaaaaaaaaaae(0)\n"
4010                "    ->aaaaaaaaaaaaaaa();");
4011 
4012   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
4013                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4014                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
4015   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
4016                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
4017                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
4018 
4019   // Prefer not to break after empty parentheses.
4020   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
4021                "    First->LastNewlineOffset);");
4022 }
4023 
TEST_F(FormatTest,BreaksAccordingToOperatorPrecedence)4024 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
4025   verifyFormat(
4026       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4027       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
4028   verifyFormat(
4029       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
4030       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
4031 
4032   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
4033                "    ccccccccccccccccccccccccc) {\n}");
4034   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
4035                "    ccccccccccccccccccccccccc) {\n}");
4036 
4037   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
4038                "    ccccccccccccccccccccccccc) {\n}");
4039   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
4040                "    ccccccccccccccccccccccccc) {\n}");
4041 
4042   verifyFormat(
4043       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
4044       "    ccccccccccccccccccccccccc) {\n}");
4045   verifyFormat(
4046       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
4047       "    ccccccccccccccccccccccccc) {\n}");
4048 
4049   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
4050                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
4051                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
4052                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
4053   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
4054                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
4055                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
4056                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
4057 
4058   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
4059                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
4060                "    aaaaaaaaaaaaaaa != aa) {\n}");
4061   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
4062                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
4063                "    aaaaaaaaaaaaaaa != aa) {\n}");
4064 }
4065 
TEST_F(FormatTest,BreaksAfterAssignments)4066 TEST_F(FormatTest, BreaksAfterAssignments) {
4067   verifyFormat(
4068       "unsigned Cost =\n"
4069       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
4070       "                        SI->getPointerAddressSpaceee());\n");
4071   verifyFormat(
4072       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
4073       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
4074 
4075   verifyFormat(
4076       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
4077       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
4078   verifyFormat("unsigned OriginalStartColumn =\n"
4079                "    SourceMgr.getSpellingColumnNumber(\n"
4080                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
4081                "    1;");
4082 }
4083 
TEST_F(FormatTest,AlignsAfterAssignments)4084 TEST_F(FormatTest, AlignsAfterAssignments) {
4085   verifyFormat(
4086       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4087       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
4088   verifyFormat(
4089       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4090       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
4091   verifyFormat(
4092       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4093       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
4094   verifyFormat(
4095       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4096       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
4097   verifyFormat(
4098       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
4099       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
4100       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
4101 }
4102 
TEST_F(FormatTest,AlignsAfterReturn)4103 TEST_F(FormatTest, AlignsAfterReturn) {
4104   verifyFormat(
4105       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4106       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
4107   verifyFormat(
4108       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4109       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
4110   verifyFormat(
4111       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
4112       "       aaaaaaaaaaaaaaaaaaaaaa();");
4113   verifyFormat(
4114       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
4115       "        aaaaaaaaaaaaaaaaaaaaaa());");
4116   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4117                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4118   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4119                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
4120                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4121   verifyFormat("return\n"
4122                "    // true if code is one of a or b.\n"
4123                "    code == a || code == b;");
4124 }
4125 
TEST_F(FormatTest,AlignsAfterOpenBracket)4126 TEST_F(FormatTest, AlignsAfterOpenBracket) {
4127   verifyFormat(
4128       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
4129       "                                                aaaaaaaaa aaaaaaa) {}");
4130   verifyFormat(
4131       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
4132       "                                               aaaaaaaaaaa aaaaaaaaa);");
4133   verifyFormat(
4134       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
4135       "                                             aaaaaaaaaaaaaaaaaaaaa));");
4136   FormatStyle Style = getLLVMStyle();
4137   Style.AlignAfterOpenBracket = false;
4138   verifyFormat(
4139       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4140       "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
4141       Style);
4142   verifyFormat(
4143       "SomeLongVariableName->someVeryLongFunctionName(\n"
4144       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
4145       Style);
4146   verifyFormat(
4147       "SomeLongVariableName->someFunction(\n"
4148       "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
4149       Style);
4150   verifyFormat(
4151       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
4152       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4153       Style);
4154   verifyFormat(
4155       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
4156       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4157       Style);
4158   verifyFormat(
4159       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
4160       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
4161       Style);
4162 }
4163 
TEST_F(FormatTest,ParenthesesAndOperandAlignment)4164 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
4165   FormatStyle Style = getLLVMStyleWithColumns(40);
4166   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4167                "          bbbbbbbbbbbbbbbbbbbbbb);",
4168                Style);
4169   Style.AlignAfterOpenBracket = true;
4170   Style.AlignOperands = false;
4171   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4172                "          bbbbbbbbbbbbbbbbbbbbbb);",
4173                Style);
4174   Style.AlignAfterOpenBracket = false;
4175   Style.AlignOperands = true;
4176   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4177                "          bbbbbbbbbbbbbbbbbbbbbb);",
4178                Style);
4179   Style.AlignAfterOpenBracket = false;
4180   Style.AlignOperands = false;
4181   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4182                "    bbbbbbbbbbbbbbbbbbbbbb);",
4183                Style);
4184 }
4185 
TEST_F(FormatTest,BreaksConditionalExpressions)4186 TEST_F(FormatTest, BreaksConditionalExpressions) {
4187   verifyFormat(
4188       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4189       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4190       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4191   verifyFormat(
4192       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4193       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4194   verifyFormat(
4195       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
4196       "                                                    : aaaaaaaaaaaaa);");
4197   verifyFormat(
4198       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4199       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4200       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4201       "                   aaaaaaaaaaaaa);");
4202   verifyFormat(
4203       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4204       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4205       "                   aaaaaaaaaaaaa);");
4206   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4207                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4208                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4209                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4210                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4211   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4212                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4213                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4214                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4215                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4216                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4217                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4218   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4219                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4220                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4221                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4222                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4223   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4224                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4225                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4226   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
4227                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4228                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4229                "        : aaaaaaaaaaaaaaaa;");
4230   verifyFormat(
4231       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4232       "    ? aaaaaaaaaaaaaaa\n"
4233       "    : aaaaaaaaaaaaaaa;");
4234   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
4235                "          aaaaaaaaa\n"
4236                "      ? b\n"
4237                "      : c);");
4238   verifyFormat("return aaaa == bbbb\n"
4239                "           // comment\n"
4240                "           ? aaaa\n"
4241                "           : bbbb;");
4242   verifyFormat(
4243       "unsigned Indent =\n"
4244       "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0\n"
4245       "                              ? IndentForLevel[TheLine.Level]\n"
4246       "                              : TheLine * 2,\n"
4247       "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
4248       getLLVMStyleWithColumns(70));
4249   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
4250                "                  ? aaaaaaaaaaaaaaa\n"
4251                "                  : bbbbbbbbbbbbbbb //\n"
4252                "                        ? ccccccccccccccc\n"
4253                "                        : ddddddddddddddd;");
4254   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
4255                "                  ? aaaaaaaaaaaaaaa\n"
4256                "                  : (bbbbbbbbbbbbbbb //\n"
4257                "                         ? ccccccccccccccc\n"
4258                "                         : ddddddddddddddd);");
4259   verifyFormat(
4260       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4261       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4262       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
4263       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
4264       "                                      : aaaaaaaaaa;");
4265   verifyFormat(
4266       "aaaaaa = aaaaaaaaaaaa\n"
4267       "             ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4268       "                          : aaaaaaaaaaaaaaaaaaaaaa\n"
4269       "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4270 
4271   FormatStyle NoBinPacking = getLLVMStyle();
4272   NoBinPacking.BinPackArguments = false;
4273   verifyFormat(
4274       "void f() {\n"
4275       "  g(aaa,\n"
4276       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
4277       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4278       "        ? aaaaaaaaaaaaaaa\n"
4279       "        : aaaaaaaaaaaaaaa);\n"
4280       "}",
4281       NoBinPacking);
4282   verifyFormat(
4283       "void f() {\n"
4284       "  g(aaa,\n"
4285       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
4286       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4287       "        ?: aaaaaaaaaaaaaaa);\n"
4288       "}",
4289       NoBinPacking);
4290 
4291   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
4292                "             // comment.\n"
4293                "             ccccccccccccccccccccccccccccccccccccccc\n"
4294                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4295                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
4296 
4297   // Assignments in conditional expressions. Apparently not uncommon :-(.
4298   verifyFormat("return a != b\n"
4299                "           // comment\n"
4300                "           ? a = b\n"
4301                "           : a = b;");
4302   verifyFormat("return a != b\n"
4303                "           // comment\n"
4304                "           ? a = a != b\n"
4305                "                     // comment\n"
4306                "                     ? a = b\n"
4307                "                     : a\n"
4308                "           : a;\n");
4309   verifyFormat("return a != b\n"
4310                "           // comment\n"
4311                "           ? a\n"
4312                "           : a = a != b\n"
4313                "                     // comment\n"
4314                "                     ? a = b\n"
4315                "                     : a;");
4316 }
4317 
TEST_F(FormatTest,BreaksConditionalExpressionsAfterOperator)4318 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
4319   FormatStyle Style = getLLVMStyle();
4320   Style.BreakBeforeTernaryOperators = false;
4321   Style.ColumnLimit = 70;
4322   verifyFormat(
4323       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4324       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4325       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4326       Style);
4327   verifyFormat(
4328       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4329       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4330       Style);
4331   verifyFormat(
4332       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
4333       "                                                      aaaaaaaaaaaaa);",
4334       Style);
4335   verifyFormat(
4336       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4337       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4338       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4339       "                   aaaaaaaaaaaaa);",
4340       Style);
4341   verifyFormat(
4342       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4343       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4344       "                   aaaaaaaaaaaaa);",
4345       Style);
4346   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4347                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4348                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
4349                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4350                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4351                Style);
4352   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4353                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4354                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4355                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
4356                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4357                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4358                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4359                Style);
4360   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4361                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
4362                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4363                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4364                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4365                Style);
4366   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4367                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4368                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4369                Style);
4370   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
4371                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4372                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4373                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4374                Style);
4375   verifyFormat(
4376       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4377       "    aaaaaaaaaaaaaaa :\n"
4378       "    aaaaaaaaaaaaaaa;",
4379       Style);
4380   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
4381                "          aaaaaaaaa ?\n"
4382                "      b :\n"
4383                "      c);",
4384                Style);
4385   verifyFormat(
4386       "unsigned Indent =\n"
4387       "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0 ?\n"
4388       "                              IndentForLevel[TheLine.Level] :\n"
4389       "                              TheLine * 2,\n"
4390       "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
4391       Style);
4392   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
4393                "                  aaaaaaaaaaaaaaa :\n"
4394                "                  bbbbbbbbbbbbbbb ? //\n"
4395                "                      ccccccccccccccc :\n"
4396                "                      ddddddddddddddd;",
4397                Style);
4398   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
4399                "                  aaaaaaaaaaaaaaa :\n"
4400                "                  (bbbbbbbbbbbbbbb ? //\n"
4401                "                       ccccccccccccccc :\n"
4402                "                       ddddddddddddddd);",
4403                Style);
4404 }
4405 
TEST_F(FormatTest,DeclarationsOfMultipleVariables)4406 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
4407   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
4408                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
4409   verifyFormat("bool a = true, b = false;");
4410 
4411   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4412                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
4413                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
4414                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
4415   verifyFormat(
4416       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
4417       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
4418       "     d = e && f;");
4419   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
4420                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
4421   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
4422                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
4423   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
4424                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
4425   // FIXME: If multiple variables are defined, the "*" needs to move to the new
4426   // line. Also fix indent for breaking after the type, this looks bad.
4427   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
4428                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
4429                "    * b = bbbbbbbbbbbbbbbbbbb;",
4430                getGoogleStyle());
4431 
4432   // Not ideal, but pointer-with-type does not allow much here.
4433   verifyGoogleFormat(
4434       "aaaaaaaaa* a = aaaaaaaaaaaaaaaaaaa, * b = bbbbbbbbbbbbbbbbbbb,\n"
4435       "           * b = bbbbbbbbbbbbbbbbbbb, * d = ddddddddddddddddddd;");
4436 }
4437 
TEST_F(FormatTest,ConditionalExpressionsInBrackets)4438 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
4439   verifyFormat("arr[foo ? bar : baz];");
4440   verifyFormat("f()[foo ? bar : baz];");
4441   verifyFormat("(a + b)[foo ? bar : baz];");
4442   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
4443 }
4444 
TEST_F(FormatTest,AlignsStringLiterals)4445 TEST_F(FormatTest, AlignsStringLiterals) {
4446   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
4447                "                                      \"short literal\");");
4448   verifyFormat(
4449       "looooooooooooooooooooooooongFunction(\n"
4450       "    \"short literal\"\n"
4451       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
4452   verifyFormat("someFunction(\"Always break between multi-line\"\n"
4453                "             \" string literals\",\n"
4454                "             and, other, parameters);");
4455   EXPECT_EQ("fun + \"1243\" /* comment */\n"
4456             "      \"5678\";",
4457             format("fun + \"1243\" /* comment */\n"
4458                    "      \"5678\";",
4459                    getLLVMStyleWithColumns(28)));
4460   EXPECT_EQ(
4461       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
4462       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
4463       "         \"aaaaaaaaaaaaaaaa\";",
4464       format("aaaaaa ="
4465              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
4466              "aaaaaaaaaaaaaaaaaaaaa\" "
4467              "\"aaaaaaaaaaaaaaaa\";"));
4468   verifyFormat("a = a + \"a\"\n"
4469                "        \"a\"\n"
4470                "        \"a\";");
4471   verifyFormat("f(\"a\", \"b\"\n"
4472                "       \"c\");");
4473 
4474   verifyFormat(
4475       "#define LL_FORMAT \"ll\"\n"
4476       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
4477       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
4478 
4479   verifyFormat("#define A(X)          \\\n"
4480                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
4481                "  \"ccccc\"",
4482                getLLVMStyleWithColumns(23));
4483   verifyFormat("#define A \"def\"\n"
4484                "f(\"abc\" A \"ghi\"\n"
4485                "  \"jkl\");");
4486 
4487   verifyFormat("f(L\"a\"\n"
4488                "  L\"b\")");
4489   verifyFormat("#define A(X)            \\\n"
4490                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
4491                "  L\"ccccc\"",
4492                getLLVMStyleWithColumns(25));
4493 }
4494 
TEST_F(FormatTest,AlwaysBreakAfterDefinitionReturnType)4495 TEST_F(FormatTest, AlwaysBreakAfterDefinitionReturnType) {
4496   FormatStyle AfterType = getLLVMStyle();
4497   AfterType.AlwaysBreakAfterDefinitionReturnType = true;
4498   verifyFormat("const char *\n"
4499                "f(void) {\n"  // Break here.
4500                "  return \"\";\n"
4501                "}\n"
4502                "const char *bar(void);\n",  // No break here.
4503                AfterType);
4504   verifyFormat("template <class T>\n"
4505                "T *\n"
4506                "f(T &c) {\n"  // Break here.
4507                "  return NULL;\n"
4508                "}\n"
4509                "template <class T> T *f(T &c);\n",  // No break here.
4510                AfterType);
4511   AfterType.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4512   verifyFormat("const char *\n"
4513                "f(void)\n"  // Break here.
4514                "{\n"
4515                "  return \"\";\n"
4516                "}\n"
4517                "const char *bar(void);\n",  // No break here.
4518                AfterType);
4519   verifyFormat("template <class T>\n"
4520                "T *\n"  // Problem here: no line break
4521                "f(T &c)\n"  // Break here.
4522                "{\n"
4523                "  return NULL;\n"
4524                "}\n"
4525                "template <class T> T *f(T &c);\n",  // No break here.
4526                AfterType);
4527 }
4528 
TEST_F(FormatTest,AlwaysBreakBeforeMultilineStrings)4529 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
4530   FormatStyle NoBreak = getLLVMStyle();
4531   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
4532   FormatStyle Break = getLLVMStyle();
4533   Break.AlwaysBreakBeforeMultilineStrings = true;
4534   verifyFormat("aaaa = \"bbbb\"\n"
4535                "       \"cccc\";",
4536                NoBreak);
4537   verifyFormat("aaaa =\n"
4538                "    \"bbbb\"\n"
4539                "    \"cccc\";",
4540                Break);
4541   verifyFormat("aaaa(\"bbbb\"\n"
4542                "     \"cccc\");",
4543                NoBreak);
4544   verifyFormat("aaaa(\n"
4545                "    \"bbbb\"\n"
4546                "    \"cccc\");",
4547                Break);
4548   verifyFormat("aaaa(qqq, \"bbbb\"\n"
4549                "          \"cccc\");",
4550                NoBreak);
4551   verifyFormat("aaaa(qqq,\n"
4552                "     \"bbbb\"\n"
4553                "     \"cccc\");",
4554                Break);
4555   verifyFormat("aaaa(qqq,\n"
4556                "     L\"bbbb\"\n"
4557                "     L\"cccc\");",
4558                Break);
4559 
4560   // As we break before unary operators, breaking right after them is bad.
4561   verifyFormat("string foo = abc ? \"x\"\n"
4562                "                   \"blah blah blah blah blah blah\"\n"
4563                "                 : \"y\";",
4564                Break);
4565 
4566   // Don't break if there is no column gain.
4567   verifyFormat("f(\"aaaa\"\n"
4568                "  \"bbbb\");",
4569                Break);
4570 
4571   // Treat literals with escaped newlines like multi-line string literals.
4572   EXPECT_EQ("x = \"a\\\n"
4573             "b\\\n"
4574             "c\";",
4575             format("x = \"a\\\n"
4576                    "b\\\n"
4577                    "c\";",
4578                    NoBreak));
4579   EXPECT_EQ("x =\n"
4580             "    \"a\\\n"
4581             "b\\\n"
4582             "c\";",
4583             format("x = \"a\\\n"
4584                    "b\\\n"
4585                    "c\";",
4586                    Break));
4587 
4588   // Exempt ObjC strings for now.
4589   EXPECT_EQ("NSString *const kString = @\"aaaa\"\n"
4590             "                           \"bbbb\";",
4591             format("NSString *const kString = @\"aaaa\"\n"
4592                    "\"bbbb\";",
4593                    Break));
4594 }
4595 
TEST_F(FormatTest,AlignsPipes)4596 TEST_F(FormatTest, AlignsPipes) {
4597   verifyFormat(
4598       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4599       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4600       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4601   verifyFormat(
4602       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
4603       "                     << aaaaaaaaaaaaaaaaaaaa;");
4604   verifyFormat(
4605       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4606       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4607   verifyFormat(
4608       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
4609       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
4610       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
4611   verifyFormat(
4612       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4613       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4614       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4615   verifyFormat(
4616       "llvm::errs() << \"a: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4617       "                             aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4618       "                             aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4619   verifyFormat(
4620       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4621       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4622       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4623       "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
4624   verifyFormat(
4625       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4626       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4627 
4628   verifyFormat("return out << \"somepacket = {\\n\"\n"
4629                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
4630                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
4631                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
4632                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
4633                "           << \"}\";");
4634 
4635   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
4636                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
4637                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
4638   verifyFormat(
4639       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
4640       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
4641       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
4642       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
4643       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
4644   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
4645                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
4646   verifyFormat(
4647       "void f() {\n"
4648       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
4649       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
4650       "}");
4651   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
4652                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
4653 
4654   // Breaking before the first "<<" is generally not desirable.
4655   verifyFormat(
4656       "llvm::errs()\n"
4657       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4658       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4659       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4660       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4661       getLLVMStyleWithColumns(70));
4662   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
4663                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4664                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
4665                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4666                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
4667                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4668                getLLVMStyleWithColumns(70));
4669 
4670   // But sometimes, breaking before the first "<<" is desirable.
4671   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
4672                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
4673   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
4674                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4675                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4676   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
4677                "    << BEF << IsTemplate << Description << E->getType();");
4678 
4679   verifyFormat(
4680       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4681       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4682 
4683   // Incomplete string literal.
4684   EXPECT_EQ("llvm::errs() << \"\n"
4685             "             << a;",
4686             format("llvm::errs() << \"\n<<a;"));
4687 
4688   verifyFormat("void f() {\n"
4689                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
4690                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
4691                "}");
4692 
4693   // Handle 'endl'.
4694   verifyFormat("llvm::errs() << aaaa << endl\n"
4695                "             << bbbb << endl;");
4696 }
4697 
TEST_F(FormatTest,UnderstandsEquals)4698 TEST_F(FormatTest, UnderstandsEquals) {
4699   verifyFormat(
4700       "aaaaaaaaaaaaaaaaa =\n"
4701       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4702   verifyFormat(
4703       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4704       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
4705   verifyFormat(
4706       "if (a) {\n"
4707       "  f();\n"
4708       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4709       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
4710       "}");
4711 
4712   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4713                "        100000000 + 10000000) {\n}");
4714 }
4715 
TEST_F(FormatTest,WrapsAtFunctionCallsIfNecessary)4716 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
4717   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
4718                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
4719 
4720   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
4721                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
4722 
4723   verifyFormat(
4724       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
4725       "                                                          Parameter2);");
4726 
4727   verifyFormat(
4728       "ShortObject->shortFunction(\n"
4729       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
4730       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
4731 
4732   verifyFormat("loooooooooooooongFunction(\n"
4733                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
4734 
4735   verifyFormat(
4736       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
4737       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
4738 
4739   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
4740                "    .WillRepeatedly(Return(SomeValue));");
4741   verifyFormat("void f() {\n"
4742                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
4743                "      .Times(2)\n"
4744                "      .WillRepeatedly(Return(SomeValue));\n"
4745                "}");
4746   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
4747                "    ccccccccccccccccccccccc);");
4748   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4749                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).aaaaa(aaaaa),\n"
4750                "      aaaaaaaaaaaaaaaaaaaaa);");
4751   verifyFormat("void f() {\n"
4752                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4753                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
4754                "}");
4755   verifyFormat(
4756       "aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4757       "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4758       "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4759       "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4760       "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
4761   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4762                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4763                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4764                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
4765                "}");
4766 
4767   // Here, it is not necessary to wrap at "." or "->".
4768   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
4769                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
4770   verifyFormat(
4771       "aaaaaaaaaaa->aaaaaaaaa(\n"
4772       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4773       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
4774 
4775   verifyFormat(
4776       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4777       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
4778   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
4779                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
4780   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
4781                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
4782 
4783   // FIXME: Should we break before .a()?
4784   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4785                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).a();");
4786 
4787   FormatStyle NoBinPacking = getLLVMStyle();
4788   NoBinPacking.BinPackParameters = false;
4789   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
4790                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
4791                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
4792                "                         aaaaaaaaaaaaaaaaaaa,\n"
4793                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4794                NoBinPacking);
4795 
4796   // If there is a subsequent call, change to hanging indentation.
4797   verifyFormat(
4798       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4799       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
4800       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4801   verifyFormat(
4802       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4803       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
4804   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4805                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4806                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4807   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4808                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4809                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
4810 }
4811 
TEST_F(FormatTest,WrapsTemplateDeclarations)4812 TEST_F(FormatTest, WrapsTemplateDeclarations) {
4813   verifyFormat("template <typename T>\n"
4814                "virtual void loooooooooooongFunction(int Param1, int Param2);");
4815   verifyFormat("template <typename T>\n"
4816                "// T should be one of {A, B}.\n"
4817                "virtual void loooooooooooongFunction(int Param1, int Param2);");
4818   verifyFormat(
4819       "template <typename T>\n"
4820       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
4821   verifyFormat("template <typename T>\n"
4822                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
4823                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
4824   verifyFormat(
4825       "template <typename T>\n"
4826       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
4827       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
4828   verifyFormat(
4829       "template <typename T>\n"
4830       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
4831       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
4832       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4833   verifyFormat("template <typename T>\n"
4834                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4835                "    int aaaaaaaaaaaaaaaaaaaaaa);");
4836   verifyFormat(
4837       "template <typename T1, typename T2 = char, typename T3 = char,\n"
4838       "          typename T4 = char>\n"
4839       "void f();");
4840   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
4841                "          template <typename> class cccccccccccccccccccccc,\n"
4842                "          typename ddddddddddddd>\n"
4843                "class C {};");
4844   verifyFormat(
4845       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
4846       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4847 
4848   verifyFormat("void f() {\n"
4849                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
4850                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
4851                "}");
4852 
4853   verifyFormat("template <typename T> class C {};");
4854   verifyFormat("template <typename T> void f();");
4855   verifyFormat("template <typename T> void f() {}");
4856   verifyFormat(
4857       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
4858       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4859       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
4860       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
4861       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4862       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
4863       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
4864       getLLVMStyleWithColumns(72));
4865   EXPECT_EQ("static_cast<A< //\n"
4866             "    B> *>(\n"
4867             "\n"
4868             "    );",
4869             format("static_cast<A<//\n"
4870                    "    B>*>(\n"
4871                    "\n"
4872                    "    );"));
4873   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4874                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
4875 
4876   FormatStyle AlwaysBreak = getLLVMStyle();
4877   AlwaysBreak.AlwaysBreakTemplateDeclarations = true;
4878   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
4879   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
4880   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
4881   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4882                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
4883                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
4884   verifyFormat("template <template <typename> class Fooooooo,\n"
4885                "          template <typename> class Baaaaaaar>\n"
4886                "struct C {};",
4887                AlwaysBreak);
4888   verifyFormat("template <typename T> // T can be A, B or C.\n"
4889                "struct C {};",
4890                AlwaysBreak);
4891 }
4892 
TEST_F(FormatTest,WrapsAtNestedNameSpecifiers)4893 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
4894   verifyFormat(
4895       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
4896       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4897   verifyFormat(
4898       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
4899       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4900       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
4901 
4902   // FIXME: Should we have the extra indent after the second break?
4903   verifyFormat(
4904       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
4905       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
4906       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4907 
4908   verifyFormat(
4909       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
4910       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
4911 
4912   // Breaking at nested name specifiers is generally not desirable.
4913   verifyFormat(
4914       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4915       "    aaaaaaaaaaaaaaaaaaaaaaa);");
4916 
4917   verifyFormat(
4918       "aaaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
4919       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4920       "                   aaaaaaaaaaaaaaaaaaaaa);",
4921       getLLVMStyleWithColumns(74));
4922 
4923   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
4924                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4925                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4926 }
4927 
TEST_F(FormatTest,UnderstandsTemplateParameters)4928 TEST_F(FormatTest, UnderstandsTemplateParameters) {
4929   verifyFormat("A<int> a;");
4930   verifyFormat("A<A<A<int>>> a;");
4931   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
4932   verifyFormat("bool x = a < 1 || 2 > a;");
4933   verifyFormat("bool x = 5 < f<int>();");
4934   verifyFormat("bool x = f<int>() > 5;");
4935   verifyFormat("bool x = 5 < a<int>::x;");
4936   verifyFormat("bool x = a < 4 ? a > 2 : false;");
4937   verifyFormat("bool x = f() ? a < 2 : a > 2;");
4938 
4939   verifyGoogleFormat("A<A<int>> a;");
4940   verifyGoogleFormat("A<A<A<int>>> a;");
4941   verifyGoogleFormat("A<A<A<A<int>>>> a;");
4942   verifyGoogleFormat("A<A<int> > a;");
4943   verifyGoogleFormat("A<A<A<int> > > a;");
4944   verifyGoogleFormat("A<A<A<A<int> > > > a;");
4945   verifyGoogleFormat("A<::A<int>> a;");
4946   verifyGoogleFormat("A<::A> a;");
4947   verifyGoogleFormat("A< ::A> a;");
4948   verifyGoogleFormat("A< ::A<int> > a;");
4949   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
4950   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
4951   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
4952   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
4953 
4954   verifyFormat("A<A>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
4955 
4956   verifyFormat("test >> a >> b;");
4957   verifyFormat("test << a >> b;");
4958 
4959   verifyFormat("f<int>();");
4960   verifyFormat("template <typename T> void f() {}");
4961   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
4962 
4963   // Not template parameters.
4964   verifyFormat("return a < b && c > d;");
4965   verifyFormat("void f() {\n"
4966                "  while (a < b && c > d) {\n"
4967                "  }\n"
4968                "}");
4969   verifyFormat("template <typename... Types>\n"
4970                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
4971 
4972   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4973                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
4974                getLLVMStyleWithColumns(60));
4975   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
4976   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
4977 }
4978 
TEST_F(FormatTest,UnderstandsBinaryOperators)4979 TEST_F(FormatTest, UnderstandsBinaryOperators) {
4980   verifyFormat("COMPARE(a, ==, b);");
4981 }
4982 
TEST_F(FormatTest,UnderstandsPointersToMembers)4983 TEST_F(FormatTest, UnderstandsPointersToMembers) {
4984   verifyFormat("int A::*x;");
4985   verifyFormat("int (S::*func)(void *);");
4986   verifyFormat("void f() { int (S::*func)(void *); }");
4987   verifyFormat("typedef bool *(Class::*Member)() const;");
4988   verifyFormat("void f() {\n"
4989                "  (a->*f)();\n"
4990                "  a->*x;\n"
4991                "  (a.*f)();\n"
4992                "  ((*a).*f)();\n"
4993                "  a.*x;\n"
4994                "}");
4995   verifyFormat("void f() {\n"
4996                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
4997                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
4998                "}");
4999   verifyFormat(
5000       "(aaaaaaaaaa->*bbbbbbb)(\n"
5001       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5002   FormatStyle Style = getLLVMStyle();
5003   Style.PointerAlignment = FormatStyle::PAS_Left;
5004   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
5005 }
5006 
TEST_F(FormatTest,UnderstandsUnaryOperators)5007 TEST_F(FormatTest, UnderstandsUnaryOperators) {
5008   verifyFormat("int a = -2;");
5009   verifyFormat("f(-1, -2, -3);");
5010   verifyFormat("a[-1] = 5;");
5011   verifyFormat("int a = 5 + -2;");
5012   verifyFormat("if (i == -1) {\n}");
5013   verifyFormat("if (i != -1) {\n}");
5014   verifyFormat("if (i > -1) {\n}");
5015   verifyFormat("if (i < -1) {\n}");
5016   verifyFormat("++(a->f());");
5017   verifyFormat("--(a->f());");
5018   verifyFormat("(a->f())++;");
5019   verifyFormat("a[42]++;");
5020   verifyFormat("if (!(a->f())) {\n}");
5021 
5022   verifyFormat("a-- > b;");
5023   verifyFormat("b ? -a : c;");
5024   verifyFormat("n * sizeof char16;");
5025   verifyFormat("n * alignof char16;", getGoogleStyle());
5026   verifyFormat("sizeof(char);");
5027   verifyFormat("alignof(char);", getGoogleStyle());
5028 
5029   verifyFormat("return -1;");
5030   verifyFormat("switch (a) {\n"
5031                "case -1:\n"
5032                "  break;\n"
5033                "}");
5034   verifyFormat("#define X -1");
5035   verifyFormat("#define X -kConstant");
5036 
5037   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
5038   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
5039 
5040   verifyFormat("int a = /* confusing comment */ -1;");
5041   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
5042   verifyFormat("int a = i /* confusing comment */++;");
5043 }
5044 
TEST_F(FormatTest,DoesNotIndentRelativeToUnaryOperators)5045 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
5046   verifyFormat("if (!aaaaaaaaaa( // break\n"
5047                "        aaaaa)) {\n"
5048                "}");
5049   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
5050                "               aaaaa));");
5051   verifyFormat("*aaa = aaaaaaa( // break\n"
5052                "    bbbbbb);");
5053 }
5054 
TEST_F(FormatTest,UnderstandsOverloadedOperators)5055 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
5056   verifyFormat("bool operator<();");
5057   verifyFormat("bool operator>();");
5058   verifyFormat("bool operator=();");
5059   verifyFormat("bool operator==();");
5060   verifyFormat("bool operator!=();");
5061   verifyFormat("int operator+();");
5062   verifyFormat("int operator++();");
5063   verifyFormat("bool operator();");
5064   verifyFormat("bool operator()();");
5065   verifyFormat("bool operator[]();");
5066   verifyFormat("operator bool();");
5067   verifyFormat("operator int();");
5068   verifyFormat("operator void *();");
5069   verifyFormat("operator SomeType<int>();");
5070   verifyFormat("operator SomeType<int, int>();");
5071   verifyFormat("operator SomeType<SomeType<int>>();");
5072   verifyFormat("void *operator new(std::size_t size);");
5073   verifyFormat("void *operator new[](std::size_t size);");
5074   verifyFormat("void operator delete(void *ptr);");
5075   verifyFormat("void operator delete[](void *ptr);");
5076   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
5077                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
5078 
5079   verifyFormat(
5080       "ostream &operator<<(ostream &OutputStream,\n"
5081       "                    SomeReallyLongType WithSomeReallyLongValue);");
5082   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
5083                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
5084                "  return left.group < right.group;\n"
5085                "}");
5086   verifyFormat("SomeType &operator=(const SomeType &S);");
5087   verifyFormat("f.template operator()<int>();");
5088 
5089   verifyGoogleFormat("operator void*();");
5090   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
5091   verifyGoogleFormat("operator ::A();");
5092 
5093   verifyFormat("using A::operator+;");
5094 
5095   verifyFormat("Deleted &operator=(const Deleted &)& = default;");
5096   verifyFormat("Deleted &operator=(const Deleted &)&& = delete;");
5097   verifyGoogleFormat("Deleted& operator=(const Deleted&)& = default;");
5098   verifyGoogleFormat("Deleted& operator=(const Deleted&)&& = delete;");
5099 
5100   verifyFormat("string // break\n"
5101                "operator()() & {}");
5102   verifyFormat("string // break\n"
5103                "operator()() && {}");
5104 }
5105 
TEST_F(FormatTest,UnderstandsNewAndDelete)5106 TEST_F(FormatTest, UnderstandsNewAndDelete) {
5107   verifyFormat("void f() {\n"
5108                "  A *a = new A;\n"
5109                "  A *a = new (placement) A;\n"
5110                "  delete a;\n"
5111                "  delete (A *)a;\n"
5112                "}");
5113   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
5114                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
5115   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5116                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
5117                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
5118   verifyFormat("delete[] h->p;");
5119 }
5120 
TEST_F(FormatTest,UnderstandsUsesOfStarAndAmp)5121 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
5122   verifyFormat("int *f(int *a) {}");
5123   verifyFormat("int main(int argc, char **argv) {}");
5124   verifyFormat("Test::Test(int b) : a(b * b) {}");
5125   verifyIndependentOfContext("f(a, *a);");
5126   verifyFormat("void g() { f(*a); }");
5127   verifyIndependentOfContext("int a = b * 10;");
5128   verifyIndependentOfContext("int a = 10 * b;");
5129   verifyIndependentOfContext("int a = b * c;");
5130   verifyIndependentOfContext("int a += b * c;");
5131   verifyIndependentOfContext("int a -= b * c;");
5132   verifyIndependentOfContext("int a *= b * c;");
5133   verifyIndependentOfContext("int a /= b * c;");
5134   verifyIndependentOfContext("int a = *b;");
5135   verifyIndependentOfContext("int a = *b * c;");
5136   verifyIndependentOfContext("int a = b * *c;");
5137   verifyIndependentOfContext("return 10 * b;");
5138   verifyIndependentOfContext("return *b * *c;");
5139   verifyIndependentOfContext("return a & ~b;");
5140   verifyIndependentOfContext("f(b ? *c : *d);");
5141   verifyIndependentOfContext("int a = b ? *c : *d;");
5142   verifyIndependentOfContext("*b = a;");
5143   verifyIndependentOfContext("a * ~b;");
5144   verifyIndependentOfContext("a * !b;");
5145   verifyIndependentOfContext("a * +b;");
5146   verifyIndependentOfContext("a * -b;");
5147   verifyIndependentOfContext("a * ++b;");
5148   verifyIndependentOfContext("a * --b;");
5149   verifyIndependentOfContext("a[4] * b;");
5150   verifyIndependentOfContext("a[a * a] = 1;");
5151   verifyIndependentOfContext("f() * b;");
5152   verifyIndependentOfContext("a * [self dostuff];");
5153   verifyIndependentOfContext("int x = a * (a + b);");
5154   verifyIndependentOfContext("(a *)(a + b);");
5155   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
5156   verifyIndependentOfContext("int *pa = (int *)&a;");
5157   verifyIndependentOfContext("return sizeof(int **);");
5158   verifyIndependentOfContext("return sizeof(int ******);");
5159   verifyIndependentOfContext("return (int **&)a;");
5160   verifyIndependentOfContext("f((*PointerToArray)[10]);");
5161   verifyFormat("void f(Type (*parameter)[10]) {}");
5162   verifyGoogleFormat("return sizeof(int**);");
5163   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
5164   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
5165   verifyFormat("auto a = [](int **&, int ***) {};");
5166   verifyFormat("auto PointerBinding = [](const char *S) {};");
5167   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
5168   verifyFormat("[](const decltype(*a) &value) {}");
5169   verifyIndependentOfContext("typedef void (*f)(int *a);");
5170   verifyIndependentOfContext("int i{a * b};");
5171   verifyIndependentOfContext("aaa && aaa->f();");
5172   verifyIndependentOfContext("int x = ~*p;");
5173   verifyFormat("Constructor() : a(a), area(width * height) {}");
5174   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
5175   verifyFormat("void f() { f(a, c * d); }");
5176 
5177   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
5178 
5179   verifyIndependentOfContext("A<int *> a;");
5180   verifyIndependentOfContext("A<int **> a;");
5181   verifyIndependentOfContext("A<int *, int *> a;");
5182   verifyIndependentOfContext("A<int *[]> a;");
5183   verifyIndependentOfContext(
5184       "const char *const p = reinterpret_cast<const char *const>(q);");
5185   verifyIndependentOfContext("A<int **, int **> a;");
5186   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
5187   verifyFormat("for (char **a = b; *a; ++a) {\n}");
5188   verifyFormat("for (; a && b;) {\n}");
5189   verifyFormat("bool foo = true && [] { return false; }();");
5190 
5191   verifyFormat(
5192       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5193       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5194 
5195   verifyGoogleFormat("**outparam = 1;");
5196   verifyGoogleFormat("int main(int argc, char** argv) {}");
5197   verifyGoogleFormat("A<int*> a;");
5198   verifyGoogleFormat("A<int**> a;");
5199   verifyGoogleFormat("A<int*, int*> a;");
5200   verifyGoogleFormat("A<int**, int**> a;");
5201   verifyGoogleFormat("f(b ? *c : *d);");
5202   verifyGoogleFormat("int a = b ? *c : *d;");
5203   verifyGoogleFormat("Type* t = **x;");
5204   verifyGoogleFormat("Type* t = *++*x;");
5205   verifyGoogleFormat("*++*x;");
5206   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
5207   verifyGoogleFormat("Type* t = x++ * y;");
5208   verifyGoogleFormat(
5209       "const char* const p = reinterpret_cast<const char* const>(q);");
5210   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
5211   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
5212   verifyGoogleFormat("template <typename T>\n"
5213                      "void f(int i = 0, SomeType** temps = NULL);");
5214 
5215   FormatStyle Left = getLLVMStyle();
5216   Left.PointerAlignment = FormatStyle::PAS_Left;
5217   verifyFormat("x = *a(x) = *a(y);", Left);
5218 
5219   verifyIndependentOfContext("a = *(x + y);");
5220   verifyIndependentOfContext("a = &(x + y);");
5221   verifyIndependentOfContext("*(x + y).call();");
5222   verifyIndependentOfContext("&(x + y)->call();");
5223   verifyFormat("void f() { &(*I).first; }");
5224 
5225   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
5226   verifyFormat(
5227       "int *MyValues = {\n"
5228       "    *A, // Operator detection might be confused by the '{'\n"
5229       "    *BB // Operator detection might be confused by previous comment\n"
5230       "};");
5231 
5232   verifyIndependentOfContext("if (int *a = &b)");
5233   verifyIndependentOfContext("if (int &a = *b)");
5234   verifyIndependentOfContext("if (a & b[i])");
5235   verifyIndependentOfContext("if (a::b::c::d & b[i])");
5236   verifyIndependentOfContext("if (*b[i])");
5237   verifyIndependentOfContext("if (int *a = (&b))");
5238   verifyIndependentOfContext("while (int *a = &b)");
5239   verifyIndependentOfContext("size = sizeof *a;");
5240   verifyFormat("void f() {\n"
5241                "  for (const int &v : Values) {\n"
5242                "  }\n"
5243                "}");
5244   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
5245   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
5246   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
5247 
5248   verifyFormat("#define A (!a * b)");
5249   verifyFormat("#define MACRO     \\\n"
5250                "  int *i = a * b; \\\n"
5251                "  void f(a *b);",
5252                getLLVMStyleWithColumns(19));
5253 
5254   verifyIndependentOfContext("A = new SomeType *[Length];");
5255   verifyIndependentOfContext("A = new SomeType *[Length]();");
5256   verifyIndependentOfContext("T **t = new T *;");
5257   verifyIndependentOfContext("T **t = new T *();");
5258   verifyGoogleFormat("A = new SomeType* [Length]();");
5259   verifyGoogleFormat("A = new SomeType* [Length];");
5260   verifyGoogleFormat("T** t = new T*;");
5261   verifyGoogleFormat("T** t = new T*();");
5262 
5263   FormatStyle PointerLeft = getLLVMStyle();
5264   PointerLeft.PointerAlignment = FormatStyle::PAS_Left;
5265   verifyFormat("delete *x;", PointerLeft);
5266   verifyFormat("STATIC_ASSERT((a & b) == 0);");
5267   verifyFormat("STATIC_ASSERT(0 == (a & b));");
5268   verifyFormat("template <bool a, bool b> "
5269                "typename t::if<x && y>::type f() {}");
5270   verifyFormat("template <int *y> f() {}");
5271   verifyFormat("vector<int *> v;");
5272   verifyFormat("vector<int *const> v;");
5273   verifyFormat("vector<int *const **const *> v;");
5274   verifyFormat("vector<int *volatile> v;");
5275   verifyFormat("vector<a * b> v;");
5276   verifyFormat("foo<b && false>();");
5277   verifyFormat("foo<b & 1>();");
5278   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
5279   verifyFormat(
5280       "template <class T, class = typename std::enable_if<\n"
5281       "                       std::is_integral<T>::value &&\n"
5282       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
5283       "void F();",
5284       getLLVMStyleWithColumns(76));
5285   verifyFormat(
5286       "template <class T,\n"
5287       "          class = typename ::std::enable_if<\n"
5288       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
5289       "void F();",
5290       getGoogleStyleWithColumns(68));
5291 
5292   verifyIndependentOfContext("MACRO(int *i);");
5293   verifyIndependentOfContext("MACRO(auto *a);");
5294   verifyIndependentOfContext("MACRO(const A *a);");
5295   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
5296   // FIXME: Is there a way to make this work?
5297   // verifyIndependentOfContext("MACRO(A *a);");
5298 
5299   verifyFormat("DatumHandle const *operator->() const { return input_; }");
5300 
5301   EXPECT_EQ("#define OP(x)                                    \\\n"
5302             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
5303             "    return s << a.DebugString();                 \\\n"
5304             "  }",
5305             format("#define OP(x) \\\n"
5306                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
5307                    "    return s << a.DebugString(); \\\n"
5308                    "  }",
5309                    getLLVMStyleWithColumns(50)));
5310 
5311   // FIXME: We cannot handle this case yet; we might be able to figure out that
5312   // foo<x> d > v; doesn't make sense.
5313   verifyFormat("foo<a<b && c> d> v;");
5314 
5315   FormatStyle PointerMiddle = getLLVMStyle();
5316   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
5317   verifyFormat("delete *x;", PointerMiddle);
5318   verifyFormat("int * x;", PointerMiddle);
5319   verifyFormat("template <int * y> f() {}", PointerMiddle);
5320   verifyFormat("int * f(int * a) {}", PointerMiddle);
5321   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
5322   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
5323   verifyFormat("A<int *> a;", PointerMiddle);
5324   verifyFormat("A<int **> a;", PointerMiddle);
5325   verifyFormat("A<int *, int *> a;", PointerMiddle);
5326   verifyFormat("A<int * []> a;", PointerMiddle);
5327   verifyFormat("A = new SomeType * [Length]();", PointerMiddle);
5328   verifyFormat("A = new SomeType * [Length];", PointerMiddle);
5329   verifyFormat("T ** t = new T *;", PointerMiddle);
5330 }
5331 
TEST_F(FormatTest,UnderstandsAttributes)5332 TEST_F(FormatTest, UnderstandsAttributes) {
5333   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
5334   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
5335                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
5336 }
5337 
TEST_F(FormatTest,UnderstandsEllipsis)5338 TEST_F(FormatTest, UnderstandsEllipsis) {
5339   verifyFormat("int printf(const char *fmt, ...);");
5340   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
5341   verifyFormat("template <class... Ts> void Foo(Ts *... ts) {}");
5342 
5343   FormatStyle PointersLeft = getLLVMStyle();
5344   PointersLeft.PointerAlignment = FormatStyle::PAS_Left;
5345   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", PointersLeft);
5346 }
5347 
TEST_F(FormatTest,AdaptivelyFormatsPointersAndReferences)5348 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
5349   EXPECT_EQ("int *a;\n"
5350             "int *a;\n"
5351             "int *a;",
5352             format("int *a;\n"
5353                    "int* a;\n"
5354                    "int *a;",
5355                    getGoogleStyle()));
5356   EXPECT_EQ("int* a;\n"
5357             "int* a;\n"
5358             "int* a;",
5359             format("int* a;\n"
5360                    "int* a;\n"
5361                    "int *a;",
5362                    getGoogleStyle()));
5363   EXPECT_EQ("int *a;\n"
5364             "int *a;\n"
5365             "int *a;",
5366             format("int *a;\n"
5367                    "int * a;\n"
5368                    "int *  a;",
5369                    getGoogleStyle()));
5370 }
5371 
TEST_F(FormatTest,UnderstandsRvalueReferences)5372 TEST_F(FormatTest, UnderstandsRvalueReferences) {
5373   verifyFormat("int f(int &&a) {}");
5374   verifyFormat("int f(int a, char &&b) {}");
5375   verifyFormat("void f() { int &&a = b; }");
5376   verifyGoogleFormat("int f(int a, char&& b) {}");
5377   verifyGoogleFormat("void f() { int&& a = b; }");
5378 
5379   verifyIndependentOfContext("A<int &&> a;");
5380   verifyIndependentOfContext("A<int &&, int &&> a;");
5381   verifyGoogleFormat("A<int&&> a;");
5382   verifyGoogleFormat("A<int&&, int&&> a;");
5383 
5384   // Not rvalue references:
5385   verifyFormat("template <bool B, bool C> class A {\n"
5386                "  static_assert(B && C, \"Something is wrong\");\n"
5387                "};");
5388   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
5389   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
5390   verifyFormat("#define A(a, b) (a && b)");
5391 }
5392 
TEST_F(FormatTest,FormatsBinaryOperatorsPrecedingEquals)5393 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
5394   verifyFormat("void f() {\n"
5395                "  x[aaaaaaaaa -\n"
5396                "    b] = 23;\n"
5397                "}",
5398                getLLVMStyleWithColumns(15));
5399 }
5400 
TEST_F(FormatTest,FormatsCasts)5401 TEST_F(FormatTest, FormatsCasts) {
5402   verifyFormat("Type *A = static_cast<Type *>(P);");
5403   verifyFormat("Type *A = (Type *)P;");
5404   verifyFormat("Type *A = (vector<Type *, int *>)P;");
5405   verifyFormat("int a = (int)(2.0f);");
5406   verifyFormat("int a = (int)2.0f;");
5407   verifyFormat("x[(int32)y];");
5408   verifyFormat("x = (int32)y;");
5409   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
5410   verifyFormat("int a = (int)*b;");
5411   verifyFormat("int a = (int)2.0f;");
5412   verifyFormat("int a = (int)~0;");
5413   verifyFormat("int a = (int)++a;");
5414   verifyFormat("int a = (int)sizeof(int);");
5415   verifyFormat("int a = (int)+2;");
5416   verifyFormat("my_int a = (my_int)2.0f;");
5417   verifyFormat("my_int a = (my_int)sizeof(int);");
5418   verifyFormat("return (my_int)aaa;");
5419   verifyFormat("#define x ((int)-1)");
5420   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
5421   verifyFormat("#define p(q) ((int *)&q)");
5422   verifyFormat("fn(a)(b) + 1;");
5423 
5424   verifyFormat("void f() { my_int a = (my_int)*b; }");
5425   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
5426   verifyFormat("my_int a = (my_int)~0;");
5427   verifyFormat("my_int a = (my_int)++a;");
5428   verifyFormat("my_int a = (my_int)-2;");
5429   verifyFormat("my_int a = (my_int)1;");
5430   verifyFormat("my_int a = (my_int *)1;");
5431   verifyFormat("my_int a = (const my_int)-1;");
5432   verifyFormat("my_int a = (const my_int *)-1;");
5433   verifyFormat("my_int a = (my_int)(my_int)-1;");
5434 
5435   // FIXME: single value wrapped with paren will be treated as cast.
5436   verifyFormat("void f(int i = (kValue)*kMask) {}");
5437 
5438   verifyFormat("{ (void)F; }");
5439 
5440   // Don't break after a cast's
5441   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5442                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
5443                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
5444 
5445   // These are not casts.
5446   verifyFormat("void f(int *) {}");
5447   verifyFormat("f(foo)->b;");
5448   verifyFormat("f(foo).b;");
5449   verifyFormat("f(foo)(b);");
5450   verifyFormat("f(foo)[b];");
5451   verifyFormat("[](foo) { return 4; }(bar);");
5452   verifyFormat("(*funptr)(foo)[4];");
5453   verifyFormat("funptrs[4](foo)[4];");
5454   verifyFormat("void f(int *);");
5455   verifyFormat("void f(int *) = 0;");
5456   verifyFormat("void f(SmallVector<int>) {}");
5457   verifyFormat("void f(SmallVector<int>);");
5458   verifyFormat("void f(SmallVector<int>) = 0;");
5459   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
5460   verifyFormat("int a = sizeof(int) * b;");
5461   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
5462   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
5463   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
5464   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
5465 
5466   // These are not casts, but at some point were confused with casts.
5467   verifyFormat("virtual void foo(int *) override;");
5468   verifyFormat("virtual void foo(char &) const;");
5469   verifyFormat("virtual void foo(int *a, char *) const;");
5470   verifyFormat("int a = sizeof(int *) + b;");
5471   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
5472 
5473   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
5474                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
5475   // FIXME: The indentation here is not ideal.
5476   verifyFormat(
5477       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5478       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
5479       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
5480 }
5481 
TEST_F(FormatTest,FormatsFunctionTypes)5482 TEST_F(FormatTest, FormatsFunctionTypes) {
5483   verifyFormat("A<bool()> a;");
5484   verifyFormat("A<SomeType()> a;");
5485   verifyFormat("A<void (*)(int, std::string)> a;");
5486   verifyFormat("A<void *(int)>;");
5487   verifyFormat("void *(*a)(int *, SomeType *);");
5488   verifyFormat("int (*func)(void *);");
5489   verifyFormat("void f() { int (*func)(void *); }");
5490   verifyFormat("template <class CallbackClass>\n"
5491                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
5492 
5493   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
5494   verifyGoogleFormat("void* (*a)(int);");
5495   verifyGoogleFormat(
5496       "template <class CallbackClass>\n"
5497       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
5498 
5499   // Other constructs can look somewhat like function types:
5500   verifyFormat("A<sizeof(*x)> a;");
5501   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
5502   verifyFormat("some_var = function(*some_pointer_var)[0];");
5503   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
5504 }
5505 
TEST_F(FormatTest,BreaksLongVariableDeclarations)5506 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
5507   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
5508                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
5509   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
5510                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
5511 
5512   // Different ways of ()-initializiation.
5513   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
5514                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
5515   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
5516                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
5517   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
5518                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
5519 }
5520 
TEST_F(FormatTest,BreaksLongDeclarations)5521 TEST_F(FormatTest, BreaksLongDeclarations) {
5522   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
5523                "    AnotherNameForTheLongType;");
5524   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
5525                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5526   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
5527                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
5528   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
5529                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
5530   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
5531                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
5532   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
5533                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
5534   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
5535                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
5536   FormatStyle Indented = getLLVMStyle();
5537   Indented.IndentWrappedFunctionNames = true;
5538   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
5539                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
5540                Indented);
5541   verifyFormat(
5542       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
5543       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
5544       Indented);
5545   verifyFormat(
5546       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
5547       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
5548       Indented);
5549   verifyFormat(
5550       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
5551       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
5552       Indented);
5553 
5554   // FIXME: Without the comment, this breaks after "(".
5555   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
5556                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
5557                getGoogleStyle());
5558 
5559   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
5560                "                  int LoooooooooooooooooooongParam2) {}");
5561   verifyFormat(
5562       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
5563       "                                   SourceLocation L, IdentifierIn *II,\n"
5564       "                                   Type *T) {}");
5565   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
5566                "ReallyReallyLongFunctionName(\n"
5567                "    const std::string &SomeParameter,\n"
5568                "    const SomeType<string, SomeOtherTemplateParameter> &\n"
5569                "        ReallyReallyLongParameterName,\n"
5570                "    const SomeType<string, SomeOtherTemplateParameter> &\n"
5571                "        AnotherLongParameterName) {}");
5572   verifyFormat("template <typename A>\n"
5573                "SomeLoooooooooooooooooooooongType<\n"
5574                "    typename some_namespace::SomeOtherType<A>::Type>\n"
5575                "Function() {}");
5576 
5577   verifyGoogleFormat(
5578       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
5579       "    aaaaaaaaaaaaaaaaaaaaaaa;");
5580   verifyGoogleFormat(
5581       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
5582       "                                   SourceLocation L) {}");
5583   verifyGoogleFormat(
5584       "some_namespace::LongReturnType\n"
5585       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
5586       "    int first_long_parameter, int second_parameter) {}");
5587 
5588   verifyGoogleFormat("template <typename T>\n"
5589                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
5590                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
5591   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5592                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
5593 
5594   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
5595                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5596                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5597 }
5598 
TEST_F(FormatTest,FormatsArrays)5599 TEST_F(FormatTest, FormatsArrays) {
5600   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5601                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
5602   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5603                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
5604   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5605                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
5606   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5607                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5608                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
5609   verifyFormat(
5610       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
5611       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5612       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
5613 
5614   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
5615                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
5616   verifyFormat(
5617       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
5618       "                                  .aaaaaaa[0]\n"
5619       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
5620 }
5621 
TEST_F(FormatTest,LineStartsWithSpecialCharacter)5622 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
5623   verifyFormat("(a)->b();");
5624   verifyFormat("--a;");
5625 }
5626 
TEST_F(FormatTest,HandlesIncludeDirectives)5627 TEST_F(FormatTest, HandlesIncludeDirectives) {
5628   verifyFormat("#include <string>\n"
5629                "#include <a/b/c.h>\n"
5630                "#include \"a/b/string\"\n"
5631                "#include \"string.h\"\n"
5632                "#include \"string.h\"\n"
5633                "#include <a-a>\n"
5634                "#include < path with space >\n"
5635                "#include \"abc.h\" // this is included for ABC\n"
5636                "#include \"some long include\" // with a comment\n"
5637                "#include \"some very long include paaaaaaaaaaaaaaaaaaaaaaath\"",
5638                getLLVMStyleWithColumns(35));
5639   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
5640   EXPECT_EQ("#include <a>", format("#include<a>"));
5641 
5642   verifyFormat("#import <string>");
5643   verifyFormat("#import <a/b/c.h>");
5644   verifyFormat("#import \"a/b/string\"");
5645   verifyFormat("#import \"string.h\"");
5646   verifyFormat("#import \"string.h\"");
5647   verifyFormat("#if __has_include(<strstream>)\n"
5648                "#include <strstream>\n"
5649                "#endif");
5650 
5651   verifyFormat("#define MY_IMPORT <a/b>");
5652 
5653   // Protocol buffer definition or missing "#".
5654   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
5655                getLLVMStyleWithColumns(30));
5656 
5657   FormatStyle Style = getLLVMStyle();
5658   Style.AlwaysBreakBeforeMultilineStrings = true;
5659   Style.ColumnLimit = 0;
5660   verifyFormat("#import \"abc.h\"", Style);
5661 
5662   // But 'import' might also be a regular C++ namespace.
5663   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5664                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5665 }
5666 
5667 //===----------------------------------------------------------------------===//
5668 // Error recovery tests.
5669 //===----------------------------------------------------------------------===//
5670 
TEST_F(FormatTest,IncompleteParameterLists)5671 TEST_F(FormatTest, IncompleteParameterLists) {
5672   FormatStyle NoBinPacking = getLLVMStyle();
5673   NoBinPacking.BinPackParameters = false;
5674   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
5675                "                        double *min_x,\n"
5676                "                        double *max_x,\n"
5677                "                        double *min_y,\n"
5678                "                        double *max_y,\n"
5679                "                        double *min_z,\n"
5680                "                        double *max_z, ) {}",
5681                NoBinPacking);
5682 }
5683 
TEST_F(FormatTest,IncorrectCodeTrailingStuff)5684 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
5685   verifyFormat("void f() { return; }\n42");
5686   verifyFormat("void f() {\n"
5687                "  if (0)\n"
5688                "    return;\n"
5689                "}\n"
5690                "42");
5691   verifyFormat("void f() { return }\n42");
5692   verifyFormat("void f() {\n"
5693                "  if (0)\n"
5694                "    return\n"
5695                "}\n"
5696                "42");
5697 }
5698 
TEST_F(FormatTest,IncorrectCodeMissingSemicolon)5699 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
5700   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
5701   EXPECT_EQ("void f() {\n"
5702             "  if (a)\n"
5703             "    return\n"
5704             "}",
5705             format("void  f  (  )  {  if  ( a )  return  }"));
5706   EXPECT_EQ("namespace N {\n"
5707             "void f()\n"
5708             "}",
5709             format("namespace  N  {  void f()  }"));
5710   EXPECT_EQ("namespace N {\n"
5711             "void f() {}\n"
5712             "void g()\n"
5713             "}",
5714             format("namespace N  { void f( ) { } void g( ) }"));
5715 }
5716 
TEST_F(FormatTest,IndentationWithinColumnLimitNotPossible)5717 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
5718   verifyFormat("int aaaaaaaa =\n"
5719                "    // Overlylongcomment\n"
5720                "    b;",
5721                getLLVMStyleWithColumns(20));
5722   verifyFormat("function(\n"
5723                "    ShortArgument,\n"
5724                "    LoooooooooooongArgument);\n",
5725                getLLVMStyleWithColumns(20));
5726 }
5727 
TEST_F(FormatTest,IncorrectAccessSpecifier)5728 TEST_F(FormatTest, IncorrectAccessSpecifier) {
5729   verifyFormat("public:");
5730   verifyFormat("class A {\n"
5731                "public\n"
5732                "  void f() {}\n"
5733                "};");
5734   verifyFormat("public\n"
5735                "int qwerty;");
5736   verifyFormat("public\n"
5737                "B {}");
5738   verifyFormat("public\n"
5739                "{}");
5740   verifyFormat("public\n"
5741                "B { int x; }");
5742 }
5743 
TEST_F(FormatTest,IncorrectCodeUnbalancedBraces)5744 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
5745   verifyFormat("{");
5746   verifyFormat("#})");
5747 }
5748 
TEST_F(FormatTest,IncorrectCodeDoNoWhile)5749 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
5750   verifyFormat("do {\n}");
5751   verifyFormat("do {\n}\n"
5752                "f();");
5753   verifyFormat("do {\n}\n"
5754                "wheeee(fun);");
5755   verifyFormat("do {\n"
5756                "  f();\n"
5757                "}");
5758 }
5759 
TEST_F(FormatTest,IncorrectCodeMissingParens)5760 TEST_F(FormatTest, IncorrectCodeMissingParens) {
5761   verifyFormat("if {\n  foo;\n  foo();\n}");
5762   verifyFormat("switch {\n  foo;\n  foo();\n}");
5763   verifyFormat("for {\n  foo;\n  foo();\n}");
5764   verifyFormat("while {\n  foo;\n  foo();\n}");
5765   verifyFormat("do {\n  foo;\n  foo();\n} while;");
5766 }
5767 
TEST_F(FormatTest,DoesNotTouchUnwrappedLinesWithErrors)5768 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
5769   verifyFormat("namespace {\n"
5770                "class Foo { Foo (\n"
5771                "};\n"
5772                "} // comment");
5773 }
5774 
TEST_F(FormatTest,IncorrectCodeErrorDetection)5775 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
5776   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
5777   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
5778   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
5779   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
5780 
5781   EXPECT_EQ("{\n"
5782             "  {\n"
5783             "    breakme(\n"
5784             "        qwe);\n"
5785             "  }\n",
5786             format("{\n"
5787                    "    {\n"
5788                    " breakme(qwe);\n"
5789                    "}\n",
5790                    getLLVMStyleWithColumns(10)));
5791 }
5792 
TEST_F(FormatTest,LayoutCallsInsideBraceInitializers)5793 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
5794   verifyFormat("int x = {\n"
5795                "    avariable,\n"
5796                "    b(alongervariable)};",
5797                getLLVMStyleWithColumns(25));
5798 }
5799 
TEST_F(FormatTest,LayoutBraceInitializersInReturnStatement)5800 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
5801   verifyFormat("return (a)(b){1, 2, 3};");
5802 }
5803 
TEST_F(FormatTest,LayoutCxx11BraceInitializers)5804 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
5805   verifyFormat("vector<int> x{1, 2, 3, 4};");
5806   verifyFormat("vector<int> x{\n"
5807                "    1, 2, 3, 4,\n"
5808                "};");
5809   verifyFormat("vector<T> x{{}, {}, {}, {}};");
5810   verifyFormat("f({1, 2});");
5811   verifyFormat("auto v = Foo{-1};");
5812   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
5813   verifyFormat("Class::Class : member{1, 2, 3} {}");
5814   verifyFormat("new vector<int>{1, 2, 3};");
5815   verifyFormat("new int[3]{1, 2, 3};");
5816   verifyFormat("new int{1};");
5817   verifyFormat("return {arg1, arg2};");
5818   verifyFormat("return {arg1, SomeType{parameter}};");
5819   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
5820   verifyFormat("new T{arg1, arg2};");
5821   verifyFormat("f(MyMap[{composite, key}]);");
5822   verifyFormat("class Class {\n"
5823                "  T member = {arg1, arg2};\n"
5824                "};");
5825   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
5826   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
5827   verifyFormat("int a = std::is_integral<int>{} + 0;");
5828 
5829   verifyFormat("int foo(int i) { return fo1{}(i); }");
5830   verifyFormat("int foo(int i) { return fo1{}(i); }");
5831   verifyFormat("auto i = decltype(x){};");
5832   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
5833   verifyFormat("Node n{1, Node{1000}, //\n"
5834                "       2};");
5835 
5836   // In combination with BinPackParameters = false.
5837   FormatStyle NoBinPacking = getLLVMStyle();
5838   NoBinPacking.BinPackParameters = false;
5839   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
5840                "                      bbbbb,\n"
5841                "                      ccccc,\n"
5842                "                      ddddd,\n"
5843                "                      eeeee,\n"
5844                "                      ffffff,\n"
5845                "                      ggggg,\n"
5846                "                      hhhhhh,\n"
5847                "                      iiiiii,\n"
5848                "                      jjjjjj,\n"
5849                "                      kkkkkk};",
5850                NoBinPacking);
5851   verifyFormat("const Aaaaaa aaaaa = {\n"
5852                "    aaaaa,\n"
5853                "    bbbbb,\n"
5854                "    ccccc,\n"
5855                "    ddddd,\n"
5856                "    eeeee,\n"
5857                "    ffffff,\n"
5858                "    ggggg,\n"
5859                "    hhhhhh,\n"
5860                "    iiiiii,\n"
5861                "    jjjjjj,\n"
5862                "    kkkkkk,\n"
5863                "};",
5864                NoBinPacking);
5865   verifyFormat(
5866       "const Aaaaaa aaaaa = {\n"
5867       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
5868       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
5869       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
5870       "};",
5871       NoBinPacking);
5872 
5873   // FIXME: The alignment of these trailing comments might be bad. Then again,
5874   // this might be utterly useless in real code.
5875   verifyFormat("Constructor::Constructor()\n"
5876                "    : some_value{         //\n"
5877                "                 aaaaaaa, //\n"
5878                "                 bbbbbbb} {}");
5879 
5880   // In braced lists, the first comment is always assumed to belong to the
5881   // first element. Thus, it can be moved to the next or previous line as
5882   // appropriate.
5883   EXPECT_EQ("function({// First element:\n"
5884             "          1,\n"
5885             "          // Second element:\n"
5886             "          2});",
5887             format("function({\n"
5888                    "    // First element:\n"
5889                    "    1,\n"
5890                    "    // Second element:\n"
5891                    "    2});"));
5892   EXPECT_EQ("std::vector<int> MyNumbers{\n"
5893             "    // First element:\n"
5894             "    1,\n"
5895             "    // Second element:\n"
5896             "    2};",
5897             format("std::vector<int> MyNumbers{// First element:\n"
5898                    "                           1,\n"
5899                    "                           // Second element:\n"
5900                    "                           2};",
5901                    getLLVMStyleWithColumns(30)));
5902   // A trailing comma should still lead to an enforced line break.
5903   EXPECT_EQ("vector<int> SomeVector = {\n"
5904             "    // aaa\n"
5905             "    1, 2,\n"
5906             "};",
5907             format("vector<int> SomeVector = { // aaa\n"
5908                    "    1, 2, };"));
5909 
5910   FormatStyle ExtraSpaces = getLLVMStyle();
5911   ExtraSpaces.Cpp11BracedListStyle = false;
5912   ExtraSpaces.ColumnLimit = 75;
5913   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
5914   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
5915   verifyFormat("f({ 1, 2 });", ExtraSpaces);
5916   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
5917   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
5918   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
5919   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
5920   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
5921   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
5922   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
5923   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
5924   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
5925   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
5926   verifyFormat("class Class {\n"
5927                "  T member = { arg1, arg2 };\n"
5928                "};",
5929                ExtraSpaces);
5930   verifyFormat(
5931       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5932       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
5933       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5934       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
5935       ExtraSpaces);
5936   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
5937   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
5938                ExtraSpaces);
5939   verifyFormat(
5940       "someFunction(OtherParam,\n"
5941       "             BracedList{ // comment 1 (Forcing interesting break)\n"
5942       "                         param1, param2,\n"
5943       "                         // comment 2\n"
5944       "                         param3, param4 });",
5945       ExtraSpaces);
5946   verifyFormat(
5947       "std::this_thread::sleep_for(\n"
5948       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
5949       ExtraSpaces);
5950   verifyFormat(
5951       "std::vector<MyValues> aaaaaaaaaaaaaaaaaaa{\n"
5952       "    aaaaaaa, aaaaaaaaaa, aaaaa, aaaaaaaaaaaaaaa, aaa, aaaaaaaaaa, a,\n"
5953       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaa,\n"
5954       "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa, aaaaaaa, a};");
5955   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
5956 }
5957 
TEST_F(FormatTest,FormatsBracedListsInColumnLayout)5958 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
5959   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
5960                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
5961                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
5962                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
5963                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
5964                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
5965   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
5966                "                 // line comment\n"
5967                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
5968                "                 1, 22, 333, 4444, 55555,\n"
5969                "                 // line comment\n"
5970                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
5971                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
5972   verifyFormat(
5973       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
5974       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
5975       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
5976       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
5977       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
5978       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
5979       "                 7777777};");
5980   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
5981                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
5982                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
5983   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
5984                "                 1, 1, 1, 1};",
5985                getLLVMStyleWithColumns(39));
5986   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
5987                "                 1, 1, 1, 1};",
5988                getLLVMStyleWithColumns(38));
5989   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
5990                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
5991                getLLVMStyleWithColumns(43));
5992 
5993   // Trailing commas.
5994   verifyFormat("vector<int> x = {\n"
5995                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
5996                "};",
5997                getLLVMStyleWithColumns(39));
5998   verifyFormat("vector<int> x = {\n"
5999                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
6000                "};",
6001                getLLVMStyleWithColumns(39));
6002   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
6003                "                 1, 1, 1, 1,\n"
6004                "                 /**/ /**/};",
6005                getLLVMStyleWithColumns(39));
6006   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
6007                "        {aaaaaaaaaaaaaaaaaaa},\n"
6008                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
6009                "        {aaaaaaaaaaaaaaaaa}};",
6010                getLLVMStyleWithColumns(60));
6011 
6012   // With nested lists, we should either format one item per line or all nested
6013   // lists one one line.
6014   // FIXME: For some nested lists, we can do better.
6015   verifyFormat(
6016       "SomeStruct my_struct_array = {\n"
6017       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
6018       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
6019       "    {aaa, aaa},\n"
6020       "    {aaa, aaa},\n"
6021       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
6022       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6023       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
6024 
6025   // No column layout should be used here.
6026   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
6027                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
6028 }
6029 
TEST_F(FormatTest,PullTrivialFunctionDefinitionsIntoSingleLine)6030 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
6031   FormatStyle DoNotMerge = getLLVMStyle();
6032   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6033 
6034   verifyFormat("void f() { return 42; }");
6035   verifyFormat("void f() {\n"
6036                "  return 42;\n"
6037                "}",
6038                DoNotMerge);
6039   verifyFormat("void f() {\n"
6040                "  // Comment\n"
6041                "}");
6042   verifyFormat("{\n"
6043                "#error {\n"
6044                "  int a;\n"
6045                "}");
6046   verifyFormat("{\n"
6047                "  int a;\n"
6048                "#error {\n"
6049                "}");
6050   verifyFormat("void f() {} // comment");
6051   verifyFormat("void f() { int a; } // comment");
6052   verifyFormat("void f() {\n"
6053                "} // comment",
6054                DoNotMerge);
6055   verifyFormat("void f() {\n"
6056                "  int a;\n"
6057                "} // comment",
6058                DoNotMerge);
6059   verifyFormat("void f() {\n"
6060                "} // comment",
6061                getLLVMStyleWithColumns(15));
6062 
6063   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
6064   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
6065 
6066   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
6067   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
6068   verifyFormat("class C {\n"
6069                "  C()\n"
6070                "      : iiiiiiii(nullptr),\n"
6071                "        kkkkkkk(nullptr),\n"
6072                "        mmmmmmm(nullptr),\n"
6073                "        nnnnnnn(nullptr) {}\n"
6074                "};",
6075                getGoogleStyle());
6076 
6077   FormatStyle NoColumnLimit = getLLVMStyle();
6078   NoColumnLimit.ColumnLimit = 0;
6079   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
6080   EXPECT_EQ("class C {\n"
6081             "  A() : b(0) {}\n"
6082             "};", format("class C{A():b(0){}};", NoColumnLimit));
6083   EXPECT_EQ("A()\n"
6084             "    : b(0) {\n"
6085             "}",
6086             format("A()\n:b(0)\n{\n}", NoColumnLimit));
6087 
6088   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
6089   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
6090       FormatStyle::SFS_None;
6091   EXPECT_EQ("A()\n"
6092             "    : b(0) {\n"
6093             "}",
6094             format("A():b(0){}", DoNotMergeNoColumnLimit));
6095   EXPECT_EQ("A()\n"
6096             "    : b(0) {\n"
6097             "}",
6098             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
6099 
6100   verifyFormat("#define A          \\\n"
6101                "  void f() {       \\\n"
6102                "    int i;         \\\n"
6103                "  }",
6104                getLLVMStyleWithColumns(20));
6105   verifyFormat("#define A           \\\n"
6106                "  void f() { int i; }",
6107                getLLVMStyleWithColumns(21));
6108   verifyFormat("#define A            \\\n"
6109                "  void f() {         \\\n"
6110                "    int i;           \\\n"
6111                "  }                  \\\n"
6112                "  int j;",
6113                getLLVMStyleWithColumns(22));
6114   verifyFormat("#define A             \\\n"
6115                "  void f() { int i; } \\\n"
6116                "  int j;",
6117                getLLVMStyleWithColumns(23));
6118 }
6119 
TEST_F(FormatTest,PullInlineFunctionDefinitionsIntoSingleLine)6120 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
6121   FormatStyle MergeInlineOnly = getLLVMStyle();
6122   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
6123   verifyFormat("class C {\n"
6124                "  int f() { return 42; }\n"
6125                "};",
6126                MergeInlineOnly);
6127   verifyFormat("int f() {\n"
6128                "  return 42;\n"
6129                "}",
6130                MergeInlineOnly);
6131 }
6132 
TEST_F(FormatTest,UnderstandContextOfRecordTypeKeywords)6133 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
6134   // Elaborate type variable declarations.
6135   verifyFormat("struct foo a = {bar};\nint n;");
6136   verifyFormat("class foo a = {bar};\nint n;");
6137   verifyFormat("union foo a = {bar};\nint n;");
6138 
6139   // Elaborate types inside function definitions.
6140   verifyFormat("struct foo f() {}\nint n;");
6141   verifyFormat("class foo f() {}\nint n;");
6142   verifyFormat("union foo f() {}\nint n;");
6143 
6144   // Templates.
6145   verifyFormat("template <class X> void f() {}\nint n;");
6146   verifyFormat("template <struct X> void f() {}\nint n;");
6147   verifyFormat("template <union X> void f() {}\nint n;");
6148 
6149   // Actual definitions...
6150   verifyFormat("struct {\n} n;");
6151   verifyFormat(
6152       "template <template <class T, class Y>, class Z> class X {\n} n;");
6153   verifyFormat("union Z {\n  int n;\n} x;");
6154   verifyFormat("class MACRO Z {\n} n;");
6155   verifyFormat("class MACRO(X) Z {\n} n;");
6156   verifyFormat("class __attribute__(X) Z {\n} n;");
6157   verifyFormat("class __declspec(X) Z {\n} n;");
6158   verifyFormat("class A##B##C {\n} n;");
6159   verifyFormat("class alignas(16) Z {\n} n;");
6160 
6161   // Redefinition from nested context:
6162   verifyFormat("class A::B::C {\n} n;");
6163 
6164   // Template definitions.
6165   verifyFormat(
6166       "template <typename F>\n"
6167       "Matcher(const Matcher<F> &Other,\n"
6168       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
6169       "                             !is_same<F, T>::value>::type * = 0)\n"
6170       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
6171 
6172   // FIXME: This is still incorrectly handled at the formatter side.
6173   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
6174 
6175   // FIXME:
6176   // This now gets parsed incorrectly as class definition.
6177   // verifyFormat("class A<int> f() {\n}\nint n;");
6178 
6179   // Elaborate types where incorrectly parsing the structural element would
6180   // break the indent.
6181   verifyFormat("if (true)\n"
6182                "  class X x;\n"
6183                "else\n"
6184                "  f();\n");
6185 
6186   // This is simply incomplete. Formatting is not important, but must not crash.
6187   verifyFormat("class A:");
6188 }
6189 
TEST_F(FormatTest,DoNotInterfereWithErrorAndWarning)6190 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
6191   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
6192             format("#error Leave     all         white!!!!! space* alone!\n"));
6193   EXPECT_EQ(
6194       "#warning Leave     all         white!!!!! space* alone!\n",
6195       format("#warning Leave     all         white!!!!! space* alone!\n"));
6196   EXPECT_EQ("#error 1", format("  #  error   1"));
6197   EXPECT_EQ("#warning 1", format("  #  warning 1"));
6198 }
6199 
TEST_F(FormatTest,FormatHashIfExpressions)6200 TEST_F(FormatTest, FormatHashIfExpressions) {
6201   verifyFormat("#if AAAA && BBBB");
6202   // FIXME: Come up with a better indentation for #elif.
6203   verifyFormat(
6204       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
6205       "    defined(BBBBBBBB)\n"
6206       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
6207       "    defined(BBBBBBBB)\n"
6208       "#endif",
6209       getLLVMStyleWithColumns(65));
6210 }
6211 
TEST_F(FormatTest,MergeHandlingInTheFaceOfPreprocessorDirectives)6212 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
6213   FormatStyle AllowsMergedIf = getGoogleStyle();
6214   AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
6215   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
6216   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
6217   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
6218   EXPECT_EQ("if (true) return 42;",
6219             format("if (true)\nreturn 42;", AllowsMergedIf));
6220   FormatStyle ShortMergedIf = AllowsMergedIf;
6221   ShortMergedIf.ColumnLimit = 25;
6222   verifyFormat("#define A \\\n"
6223                "  if (true) return 42;",
6224                ShortMergedIf);
6225   verifyFormat("#define A \\\n"
6226                "  f();    \\\n"
6227                "  if (true)\n"
6228                "#define B",
6229                ShortMergedIf);
6230   verifyFormat("#define A \\\n"
6231                "  f();    \\\n"
6232                "  if (true)\n"
6233                "g();",
6234                ShortMergedIf);
6235   verifyFormat("{\n"
6236                "#ifdef A\n"
6237                "  // Comment\n"
6238                "  if (true) continue;\n"
6239                "#endif\n"
6240                "  // Comment\n"
6241                "  if (true) continue;\n"
6242                "}",
6243                ShortMergedIf);
6244   ShortMergedIf.ColumnLimit = 29;
6245   verifyFormat("#define A                   \\\n"
6246                "  if (aaaaaaaaaa) return 1; \\\n"
6247                "  return 2;",
6248                ShortMergedIf);
6249   ShortMergedIf.ColumnLimit = 28;
6250   verifyFormat("#define A         \\\n"
6251                "  if (aaaaaaaaaa) \\\n"
6252                "    return 1;     \\\n"
6253                "  return 2;",
6254                ShortMergedIf);
6255 }
6256 
TEST_F(FormatTest,BlockCommentsInControlLoops)6257 TEST_F(FormatTest, BlockCommentsInControlLoops) {
6258   verifyFormat("if (0) /* a comment in a strange place */ {\n"
6259                "  f();\n"
6260                "}");
6261   verifyFormat("if (0) /* a comment in a strange place */ {\n"
6262                "  f();\n"
6263                "} /* another comment */ else /* comment #3 */ {\n"
6264                "  g();\n"
6265                "}");
6266   verifyFormat("while (0) /* a comment in a strange place */ {\n"
6267                "  f();\n"
6268                "}");
6269   verifyFormat("for (;;) /* a comment in a strange place */ {\n"
6270                "  f();\n"
6271                "}");
6272   verifyFormat("do /* a comment in a strange place */ {\n"
6273                "  f();\n"
6274                "} /* another comment */ while (0);");
6275 }
6276 
TEST_F(FormatTest,BlockComments)6277 TEST_F(FormatTest, BlockComments) {
6278   EXPECT_EQ("/* */ /* */ /* */\n/* */ /* */ /* */",
6279             format("/* *//* */  /* */\n/* *//* */  /* */"));
6280   EXPECT_EQ("/* */ a /* */ b;", format("  /* */  a/* */  b;"));
6281   EXPECT_EQ("#define A /*123*/ \\\n"
6282             "  b\n"
6283             "/* */\n"
6284             "someCall(\n"
6285             "    parameter);",
6286             format("#define A /*123*/ b\n"
6287                    "/* */\n"
6288                    "someCall(parameter);",
6289                    getLLVMStyleWithColumns(15)));
6290 
6291   EXPECT_EQ("#define A\n"
6292             "/* */ someCall(\n"
6293             "    parameter);",
6294             format("#define A\n"
6295                    "/* */someCall(parameter);",
6296                    getLLVMStyleWithColumns(15)));
6297   EXPECT_EQ("/*\n**\n*/", format("/*\n**\n*/"));
6298   EXPECT_EQ("/*\n"
6299             "*\n"
6300             " * aaaaaa\n"
6301             "*aaaaaa\n"
6302             "*/",
6303             format("/*\n"
6304                    "*\n"
6305                    " * aaaaaa aaaaaa\n"
6306                    "*/",
6307                    getLLVMStyleWithColumns(10)));
6308   EXPECT_EQ("/*\n"
6309             "**\n"
6310             "* aaaaaa\n"
6311             "*aaaaaa\n"
6312             "*/",
6313             format("/*\n"
6314                    "**\n"
6315                    "* aaaaaa aaaaaa\n"
6316                    "*/",
6317                    getLLVMStyleWithColumns(10)));
6318 
6319   FormatStyle NoBinPacking = getLLVMStyle();
6320   NoBinPacking.BinPackParameters = false;
6321   EXPECT_EQ("someFunction(1, /* comment 1 */\n"
6322             "             2, /* comment 2 */\n"
6323             "             3, /* comment 3 */\n"
6324             "             aaaa,\n"
6325             "             bbbb);",
6326             format("someFunction (1,   /* comment 1 */\n"
6327                    "                2, /* comment 2 */  \n"
6328                    "               3,   /* comment 3 */\n"
6329                    "aaaa, bbbb );",
6330                    NoBinPacking));
6331   verifyFormat(
6332       "bool aaaaaaaaaaaaa = /* comment: */ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6333       "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6334   EXPECT_EQ(
6335       "bool aaaaaaaaaaaaa = /* trailing comment */\n"
6336       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6337       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;",
6338       format(
6339           "bool       aaaaaaaaaaaaa =       /* trailing comment */\n"
6340           "    aaaaaaaaaaaaaaaaaaaaaaaaaaa||aaaaaaaaaaaaaaaaaaaaaaaaa    ||\n"
6341           "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa   || aaaaaaaaaaaaaaaaaaaaaaaaaa;"));
6342   EXPECT_EQ(
6343       "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
6344       "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   /* comment */\n"
6345       "int cccccccccccccccccccccccccccccc;       /* comment */\n",
6346       format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
6347              "int      bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n"
6348              "int    cccccccccccccccccccccccccccccc;  /* comment */\n"));
6349 
6350   verifyFormat("void f(int * /* unused */) {}");
6351 
6352   EXPECT_EQ("/*\n"
6353             " **\n"
6354             " */",
6355             format("/*\n"
6356                    " **\n"
6357                    " */"));
6358   EXPECT_EQ("/*\n"
6359             " *q\n"
6360             " */",
6361             format("/*\n"
6362                    " *q\n"
6363                    " */"));
6364   EXPECT_EQ("/*\n"
6365             " * q\n"
6366             " */",
6367             format("/*\n"
6368                    " * q\n"
6369                    " */"));
6370   EXPECT_EQ("/*\n"
6371             " **/",
6372             format("/*\n"
6373                    " **/"));
6374   EXPECT_EQ("/*\n"
6375             " ***/",
6376             format("/*\n"
6377                    " ***/"));
6378 }
6379 
TEST_F(FormatTest,BlockCommentsInMacros)6380 TEST_F(FormatTest, BlockCommentsInMacros) {
6381   EXPECT_EQ("#define A          \\\n"
6382             "  {                \\\n"
6383             "    /* one line */ \\\n"
6384             "    someCall();",
6385             format("#define A {        \\\n"
6386                    "  /* one line */   \\\n"
6387                    "  someCall();",
6388                    getLLVMStyleWithColumns(20)));
6389   EXPECT_EQ("#define A          \\\n"
6390             "  {                \\\n"
6391             "    /* previous */ \\\n"
6392             "    /* one line */ \\\n"
6393             "    someCall();",
6394             format("#define A {        \\\n"
6395                    "  /* previous */   \\\n"
6396                    "  /* one line */   \\\n"
6397                    "  someCall();",
6398                    getLLVMStyleWithColumns(20)));
6399 }
6400 
TEST_F(FormatTest,BlockCommentsAtEndOfLine)6401 TEST_F(FormatTest, BlockCommentsAtEndOfLine) {
6402   EXPECT_EQ("a = {\n"
6403             "    1111 /*    */\n"
6404             "};",
6405             format("a = {1111 /*    */\n"
6406                    "};",
6407                    getLLVMStyleWithColumns(15)));
6408   EXPECT_EQ("a = {\n"
6409             "    1111 /*      */\n"
6410             "};",
6411             format("a = {1111 /*      */\n"
6412                    "};",
6413                    getLLVMStyleWithColumns(15)));
6414 
6415   // FIXME: The formatting is still wrong here.
6416   EXPECT_EQ("a = {\n"
6417             "    1111 /*      a\n"
6418             "            */\n"
6419             "};",
6420             format("a = {1111 /*      a */\n"
6421                    "};",
6422                    getLLVMStyleWithColumns(15)));
6423 }
6424 
TEST_F(FormatTest,IndentLineCommentsInStartOfBlockAtEndOfFile)6425 TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
6426   // FIXME: This is not what we want...
6427   verifyFormat("{\n"
6428                "// a"
6429                "// b");
6430 }
6431 
TEST_F(FormatTest,FormatStarDependingOnContext)6432 TEST_F(FormatTest, FormatStarDependingOnContext) {
6433   verifyFormat("void f(int *a);");
6434   verifyFormat("void f() { f(fint * b); }");
6435   verifyFormat("class A {\n  void f(int *a);\n};");
6436   verifyFormat("class A {\n  int *a;\n};");
6437   verifyFormat("namespace a {\n"
6438                "namespace b {\n"
6439                "class A {\n"
6440                "  void f() {}\n"
6441                "  int *a;\n"
6442                "};\n"
6443                "}\n"
6444                "}");
6445 }
6446 
TEST_F(FormatTest,SpecialTokensAtEndOfLine)6447 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
6448   verifyFormat("while");
6449   verifyFormat("operator");
6450 }
6451 
6452 //===----------------------------------------------------------------------===//
6453 // Objective-C tests.
6454 //===----------------------------------------------------------------------===//
6455 
TEST_F(FormatTest,FormatForObjectiveCMethodDecls)6456 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
6457   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
6458   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
6459             format("-(NSUInteger)indexOfObject:(id)anObject;"));
6460   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
6461   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
6462   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
6463             format("-(NSInteger)Method3:(id)anObject;"));
6464   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
6465             format("-(NSInteger)Method4:(id)anObject;"));
6466   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
6467             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
6468   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
6469             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
6470   EXPECT_EQ(
6471       "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;",
6472       format(
6473           "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;"));
6474 
6475   // Very long objectiveC method declaration.
6476   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
6477                "                    inRange:(NSRange)range\n"
6478                "                   outRange:(NSRange)out_range\n"
6479                "                  outRange1:(NSRange)out_range1\n"
6480                "                  outRange2:(NSRange)out_range2\n"
6481                "                  outRange3:(NSRange)out_range3\n"
6482                "                  outRange4:(NSRange)out_range4\n"
6483                "                  outRange5:(NSRange)out_range5\n"
6484                "                  outRange6:(NSRange)out_range6\n"
6485                "                  outRange7:(NSRange)out_range7\n"
6486                "                  outRange8:(NSRange)out_range8\n"
6487                "                  outRange9:(NSRange)out_range9;");
6488 
6489   verifyFormat("- (int)sum:(vector<int>)numbers;");
6490   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
6491   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
6492   // protocol lists (but not for template classes):
6493   //verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
6494 
6495   verifyFormat("- (int (*)())foo:(int (*)())f;");
6496   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
6497 
6498   // If there's no return type (very rare in practice!), LLVM and Google style
6499   // agree.
6500   verifyFormat("- foo;");
6501   verifyFormat("- foo:(int)f;");
6502   verifyGoogleFormat("- foo:(int)foo;");
6503 }
6504 
TEST_F(FormatTest,FormatObjCInterface)6505 TEST_F(FormatTest, FormatObjCInterface) {
6506   verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
6507                "@public\n"
6508                "  int field1;\n"
6509                "@protected\n"
6510                "  int field2;\n"
6511                "@private\n"
6512                "  int field3;\n"
6513                "@package\n"
6514                "  int field4;\n"
6515                "}\n"
6516                "+ (id)init;\n"
6517                "@end");
6518 
6519   verifyGoogleFormat("@interface Foo : NSObject<NSSomeDelegate> {\n"
6520                      " @public\n"
6521                      "  int field1;\n"
6522                      " @protected\n"
6523                      "  int field2;\n"
6524                      " @private\n"
6525                      "  int field3;\n"
6526                      " @package\n"
6527                      "  int field4;\n"
6528                      "}\n"
6529                      "+ (id)init;\n"
6530                      "@end");
6531 
6532   verifyFormat("@interface /* wait for it */ Foo\n"
6533                "+ (id)init;\n"
6534                "// Look, a comment!\n"
6535                "- (int)answerWith:(int)i;\n"
6536                "@end");
6537 
6538   verifyFormat("@interface Foo\n"
6539                "@end\n"
6540                "@interface Bar\n"
6541                "@end");
6542 
6543   verifyFormat("@interface Foo : Bar\n"
6544                "+ (id)init;\n"
6545                "@end");
6546 
6547   verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
6548                "+ (id)init;\n"
6549                "@end");
6550 
6551   verifyGoogleFormat("@interface Foo : Bar<Baz, Quux>\n"
6552                      "+ (id)init;\n"
6553                      "@end");
6554 
6555   verifyFormat("@interface Foo (HackStuff)\n"
6556                "+ (id)init;\n"
6557                "@end");
6558 
6559   verifyFormat("@interface Foo ()\n"
6560                "+ (id)init;\n"
6561                "@end");
6562 
6563   verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
6564                "+ (id)init;\n"
6565                "@end");
6566 
6567   verifyGoogleFormat("@interface Foo (HackStuff) <MyProtocol>\n"
6568                      "+ (id)init;\n"
6569                      "@end");
6570 
6571   verifyFormat("@interface Foo {\n"
6572                "  int _i;\n"
6573                "}\n"
6574                "+ (id)init;\n"
6575                "@end");
6576 
6577   verifyFormat("@interface Foo : Bar {\n"
6578                "  int _i;\n"
6579                "}\n"
6580                "+ (id)init;\n"
6581                "@end");
6582 
6583   verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
6584                "  int _i;\n"
6585                "}\n"
6586                "+ (id)init;\n"
6587                "@end");
6588 
6589   verifyFormat("@interface Foo (HackStuff) {\n"
6590                "  int _i;\n"
6591                "}\n"
6592                "+ (id)init;\n"
6593                "@end");
6594 
6595   verifyFormat("@interface Foo () {\n"
6596                "  int _i;\n"
6597                "}\n"
6598                "+ (id)init;\n"
6599                "@end");
6600 
6601   verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
6602                "  int _i;\n"
6603                "}\n"
6604                "+ (id)init;\n"
6605                "@end");
6606 
6607   FormatStyle OnePerLine = getGoogleStyle();
6608   OnePerLine.BinPackParameters = false;
6609   verifyFormat("@interface aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa () <\n"
6610                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6611                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6612                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6613                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
6614                "}",
6615                OnePerLine);
6616 }
6617 
TEST_F(FormatTest,FormatObjCImplementation)6618 TEST_F(FormatTest, FormatObjCImplementation) {
6619   verifyFormat("@implementation Foo : NSObject {\n"
6620                "@public\n"
6621                "  int field1;\n"
6622                "@protected\n"
6623                "  int field2;\n"
6624                "@private\n"
6625                "  int field3;\n"
6626                "@package\n"
6627                "  int field4;\n"
6628                "}\n"
6629                "+ (id)init {\n}\n"
6630                "@end");
6631 
6632   verifyGoogleFormat("@implementation Foo : NSObject {\n"
6633                      " @public\n"
6634                      "  int field1;\n"
6635                      " @protected\n"
6636                      "  int field2;\n"
6637                      " @private\n"
6638                      "  int field3;\n"
6639                      " @package\n"
6640                      "  int field4;\n"
6641                      "}\n"
6642                      "+ (id)init {\n}\n"
6643                      "@end");
6644 
6645   verifyFormat("@implementation Foo\n"
6646                "+ (id)init {\n"
6647                "  if (true)\n"
6648                "    return nil;\n"
6649                "}\n"
6650                "// Look, a comment!\n"
6651                "- (int)answerWith:(int)i {\n"
6652                "  return i;\n"
6653                "}\n"
6654                "+ (int)answerWith:(int)i {\n"
6655                "  return i;\n"
6656                "}\n"
6657                "@end");
6658 
6659   verifyFormat("@implementation Foo\n"
6660                "@end\n"
6661                "@implementation Bar\n"
6662                "@end");
6663 
6664   EXPECT_EQ("@implementation Foo : Bar\n"
6665             "+ (id)init {\n}\n"
6666             "- (void)foo {\n}\n"
6667             "@end",
6668             format("@implementation Foo : Bar\n"
6669                    "+(id)init{}\n"
6670                    "-(void)foo{}\n"
6671                    "@end"));
6672 
6673   verifyFormat("@implementation Foo {\n"
6674                "  int _i;\n"
6675                "}\n"
6676                "+ (id)init {\n}\n"
6677                "@end");
6678 
6679   verifyFormat("@implementation Foo : Bar {\n"
6680                "  int _i;\n"
6681                "}\n"
6682                "+ (id)init {\n}\n"
6683                "@end");
6684 
6685   verifyFormat("@implementation Foo (HackStuff)\n"
6686                "+ (id)init {\n}\n"
6687                "@end");
6688   verifyFormat("@implementation ObjcClass\n"
6689                "- (void)method;\n"
6690                "{}\n"
6691                "@end");
6692 }
6693 
TEST_F(FormatTest,FormatObjCProtocol)6694 TEST_F(FormatTest, FormatObjCProtocol) {
6695   verifyFormat("@protocol Foo\n"
6696                "@property(weak) id delegate;\n"
6697                "- (NSUInteger)numberOfThings;\n"
6698                "@end");
6699 
6700   verifyFormat("@protocol MyProtocol <NSObject>\n"
6701                "- (NSUInteger)numberOfThings;\n"
6702                "@end");
6703 
6704   verifyGoogleFormat("@protocol MyProtocol<NSObject>\n"
6705                      "- (NSUInteger)numberOfThings;\n"
6706                      "@end");
6707 
6708   verifyFormat("@protocol Foo;\n"
6709                "@protocol Bar;\n");
6710 
6711   verifyFormat("@protocol Foo\n"
6712                "@end\n"
6713                "@protocol Bar\n"
6714                "@end");
6715 
6716   verifyFormat("@protocol myProtocol\n"
6717                "- (void)mandatoryWithInt:(int)i;\n"
6718                "@optional\n"
6719                "- (void)optional;\n"
6720                "@required\n"
6721                "- (void)required;\n"
6722                "@optional\n"
6723                "@property(assign) int madProp;\n"
6724                "@end\n");
6725 
6726   verifyFormat("@property(nonatomic, assign, readonly)\n"
6727                "    int *looooooooooooooooooooooooooooongNumber;\n"
6728                "@property(nonatomic, assign, readonly)\n"
6729                "    NSString *looooooooooooooooooooooooooooongName;");
6730 
6731   verifyFormat("@implementation PR18406\n"
6732                "}\n"
6733                "@end");
6734 }
6735 
TEST_F(FormatTest,FormatObjCMethodDeclarations)6736 TEST_F(FormatTest, FormatObjCMethodDeclarations) {
6737   verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
6738                "                   rect:(NSRect)theRect\n"
6739                "               interval:(float)theInterval {\n"
6740                "}");
6741   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
6742                "          longKeyword:(NSRect)theRect\n"
6743                "    evenLongerKeyword:(float)theInterval\n"
6744                "                error:(NSError **)theError {\n"
6745                "}");
6746   verifyFormat("- (instancetype)initXxxxxx:(id<x>)x\n"
6747                "                         y:(id<yyyyyyyyyyyyyyyyyyyy>)y\n"
6748                "    NS_DESIGNATED_INITIALIZER;",
6749                getLLVMStyleWithColumns(60));
6750 }
6751 
TEST_F(FormatTest,FormatObjCMethodExpr)6752 TEST_F(FormatTest, FormatObjCMethodExpr) {
6753   verifyFormat("[foo bar:baz];");
6754   verifyFormat("return [foo bar:baz];");
6755   verifyFormat("return (a)[foo bar:baz];");
6756   verifyFormat("f([foo bar:baz]);");
6757   verifyFormat("f(2, [foo bar:baz]);");
6758   verifyFormat("f(2, a ? b : c);");
6759   verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
6760 
6761   // Unary operators.
6762   verifyFormat("int a = +[foo bar:baz];");
6763   verifyFormat("int a = -[foo bar:baz];");
6764   verifyFormat("int a = ![foo bar:baz];");
6765   verifyFormat("int a = ~[foo bar:baz];");
6766   verifyFormat("int a = ++[foo bar:baz];");
6767   verifyFormat("int a = --[foo bar:baz];");
6768   verifyFormat("int a = sizeof [foo bar:baz];");
6769   verifyFormat("int a = alignof [foo bar:baz];", getGoogleStyle());
6770   verifyFormat("int a = &[foo bar:baz];");
6771   verifyFormat("int a = *[foo bar:baz];");
6772   // FIXME: Make casts work, without breaking f()[4].
6773   //verifyFormat("int a = (int)[foo bar:baz];");
6774   //verifyFormat("return (int)[foo bar:baz];");
6775   //verifyFormat("(void)[foo bar:baz];");
6776   verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
6777 
6778   // Binary operators.
6779   verifyFormat("[foo bar:baz], [foo bar:baz];");
6780   verifyFormat("[foo bar:baz] = [foo bar:baz];");
6781   verifyFormat("[foo bar:baz] *= [foo bar:baz];");
6782   verifyFormat("[foo bar:baz] /= [foo bar:baz];");
6783   verifyFormat("[foo bar:baz] %= [foo bar:baz];");
6784   verifyFormat("[foo bar:baz] += [foo bar:baz];");
6785   verifyFormat("[foo bar:baz] -= [foo bar:baz];");
6786   verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
6787   verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
6788   verifyFormat("[foo bar:baz] &= [foo bar:baz];");
6789   verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
6790   verifyFormat("[foo bar:baz] |= [foo bar:baz];");
6791   verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
6792   verifyFormat("[foo bar:baz] || [foo bar:baz];");
6793   verifyFormat("[foo bar:baz] && [foo bar:baz];");
6794   verifyFormat("[foo bar:baz] | [foo bar:baz];");
6795   verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
6796   verifyFormat("[foo bar:baz] & [foo bar:baz];");
6797   verifyFormat("[foo bar:baz] == [foo bar:baz];");
6798   verifyFormat("[foo bar:baz] != [foo bar:baz];");
6799   verifyFormat("[foo bar:baz] >= [foo bar:baz];");
6800   verifyFormat("[foo bar:baz] <= [foo bar:baz];");
6801   verifyFormat("[foo bar:baz] > [foo bar:baz];");
6802   verifyFormat("[foo bar:baz] < [foo bar:baz];");
6803   verifyFormat("[foo bar:baz] >> [foo bar:baz];");
6804   verifyFormat("[foo bar:baz] << [foo bar:baz];");
6805   verifyFormat("[foo bar:baz] - [foo bar:baz];");
6806   verifyFormat("[foo bar:baz] + [foo bar:baz];");
6807   verifyFormat("[foo bar:baz] * [foo bar:baz];");
6808   verifyFormat("[foo bar:baz] / [foo bar:baz];");
6809   verifyFormat("[foo bar:baz] % [foo bar:baz];");
6810   // Whew!
6811 
6812   verifyFormat("return in[42];");
6813   verifyFormat("for (auto v : in[1]) {\n}");
6814   verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
6815                "}");
6816   verifyFormat("[self aaaaa:MACRO(a, b:, c:)];");
6817 
6818   verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
6819   verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
6820   verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
6821   verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
6822   verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
6823   verifyFormat("[button setAction:@selector(zoomOut:)];");
6824   verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
6825 
6826   verifyFormat("arr[[self indexForFoo:a]];");
6827   verifyFormat("throw [self errorFor:a];");
6828   verifyFormat("@throw [self errorFor:a];");
6829 
6830   verifyFormat("[(id)foo bar:(id)baz quux:(id)snorf];");
6831   verifyFormat("[(id)foo bar:(id) ? baz : quux];");
6832   verifyFormat("4 > 4 ? (id)a : (id)baz;");
6833 
6834   // This tests that the formatter doesn't break after "backing" but before ":",
6835   // which would be at 80 columns.
6836   verifyFormat(
6837       "void f() {\n"
6838       "  if ((self = [super initWithContentRect:contentRect\n"
6839       "                               styleMask:styleMask ?: otherMask\n"
6840       "                                 backing:NSBackingStoreBuffered\n"
6841       "                                   defer:YES]))");
6842 
6843   verifyFormat(
6844       "[foo checkThatBreakingAfterColonWorksOk:\n"
6845       "         [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
6846 
6847   verifyFormat("[myObj short:arg1 // Force line break\n"
6848                "          longKeyword:arg2 != nil ? arg2 : @\"longKeyword\"\n"
6849                "    evenLongerKeyword:arg3 ?: @\"evenLongerKeyword\"\n"
6850                "                error:arg4];");
6851   verifyFormat(
6852       "void f() {\n"
6853       "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
6854       "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
6855       "                                     pos.width(), pos.height())\n"
6856       "                styleMask:NSBorderlessWindowMask\n"
6857       "                  backing:NSBackingStoreBuffered\n"
6858       "                    defer:NO]);\n"
6859       "}");
6860   verifyFormat(
6861       "void f() {\n"
6862       "  popup_wdow_.reset([[RenderWidgetPopupWindow alloc]\n"
6863       "      iniithContentRect:NSMakRet(origin_global.x, origin_global.y,\n"
6864       "                                 pos.width(), pos.height())\n"
6865       "                syeMask:NSBorderlessWindowMask\n"
6866       "                  bking:NSBackingStoreBuffered\n"
6867       "                    der:NO]);\n"
6868       "}",
6869       getLLVMStyleWithColumns(70));
6870   verifyFormat(
6871       "void f() {\n"
6872       "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
6873       "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
6874       "                                     pos.width(), pos.height())\n"
6875       "                styleMask:NSBorderlessWindowMask\n"
6876       "                  backing:NSBackingStoreBuffered\n"
6877       "                    defer:NO]);\n"
6878       "}",
6879       getChromiumStyle(FormatStyle::LK_Cpp));
6880   verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
6881                "                             with:contentsNativeView];");
6882 
6883   verifyFormat(
6884       "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
6885       "           owner:nillllll];");
6886 
6887   verifyFormat(
6888       "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
6889       "        forType:kBookmarkButtonDragType];");
6890 
6891   verifyFormat("[defaultCenter addObserver:self\n"
6892                "                  selector:@selector(willEnterFullscreen)\n"
6893                "                      name:kWillEnterFullscreenNotification\n"
6894                "                    object:nil];");
6895   verifyFormat("[image_rep drawInRect:drawRect\n"
6896                "             fromRect:NSZeroRect\n"
6897                "            operation:NSCompositeCopy\n"
6898                "             fraction:1.0\n"
6899                "       respectFlipped:NO\n"
6900                "                hints:nil];");
6901 
6902   verifyFormat(
6903       "scoped_nsobject<NSTextField> message(\n"
6904       "    // The frame will be fixed up when |-setMessageText:| is called.\n"
6905       "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
6906   verifyFormat("[self aaaaaa:bbbbbbbbbbbbb\n"
6907                "    aaaaaaaaaa:bbbbbbbbbbbbbbbbb\n"
6908                "         aaaaa:bbbbbbbbbbb + bbbbbbbbbbbb\n"
6909                "          aaaa:bbb];");
6910   verifyFormat("[self param:function( //\n"
6911                "                parameter)]");
6912   verifyFormat(
6913       "[self aaaaaaaaaa:aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
6914       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
6915       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa];");
6916 
6917   // Variadic parameters.
6918   verifyFormat(
6919       "NSArray *myStrings = [NSArray stringarray:@\"a\", @\"b\", nil];");
6920   verifyFormat(
6921       "[self aaaaaaaaaaaaa:aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
6922       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
6923       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa];");
6924   verifyFormat("[self // break\n"
6925                "      a:a\n"
6926                "    aaa:aaa];");
6927   verifyFormat("bool a = ([aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaa ||\n"
6928                "          [aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaaaaa);");
6929 }
6930 
TEST_F(FormatTest,ObjCAt)6931 TEST_F(FormatTest, ObjCAt) {
6932   verifyFormat("@autoreleasepool");
6933   verifyFormat("@catch");
6934   verifyFormat("@class");
6935   verifyFormat("@compatibility_alias");
6936   verifyFormat("@defs");
6937   verifyFormat("@dynamic");
6938   verifyFormat("@encode");
6939   verifyFormat("@end");
6940   verifyFormat("@finally");
6941   verifyFormat("@implementation");
6942   verifyFormat("@import");
6943   verifyFormat("@interface");
6944   verifyFormat("@optional");
6945   verifyFormat("@package");
6946   verifyFormat("@private");
6947   verifyFormat("@property");
6948   verifyFormat("@protected");
6949   verifyFormat("@protocol");
6950   verifyFormat("@public");
6951   verifyFormat("@required");
6952   verifyFormat("@selector");
6953   verifyFormat("@synchronized");
6954   verifyFormat("@synthesize");
6955   verifyFormat("@throw");
6956   verifyFormat("@try");
6957 
6958   EXPECT_EQ("@interface", format("@ interface"));
6959 
6960   // The precise formatting of this doesn't matter, nobody writes code like
6961   // this.
6962   verifyFormat("@ /*foo*/ interface");
6963 }
6964 
TEST_F(FormatTest,ObjCSnippets)6965 TEST_F(FormatTest, ObjCSnippets) {
6966   verifyFormat("@autoreleasepool {\n"
6967                "  foo();\n"
6968                "}");
6969   verifyFormat("@class Foo, Bar;");
6970   verifyFormat("@compatibility_alias AliasName ExistingClass;");
6971   verifyFormat("@dynamic textColor;");
6972   verifyFormat("char *buf1 = @encode(int *);");
6973   verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
6974   verifyFormat("char *buf1 = @encode(int **);");
6975   verifyFormat("Protocol *proto = @protocol(p1);");
6976   verifyFormat("SEL s = @selector(foo:);");
6977   verifyFormat("@synchronized(self) {\n"
6978                "  f();\n"
6979                "}");
6980 
6981   verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
6982   verifyGoogleFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
6983 
6984   verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
6985   verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
6986   verifyGoogleFormat("@property(assign, getter=isEditable) BOOL editable;");
6987   verifyFormat("@property (assign, getter=isEditable) BOOL editable;",
6988                getMozillaStyle());
6989   verifyFormat("@property BOOL editable;", getMozillaStyle());
6990   verifyFormat("@property (assign, getter=isEditable) BOOL editable;",
6991                getWebKitStyle());
6992   verifyFormat("@property BOOL editable;", getWebKitStyle());
6993 
6994   verifyFormat("@import foo.bar;\n"
6995                "@import baz;");
6996 }
6997 
TEST_F(FormatTest,ObjCLiterals)6998 TEST_F(FormatTest, ObjCLiterals) {
6999   verifyFormat("@\"String\"");
7000   verifyFormat("@1");
7001   verifyFormat("@+4.8");
7002   verifyFormat("@-4");
7003   verifyFormat("@1LL");
7004   verifyFormat("@.5");
7005   verifyFormat("@'c'");
7006   verifyFormat("@true");
7007 
7008   verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
7009   verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
7010   verifyFormat("NSNumber *favoriteColor = @(Green);");
7011   verifyFormat("NSString *path = @(getenv(\"PATH\"));");
7012 
7013   verifyFormat("[dictionary setObject:@(1) forKey:@\"number\"];");
7014 }
7015 
TEST_F(FormatTest,ObjCDictLiterals)7016 TEST_F(FormatTest, ObjCDictLiterals) {
7017   verifyFormat("@{");
7018   verifyFormat("@{}");
7019   verifyFormat("@{@\"one\" : @1}");
7020   verifyFormat("return @{@\"one\" : @1;");
7021   verifyFormat("@{@\"one\" : @1}");
7022 
7023   verifyFormat("@{@\"one\" : @{@2 : @1}}");
7024   verifyFormat("@{\n"
7025                "  @\"one\" : @{@2 : @1},\n"
7026                "}");
7027 
7028   verifyFormat("@{1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2}");
7029   verifyFormat("[self setDict:@{}");
7030   verifyFormat("[self setDict:@{@1 : @2}");
7031   verifyFormat("NSLog(@\"%@\", @{@1 : @2, @2 : @3}[@1]);");
7032   verifyFormat(
7033       "NSDictionary *masses = @{@\"H\" : @1.0078, @\"He\" : @4.0026};");
7034   verifyFormat(
7035       "NSDictionary *settings = @{AVEncoderKey : @(AVAudioQualityMax)};");
7036 
7037   verifyFormat(
7038       "NSDictionary *d = @{\n"
7039       "  @\"nam\" : NSUserNam(),\n"
7040       "  @\"dte\" : [NSDate date],\n"
7041       "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
7042       "};");
7043   verifyFormat(
7044       "@{\n"
7045       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
7046       "regularFont,\n"
7047       "};");
7048   verifyGoogleFormat(
7049       "@{\n"
7050       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
7051       "regularFont,\n"
7052       "};");
7053   verifyFormat(
7054       "@{\n"
7055       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :\n"
7056       "      reeeeeeeeeeeeeeeeeeeeeeeegularFont,\n"
7057       "};");
7058 
7059   // We should try to be robust in case someone forgets the "@".
7060   verifyFormat(
7061       "NSDictionary *d = {\n"
7062       "  @\"nam\" : NSUserNam(),\n"
7063       "  @\"dte\" : [NSDate date],\n"
7064       "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
7065       "};");
7066   verifyFormat("NSMutableDictionary *dictionary =\n"
7067                "    [NSMutableDictionary dictionaryWithDictionary:@{\n"
7068                "      aaaaaaaaaaaaaaaaaaaaa : aaaaaaaaaaaaa,\n"
7069                "      bbbbbbbbbbbbbbbbbb : bbbbb,\n"
7070                "      cccccccccccccccc : ccccccccccccccc\n"
7071                "    }];");
7072 }
7073 
TEST_F(FormatTest,ObjCArrayLiterals)7074 TEST_F(FormatTest, ObjCArrayLiterals) {
7075   verifyFormat("@[");
7076   verifyFormat("@[]");
7077   verifyFormat(
7078       "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
7079   verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
7080   verifyFormat("NSArray *array = @[ [foo description] ];");
7081 
7082   verifyFormat(
7083       "NSArray *some_variable = @[\n"
7084       "  aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
7085       "  @\"aaaaaaaaaaaaaaaaa\",\n"
7086       "  @\"aaaaaaaaaaaaaaaaa\",\n"
7087       "  @\"aaaaaaaaaaaaaaaaa\"\n"
7088       "];");
7089   verifyFormat("NSArray *some_variable = @[\n"
7090                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7091                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7092                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7093                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7094                "];");
7095   verifyGoogleFormat("NSArray *some_variable = @[\n"
7096                      "  @\"aaaaaaaaaaaaaaaaa\",\n"
7097                      "  @\"aaaaaaaaaaaaaaaaa\",\n"
7098                      "  @\"aaaaaaaaaaaaaaaaa\",\n"
7099                      "  @\"aaaaaaaaaaaaaaaaa\"\n"
7100                      "];");
7101 
7102   // We should try to be robust in case someone forgets the "@".
7103   verifyFormat("NSArray *some_variable = [\n"
7104                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7105                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7106                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7107                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7108                "];");
7109   verifyFormat(
7110       "- (NSAttributedString *)attributedStringForSegment:(NSUInteger)segment\n"
7111       "                                             index:(NSUInteger)index\n"
7112       "                                nonDigitAttributes:\n"
7113       "                                    (NSDictionary *)noDigitAttributes;");
7114   verifyFormat(
7115       "[someFunction someLooooooooooooongParameter:\n"
7116       "                  @[ NSBundle.mainBundle.infoDictionary[@\"a\"] ]];");
7117 }
7118 
TEST_F(FormatTest,ReformatRegionAdjustsIndent)7119 TEST_F(FormatTest, ReformatRegionAdjustsIndent) {
7120   EXPECT_EQ("{\n"
7121             "{\n"
7122             "a;\n"
7123             "b;\n"
7124             "}\n"
7125             "}",
7126             format("{\n"
7127                    "{\n"
7128                    "a;\n"
7129                    "     b;\n"
7130                    "}\n"
7131                    "}",
7132                    13, 2, getLLVMStyle()));
7133   EXPECT_EQ("{\n"
7134             "{\n"
7135             "  a;\n"
7136             "b;\n"
7137             "}\n"
7138             "}",
7139             format("{\n"
7140                    "{\n"
7141                    "     a;\n"
7142                    "b;\n"
7143                    "}\n"
7144                    "}",
7145                    9, 2, getLLVMStyle()));
7146   EXPECT_EQ("{\n"
7147             "{\n"
7148             "public:\n"
7149             "  b;\n"
7150             "}\n"
7151             "}",
7152             format("{\n"
7153                    "{\n"
7154                    "public:\n"
7155                    "     b;\n"
7156                    "}\n"
7157                    "}",
7158                    17, 2, getLLVMStyle()));
7159   EXPECT_EQ("{\n"
7160             "{\n"
7161             "a;\n"
7162             "}\n"
7163             "{\n"
7164             "  b; //\n"
7165             "}\n"
7166             "}",
7167             format("{\n"
7168                    "{\n"
7169                    "a;\n"
7170                    "}\n"
7171                    "{\n"
7172                    "           b; //\n"
7173                    "}\n"
7174                    "}",
7175                    22, 2, getLLVMStyle()));
7176   EXPECT_EQ("  {\n"
7177             "    a; //\n"
7178             "  }",
7179             format("  {\n"
7180                    "a; //\n"
7181                    "  }",
7182                    4, 2, getLLVMStyle()));
7183   EXPECT_EQ("void f() {}\n"
7184             "void g() {}",
7185             format("void f() {}\n"
7186                    "void g() {}",
7187                    13, 0, getLLVMStyle()));
7188   EXPECT_EQ("int a; // comment\n"
7189             "       // line 2\n"
7190             "int b;",
7191             format("int a; // comment\n"
7192                    "       // line 2\n"
7193                    "  int b;",
7194                    35, 0, getLLVMStyle()));
7195   EXPECT_EQ("  int a;\n"
7196             "  void\n"
7197             "  ffffff() {\n"
7198             "  }",
7199             format("  int a;\n"
7200                    "void ffffff() {}",
7201                    11, 0, getLLVMStyleWithColumns(11)));
7202 
7203   EXPECT_EQ(" void f() {\n"
7204             "#define A 1\n"
7205             " }",
7206             format(" void f() {\n"
7207                    "     #define A 1\n" // Format this line.
7208                    " }",
7209                    20, 0, getLLVMStyle()));
7210   EXPECT_EQ(" void f() {\n"
7211             "    int i;\n"
7212             "#define A \\\n"
7213             "    int i;  \\\n"
7214             "   int j;\n"
7215             "    int k;\n"
7216             " }",
7217             format(" void f() {\n"
7218                    "    int i;\n"
7219                    "#define A \\\n"
7220                    "    int i;  \\\n"
7221                    "   int j;\n"
7222                    "      int k;\n" // Format this line.
7223                    " }",
7224                    67, 0, getLLVMStyle()));
7225 }
7226 
TEST_F(FormatTest,BreaksStringLiterals)7227 TEST_F(FormatTest, BreaksStringLiterals) {
7228   EXPECT_EQ("\"some text \"\n"
7229             "\"other\";",
7230             format("\"some text other\";", getLLVMStyleWithColumns(12)));
7231   EXPECT_EQ("\"some text \"\n"
7232             "\"other\";",
7233             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
7234   EXPECT_EQ(
7235       "#define A  \\\n"
7236       "  \"some \"  \\\n"
7237       "  \"text \"  \\\n"
7238       "  \"other\";",
7239       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
7240   EXPECT_EQ(
7241       "#define A  \\\n"
7242       "  \"so \"    \\\n"
7243       "  \"text \"  \\\n"
7244       "  \"other\";",
7245       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
7246 
7247   EXPECT_EQ("\"some text\"",
7248             format("\"some text\"", getLLVMStyleWithColumns(1)));
7249   EXPECT_EQ("\"some text\"",
7250             format("\"some text\"", getLLVMStyleWithColumns(11)));
7251   EXPECT_EQ("\"some \"\n"
7252             "\"text\"",
7253             format("\"some text\"", getLLVMStyleWithColumns(10)));
7254   EXPECT_EQ("\"some \"\n"
7255             "\"text\"",
7256             format("\"some text\"", getLLVMStyleWithColumns(7)));
7257   EXPECT_EQ("\"some\"\n"
7258             "\" tex\"\n"
7259             "\"t\"",
7260             format("\"some text\"", getLLVMStyleWithColumns(6)));
7261   EXPECT_EQ("\"some\"\n"
7262             "\" tex\"\n"
7263             "\" and\"",
7264             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
7265   EXPECT_EQ("\"some\"\n"
7266             "\"/tex\"\n"
7267             "\"/and\"",
7268             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
7269 
7270   EXPECT_EQ("variable =\n"
7271             "    \"long string \"\n"
7272             "    \"literal\";",
7273             format("variable = \"long string literal\";",
7274                    getLLVMStyleWithColumns(20)));
7275 
7276   EXPECT_EQ("variable = f(\n"
7277             "    \"long string \"\n"
7278             "    \"literal\",\n"
7279             "    short,\n"
7280             "    loooooooooooooooooooong);",
7281             format("variable = f(\"long string literal\", short, "
7282                    "loooooooooooooooooooong);",
7283                    getLLVMStyleWithColumns(20)));
7284 
7285   EXPECT_EQ("f(g(\"long string \"\n"
7286             "    \"literal\"),\n"
7287             "  b);",
7288             format("f(g(\"long string literal\"), b);",
7289                    getLLVMStyleWithColumns(20)));
7290   EXPECT_EQ("f(g(\"long string \"\n"
7291             "    \"literal\",\n"
7292             "    a),\n"
7293             "  b);",
7294             format("f(g(\"long string literal\", a), b);",
7295                    getLLVMStyleWithColumns(20)));
7296   EXPECT_EQ(
7297       "f(\"one two\".split(\n"
7298       "    variable));",
7299       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
7300   EXPECT_EQ("f(\"one two three four five six \"\n"
7301             "  \"seven\".split(\n"
7302             "      really_looooong_variable));",
7303             format("f(\"one two three four five six seven\"."
7304                    "split(really_looooong_variable));",
7305                    getLLVMStyleWithColumns(33)));
7306 
7307   EXPECT_EQ("f(\"some \"\n"
7308             "  \"text\",\n"
7309             "  other);",
7310             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
7311 
7312   // Only break as a last resort.
7313   verifyFormat(
7314       "aaaaaaaaaaaaaaaaaaaa(\n"
7315       "    aaaaaaaaaaaaaaaaaaaa,\n"
7316       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
7317 
7318   EXPECT_EQ(
7319       "\"splitmea\"\n"
7320       "\"trandomp\"\n"
7321       "\"oint\"",
7322       format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
7323 
7324   EXPECT_EQ(
7325       "\"split/\"\n"
7326       "\"pathat/\"\n"
7327       "\"slashes\"",
7328       format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
7329 
7330   EXPECT_EQ(
7331       "\"split/\"\n"
7332       "\"pathat/\"\n"
7333       "\"slashes\"",
7334       format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
7335   EXPECT_EQ("\"split at \"\n"
7336             "\"spaces/at/\"\n"
7337             "\"slashes.at.any$\"\n"
7338             "\"non-alphanumeric%\"\n"
7339             "\"1111111111characte\"\n"
7340             "\"rs\"",
7341             format("\"split at "
7342                    "spaces/at/"
7343                    "slashes.at."
7344                    "any$non-"
7345                    "alphanumeric%"
7346                    "1111111111characte"
7347                    "rs\"",
7348                    getLLVMStyleWithColumns(20)));
7349 
7350   // Verify that splitting the strings understands
7351   // Style::AlwaysBreakBeforeMultilineStrings.
7352   EXPECT_EQ("aaaaaaaaaaaa(aaaaaaaaaaaaa,\n"
7353             "             \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
7354             "             \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
7355             format("aaaaaaaaaaaa(aaaaaaaaaaaaa, \"aaaaaaaaaaaaaaaaaaaaaa "
7356                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa "
7357                    "aaaaaaaaaaaaaaaaaaaaaa\");",
7358                    getGoogleStyle()));
7359   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
7360             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
7361             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
7362                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
7363                    "aaaaaaaaaaaaaaaaaaaaaa\";",
7364                    getGoogleStyle()));
7365   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
7366             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
7367             format("llvm::outs() << "
7368                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
7369                    "aaaaaaaaaaaaaaaaaaa\";"));
7370   EXPECT_EQ("ffff(\n"
7371             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
7372             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
7373             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
7374                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
7375                    getGoogleStyle()));
7376 
7377   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
7378   AlignLeft.AlignEscapedNewlinesLeft = true;
7379   EXPECT_EQ(
7380       "#define A \\\n"
7381       "  \"some \" \\\n"
7382       "  \"text \" \\\n"
7383       "  \"other\";",
7384       format("#define A \"some text other\";", AlignLeft));
7385 }
7386 
TEST_F(FormatTest,BreaksStringLiteralsWithTabs)7387 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
7388   EXPECT_EQ(
7389       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
7390       "(\n"
7391       "    \"x\t\");",
7392       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
7393              "aaaaaaa("
7394              "\"x\t\");"));
7395 }
7396 
TEST_F(FormatTest,BreaksWideAndNSStringLiterals)7397 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
7398   EXPECT_EQ(
7399       "u8\"utf8 string \"\n"
7400       "u8\"literal\";",
7401       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
7402   EXPECT_EQ(
7403       "u\"utf16 string \"\n"
7404       "u\"literal\";",
7405       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
7406   EXPECT_EQ(
7407       "U\"utf32 string \"\n"
7408       "U\"literal\";",
7409       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
7410   EXPECT_EQ("L\"wide string \"\n"
7411             "L\"literal\";",
7412             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
7413   EXPECT_EQ("@\"NSString \"\n"
7414             "@\"literal\";",
7415             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
7416 }
7417 
TEST_F(FormatTest,DoesNotBreakRawStringLiterals)7418 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
7419   FormatStyle Style = getGoogleStyleWithColumns(15);
7420   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
7421   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
7422   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
7423   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
7424   EXPECT_EQ("u8R\"x(raw literal)x\";",
7425             format("u8R\"x(raw literal)x\";", Style));
7426 }
7427 
TEST_F(FormatTest,BreaksStringLiteralsWithin_TMacro)7428 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
7429   FormatStyle Style = getLLVMStyleWithColumns(20);
7430   EXPECT_EQ(
7431       "_T(\"aaaaaaaaaaaaaa\")\n"
7432       "_T(\"aaaaaaaaaaaaaa\")\n"
7433       "_T(\"aaaaaaaaaaaa\")",
7434       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
7435   EXPECT_EQ("f(x, _T(\"aaaaaaaaa\")\n"
7436             "     _T(\"aaaaaa\"),\n"
7437             "  z);",
7438             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
7439 
7440   // FIXME: Handle embedded spaces in one iteration.
7441   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
7442   //            "_T(\"aaaaaaaaaaaaa\")\n"
7443   //            "_T(\"aaaaaaaaaaaaa\")\n"
7444   //            "_T(\"a\")",
7445   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
7446   //                   getLLVMStyleWithColumns(20)));
7447   EXPECT_EQ(
7448       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
7449       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
7450 }
7451 
TEST_F(FormatTest,DontSplitStringLiteralsWithEscapedNewlines)7452 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
7453   EXPECT_EQ(
7454       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
7455       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
7456       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
7457       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
7458              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
7459              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
7460 }
7461 
TEST_F(FormatTest,CountsCharactersInMultilineRawStringLiterals)7462 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
7463   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
7464             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
7465   EXPECT_EQ("fffffffffff(g(R\"x(\n"
7466             "multiline raw string literal xxxxxxxxxxxxxx\n"
7467             ")x\",\n"
7468             "              a),\n"
7469             "            b);",
7470             format("fffffffffff(g(R\"x(\n"
7471                    "multiline raw string literal xxxxxxxxxxxxxx\n"
7472                    ")x\", a), b);",
7473                    getGoogleStyleWithColumns(20)));
7474   EXPECT_EQ("fffffffffff(\n"
7475             "    g(R\"x(qqq\n"
7476             "multiline raw string literal xxxxxxxxxxxxxx\n"
7477             ")x\",\n"
7478             "      a),\n"
7479             "    b);",
7480             format("fffffffffff(g(R\"x(qqq\n"
7481                    "multiline raw string literal xxxxxxxxxxxxxx\n"
7482                    ")x\", a), b);",
7483                    getGoogleStyleWithColumns(20)));
7484 
7485   EXPECT_EQ("fffffffffff(R\"x(\n"
7486             "multiline raw string literal xxxxxxxxxxxxxx\n"
7487             ")x\");",
7488             format("fffffffffff(R\"x(\n"
7489                    "multiline raw string literal xxxxxxxxxxxxxx\n"
7490                    ")x\");",
7491                    getGoogleStyleWithColumns(20)));
7492   EXPECT_EQ("fffffffffff(R\"x(\n"
7493             "multiline raw string literal xxxxxxxxxxxxxx\n"
7494             ")x\" + bbbbbb);",
7495             format("fffffffffff(R\"x(\n"
7496                    "multiline raw string literal xxxxxxxxxxxxxx\n"
7497                    ")x\" +   bbbbbb);",
7498                    getGoogleStyleWithColumns(20)));
7499   EXPECT_EQ("fffffffffff(\n"
7500             "    R\"x(\n"
7501             "multiline raw string literal xxxxxxxxxxxxxx\n"
7502             ")x\" +\n"
7503             "    bbbbbb);",
7504             format("fffffffffff(\n"
7505                    " R\"x(\n"
7506                    "multiline raw string literal xxxxxxxxxxxxxx\n"
7507                    ")x\" + bbbbbb);",
7508                    getGoogleStyleWithColumns(20)));
7509 }
7510 
TEST_F(FormatTest,SkipsUnknownStringLiterals)7511 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
7512   verifyFormat("string a = \"unterminated;");
7513   EXPECT_EQ("function(\"unterminated,\n"
7514             "         OtherParameter);",
7515             format("function(  \"unterminated,\n"
7516                    "    OtherParameter);"));
7517 }
7518 
TEST_F(FormatTest,DoesNotTryToParseUDLiteralsInPreCpp11Code)7519 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
7520   FormatStyle Style = getLLVMStyle();
7521   Style.Standard = FormatStyle::LS_Cpp03;
7522   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
7523             format("#define x(_a) printf(\"foo\"_a);", Style));
7524 }
7525 
TEST_F(FormatTest,UnderstandsCpp1y)7526 TEST_F(FormatTest, UnderstandsCpp1y) {
7527   verifyFormat("int bi{1'000'000};");
7528 }
7529 
TEST_F(FormatTest,BreakStringLiteralsBeforeUnbreakableTokenSequence)7530 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
7531   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
7532             "             \"ddeeefff\");",
7533             format("someFunction(\"aaabbbcccdddeeefff\");",
7534                    getLLVMStyleWithColumns(25)));
7535   EXPECT_EQ("someFunction1234567890(\n"
7536             "    \"aaabbbcccdddeeefff\");",
7537             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
7538                    getLLVMStyleWithColumns(26)));
7539   EXPECT_EQ("someFunction1234567890(\n"
7540             "    \"aaabbbcccdddeeeff\"\n"
7541             "    \"f\");",
7542             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
7543                    getLLVMStyleWithColumns(25)));
7544   EXPECT_EQ("someFunction1234567890(\n"
7545             "    \"aaabbbcccdddeeeff\"\n"
7546             "    \"f\");",
7547             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
7548                    getLLVMStyleWithColumns(24)));
7549   EXPECT_EQ("someFunction(\"aaabbbcc \"\n"
7550             "             \"ddde \"\n"
7551             "             \"efff\");",
7552             format("someFunction(\"aaabbbcc ddde efff\");",
7553                    getLLVMStyleWithColumns(25)));
7554   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
7555             "             \"ddeeefff\");",
7556             format("someFunction(\"aaabbbccc ddeeefff\");",
7557                    getLLVMStyleWithColumns(25)));
7558   EXPECT_EQ("someFunction1234567890(\n"
7559             "    \"aaabb \"\n"
7560             "    \"cccdddeeefff\");",
7561             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
7562                    getLLVMStyleWithColumns(25)));
7563   EXPECT_EQ("#define A          \\\n"
7564             "  string s =       \\\n"
7565             "      \"123456789\"  \\\n"
7566             "      \"0\";         \\\n"
7567             "  int i;",
7568             format("#define A string s = \"1234567890\"; int i;",
7569                    getLLVMStyleWithColumns(20)));
7570   // FIXME: Put additional penalties on breaking at non-whitespace locations.
7571   EXPECT_EQ("someFunction(\"aaabbbcc \"\n"
7572             "             \"dddeeeff\"\n"
7573             "             \"f\");",
7574             format("someFunction(\"aaabbbcc dddeeefff\");",
7575                    getLLVMStyleWithColumns(25)));
7576 }
7577 
TEST_F(FormatTest,DoNotBreakStringLiteralsInEscapeSequence)7578 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
7579   EXPECT_EQ("\"\\a\"",
7580             format("\"\\a\"", getLLVMStyleWithColumns(3)));
7581   EXPECT_EQ("\"\\\"",
7582             format("\"\\\"", getLLVMStyleWithColumns(2)));
7583   EXPECT_EQ("\"test\"\n"
7584             "\"\\n\"",
7585             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
7586   EXPECT_EQ("\"tes\\\\\"\n"
7587             "\"n\"",
7588             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
7589   EXPECT_EQ("\"\\\\\\\\\"\n"
7590             "\"\\n\"",
7591             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
7592   EXPECT_EQ("\"\\uff01\"",
7593             format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
7594   EXPECT_EQ("\"\\uff01\"\n"
7595             "\"test\"",
7596             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
7597   EXPECT_EQ("\"\\Uff01ff02\"",
7598             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
7599   EXPECT_EQ("\"\\x000000000001\"\n"
7600             "\"next\"",
7601             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
7602   EXPECT_EQ("\"\\x000000000001next\"",
7603             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
7604   EXPECT_EQ("\"\\x000000000001\"",
7605             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
7606   EXPECT_EQ("\"test\"\n"
7607             "\"\\000000\"\n"
7608             "\"000001\"",
7609             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
7610   EXPECT_EQ("\"test\\000\"\n"
7611             "\"00000000\"\n"
7612             "\"1\"",
7613             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
7614 }
7615 
TEST_F(FormatTest,DoNotCreateUnreasonableUnwrappedLines)7616 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
7617   verifyFormat("void f() {\n"
7618                "  return g() {}\n"
7619                "  void h() {}");
7620   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
7621                "g();\n"
7622                "}");
7623 }
7624 
TEST_F(FormatTest,DoNotPrematurelyEndUnwrappedLineForReturnStatements)7625 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
7626   verifyFormat(
7627       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
7628 }
7629 
TEST_F(FormatTest,FormatsClosingBracesInEmptyNestedBlocks)7630 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
7631   verifyFormat("class X {\n"
7632                "  void f() {\n"
7633                "  }\n"
7634                "};",
7635                getLLVMStyleWithColumns(12));
7636 }
7637 
TEST_F(FormatTest,ConfigurableIndentWidth)7638 TEST_F(FormatTest, ConfigurableIndentWidth) {
7639   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
7640   EightIndent.IndentWidth = 8;
7641   EightIndent.ContinuationIndentWidth = 8;
7642   verifyFormat("void f() {\n"
7643                "        someFunction();\n"
7644                "        if (true) {\n"
7645                "                f();\n"
7646                "        }\n"
7647                "}",
7648                EightIndent);
7649   verifyFormat("class X {\n"
7650                "        void f() {\n"
7651                "        }\n"
7652                "};",
7653                EightIndent);
7654   verifyFormat("int x[] = {\n"
7655                "        call(),\n"
7656                "        call()};",
7657                EightIndent);
7658 }
7659 
TEST_F(FormatTest,ConfigurableFunctionDeclarationIndentAfterType)7660 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
7661   verifyFormat("double\n"
7662                "f();",
7663                getLLVMStyleWithColumns(8));
7664 }
7665 
TEST_F(FormatTest,ConfigurableUseOfTab)7666 TEST_F(FormatTest, ConfigurableUseOfTab) {
7667   FormatStyle Tab = getLLVMStyleWithColumns(42);
7668   Tab.IndentWidth = 8;
7669   Tab.UseTab = FormatStyle::UT_Always;
7670   Tab.AlignEscapedNewlinesLeft = true;
7671 
7672   EXPECT_EQ("if (aaaaaaaa && // q\n"
7673             "    bb)\t\t// w\n"
7674             "\t;",
7675             format("if (aaaaaaaa &&// q\n"
7676                    "bb)// w\n"
7677                    ";",
7678                    Tab));
7679   EXPECT_EQ("if (aaa && bbb) // w\n"
7680             "\t;",
7681             format("if(aaa&&bbb)// w\n"
7682                    ";",
7683                    Tab));
7684 
7685   verifyFormat("class X {\n"
7686                "\tvoid f() {\n"
7687                "\t\tsomeFunction(parameter1,\n"
7688                "\t\t\t     parameter2);\n"
7689                "\t}\n"
7690                "};",
7691                Tab);
7692   verifyFormat("#define A                        \\\n"
7693                "\tvoid f() {               \\\n"
7694                "\t\tsomeFunction(    \\\n"
7695                "\t\t    parameter1,  \\\n"
7696                "\t\t    parameter2); \\\n"
7697                "\t}",
7698                Tab);
7699   EXPECT_EQ("void f() {\n"
7700             "\tf();\n"
7701             "\tg();\n"
7702             "}",
7703             format("void f() {\n"
7704                    "\tf();\n"
7705                    "\tg();\n"
7706                    "}",
7707                    0, 0, Tab));
7708   EXPECT_EQ("void f() {\n"
7709             "\tf();\n"
7710             "\tg();\n"
7711             "}",
7712             format("void f() {\n"
7713                    "\tf();\n"
7714                    "\tg();\n"
7715                    "}",
7716                    16, 0, Tab));
7717   EXPECT_EQ("void f() {\n"
7718             "  \tf();\n"
7719             "\tg();\n"
7720             "}",
7721             format("void f() {\n"
7722                    "  \tf();\n"
7723                    "  \tg();\n"
7724                    "}",
7725                    21, 0, Tab));
7726 
7727   Tab.TabWidth = 4;
7728   Tab.IndentWidth = 8;
7729   verifyFormat("class TabWidth4Indent8 {\n"
7730                "\t\tvoid f() {\n"
7731                "\t\t\t\tsomeFunction(parameter1,\n"
7732                "\t\t\t\t\t\t\t parameter2);\n"
7733                "\t\t}\n"
7734                "};",
7735                Tab);
7736 
7737   Tab.TabWidth = 4;
7738   Tab.IndentWidth = 4;
7739   verifyFormat("class TabWidth4Indent4 {\n"
7740                "\tvoid f() {\n"
7741                "\t\tsomeFunction(parameter1,\n"
7742                "\t\t\t\t\t parameter2);\n"
7743                "\t}\n"
7744                "};",
7745                Tab);
7746 
7747   Tab.TabWidth = 8;
7748   Tab.IndentWidth = 4;
7749   verifyFormat("class TabWidth8Indent4 {\n"
7750                "    void f() {\n"
7751                "\tsomeFunction(parameter1,\n"
7752                "\t\t     parameter2);\n"
7753                "    }\n"
7754                "};",
7755                Tab);
7756 
7757   Tab.TabWidth = 8;
7758   Tab.IndentWidth = 8;
7759   EXPECT_EQ("/*\n"
7760             "\t      a\t\tcomment\n"
7761             "\t      in multiple lines\n"
7762             "       */",
7763             format("   /*\t \t \n"
7764                    " \t \t a\t\tcomment\t \t\n"
7765                    " \t \t in multiple lines\t\n"
7766                    " \t  */",
7767                    Tab));
7768 
7769   Tab.UseTab = FormatStyle::UT_ForIndentation;
7770   verifyFormat("{\n"
7771                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
7772                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
7773                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
7774                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
7775                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
7776                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
7777                "};",
7778                Tab);
7779   verifyFormat("enum A {\n"
7780                "\ta1, // Force multiple lines\n"
7781                "\ta2,\n"
7782                "\ta3\n"
7783                "};",
7784                Tab);
7785   EXPECT_EQ("if (aaaaaaaa && // q\n"
7786             "    bb)         // w\n"
7787             "\t;",
7788             format("if (aaaaaaaa &&// q\n"
7789                    "bb)// w\n"
7790                    ";",
7791                    Tab));
7792   verifyFormat("class X {\n"
7793                "\tvoid f() {\n"
7794                "\t\tsomeFunction(parameter1,\n"
7795                "\t\t             parameter2);\n"
7796                "\t}\n"
7797                "};",
7798                Tab);
7799   verifyFormat("{\n"
7800                "\tQ({\n"
7801                "\t\tint a;\n"
7802                "\t\tsomeFunction(aaaaaaaa,\n"
7803                "\t\t             bbbbbbb);\n"
7804                "\t}, p);\n"
7805                "}",
7806                Tab);
7807   EXPECT_EQ("{\n"
7808             "\t/* aaaa\n"
7809             "\t   bbbb */\n"
7810             "}",
7811             format("{\n"
7812                    "/* aaaa\n"
7813                    "   bbbb */\n"
7814                    "}",
7815                    Tab));
7816   EXPECT_EQ("{\n"
7817             "\t/*\n"
7818             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7819             "\t  bbbbbbbbbbbbb\n"
7820             "\t*/\n"
7821             "}",
7822             format("{\n"
7823                    "/*\n"
7824                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
7825                    "*/\n"
7826                    "}",
7827                    Tab));
7828   EXPECT_EQ("{\n"
7829             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7830             "\t// bbbbbbbbbbbbb\n"
7831             "}",
7832             format("{\n"
7833                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
7834                    "}",
7835                    Tab));
7836   EXPECT_EQ("{\n"
7837             "\t/*\n"
7838             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7839             "\t  bbbbbbbbbbbbb\n"
7840             "\t*/\n"
7841             "}",
7842             format("{\n"
7843                    "\t/*\n"
7844                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
7845                    "\t*/\n"
7846                    "}",
7847                    Tab));
7848   EXPECT_EQ("{\n"
7849             "\t/*\n"
7850             "\n"
7851             "\t*/\n"
7852             "}",
7853             format("{\n"
7854                    "\t/*\n"
7855                    "\n"
7856                    "\t*/\n"
7857                    "}",
7858                    Tab));
7859   EXPECT_EQ("{\n"
7860             "\t/*\n"
7861             " asdf\n"
7862             "\t*/\n"
7863             "}",
7864             format("{\n"
7865                    "\t/*\n"
7866                    " asdf\n"
7867                    "\t*/\n"
7868                    "}",
7869                    Tab));
7870 
7871   Tab.UseTab = FormatStyle::UT_Never;
7872   EXPECT_EQ("/*\n"
7873             "              a\t\tcomment\n"
7874             "              in multiple lines\n"
7875             "       */",
7876             format("   /*\t \t \n"
7877                    " \t \t a\t\tcomment\t \t\n"
7878                    " \t \t in multiple lines\t\n"
7879                    " \t  */",
7880                    Tab));
7881   EXPECT_EQ("/* some\n"
7882             "   comment */",
7883            format(" \t \t /* some\n"
7884                   " \t \t    comment */",
7885                   Tab));
7886   EXPECT_EQ("int a; /* some\n"
7887             "   comment */",
7888            format(" \t \t int a; /* some\n"
7889                   " \t \t    comment */",
7890                   Tab));
7891 
7892   EXPECT_EQ("int a; /* some\n"
7893             "comment */",
7894            format(" \t \t int\ta; /* some\n"
7895                   " \t \t    comment */",
7896                   Tab));
7897   EXPECT_EQ("f(\"\t\t\"); /* some\n"
7898             "    comment */",
7899            format(" \t \t f(\"\t\t\"); /* some\n"
7900                   " \t \t    comment */",
7901                   Tab));
7902   EXPECT_EQ("{\n"
7903             "  /*\n"
7904             "   * Comment\n"
7905             "   */\n"
7906             "  int i;\n"
7907             "}",
7908             format("{\n"
7909                    "\t/*\n"
7910                    "\t * Comment\n"
7911                    "\t */\n"
7912                    "\t int i;\n"
7913                    "}"));
7914 }
7915 
TEST_F(FormatTest,CalculatesOriginalColumn)7916 TEST_F(FormatTest, CalculatesOriginalColumn) {
7917   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
7918             "q\"; /* some\n"
7919             "       comment */",
7920             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
7921                    "q\"; /* some\n"
7922                    "       comment */",
7923                    getLLVMStyle()));
7924   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
7925             "/* some\n"
7926             "   comment */",
7927             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
7928                    " /* some\n"
7929                    "    comment */",
7930                    getLLVMStyle()));
7931   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
7932             "qqq\n"
7933             "/* some\n"
7934             "   comment */",
7935             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
7936                    "qqq\n"
7937                    " /* some\n"
7938                    "    comment */",
7939                    getLLVMStyle()));
7940   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
7941             "wwww; /* some\n"
7942             "         comment */",
7943             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
7944                    "wwww; /* some\n"
7945                    "         comment */",
7946                    getLLVMStyle()));
7947 }
7948 
TEST_F(FormatTest,ConfigurableSpaceBeforeParens)7949 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
7950   FormatStyle NoSpace = getLLVMStyle();
7951   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
7952 
7953   verifyFormat("while(true)\n"
7954                "  continue;", NoSpace);
7955   verifyFormat("for(;;)\n"
7956                "  continue;", NoSpace);
7957   verifyFormat("if(true)\n"
7958                "  f();\n"
7959                "else if(true)\n"
7960                "  f();", NoSpace);
7961   verifyFormat("do {\n"
7962                "  do_something();\n"
7963                "} while(something());", NoSpace);
7964   verifyFormat("switch(x) {\n"
7965                "default:\n"
7966                "  break;\n"
7967                "}", NoSpace);
7968   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
7969   verifyFormat("size_t x = sizeof(x);", NoSpace);
7970   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
7971   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
7972   verifyFormat("alignas(128) char a[128];", NoSpace);
7973   verifyFormat("size_t x = alignof(MyType);", NoSpace);
7974   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
7975   verifyFormat("int f() throw(Deprecated);", NoSpace);
7976 
7977   FormatStyle Space = getLLVMStyle();
7978   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
7979 
7980   verifyFormat("int f ();", Space);
7981   verifyFormat("void f (int a, T b) {\n"
7982                "  while (true)\n"
7983                "    continue;\n"
7984                "}",
7985                Space);
7986   verifyFormat("if (true)\n"
7987                "  f ();\n"
7988                "else if (true)\n"
7989                "  f ();",
7990                Space);
7991   verifyFormat("do {\n"
7992                "  do_something ();\n"
7993                "} while (something ());",
7994                Space);
7995   verifyFormat("switch (x) {\n"
7996                "default:\n"
7997                "  break;\n"
7998                "}",
7999                Space);
8000   verifyFormat("A::A () : a (1) {}", Space);
8001   verifyFormat("void f () __attribute__ ((asdf));", Space);
8002   verifyFormat("*(&a + 1);\n"
8003                "&((&a)[1]);\n"
8004                "a[(b + c) * d];\n"
8005                "(((a + 1) * 2) + 3) * 4;",
8006                Space);
8007   verifyFormat("#define A(x) x", Space);
8008   verifyFormat("#define A (x) x", Space);
8009   verifyFormat("#if defined(x)\n"
8010                "#endif",
8011                Space);
8012   verifyFormat("auto i = std::make_unique<int> (5);", Space);
8013   verifyFormat("size_t x = sizeof (x);", Space);
8014   verifyFormat("auto f (int x) -> decltype (x);", Space);
8015   verifyFormat("int f (T x) noexcept (x.create ());", Space);
8016   verifyFormat("alignas (128) char a[128];", Space);
8017   verifyFormat("size_t x = alignof (MyType);", Space);
8018   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
8019   verifyFormat("int f () throw (Deprecated);", Space);
8020 }
8021 
TEST_F(FormatTest,ConfigurableSpacesInParentheses)8022 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
8023   FormatStyle Spaces = getLLVMStyle();
8024 
8025   Spaces.SpacesInParentheses = true;
8026   verifyFormat("call( x, y, z );", Spaces);
8027   verifyFormat("while ( (bool)1 )\n"
8028                "  continue;", Spaces);
8029   verifyFormat("for ( ;; )\n"
8030                "  continue;", Spaces);
8031   verifyFormat("if ( true )\n"
8032                "  f();\n"
8033                "else if ( true )\n"
8034                "  f();", Spaces);
8035   verifyFormat("do {\n"
8036                "  do_something( (int)i );\n"
8037                "} while ( something() );", Spaces);
8038   verifyFormat("switch ( x ) {\n"
8039                "default:\n"
8040                "  break;\n"
8041                "}", Spaces);
8042 
8043   Spaces.SpacesInParentheses = false;
8044   Spaces.SpacesInCStyleCastParentheses = true;
8045   verifyFormat("Type *A = ( Type * )P;", Spaces);
8046   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
8047   verifyFormat("x = ( int32 )y;", Spaces);
8048   verifyFormat("int a = ( int )(2.0f);", Spaces);
8049   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
8050   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
8051   verifyFormat("#define x (( int )-1)", Spaces);
8052 
8053   Spaces.SpacesInParentheses = false;
8054   Spaces.SpaceInEmptyParentheses = true;
8055   verifyFormat("call(x, y, z);", Spaces);
8056   verifyFormat("call( )", Spaces);
8057 
8058   // Run the first set of tests again with
8059   // Spaces.SpacesInParentheses = false,
8060   // Spaces.SpaceInEmptyParentheses = true and
8061   // Spaces.SpacesInCStyleCastParentheses = true
8062   Spaces.SpacesInParentheses = false,
8063   Spaces.SpaceInEmptyParentheses = true;
8064   Spaces.SpacesInCStyleCastParentheses = true;
8065   verifyFormat("call(x, y, z);", Spaces);
8066   verifyFormat("while (( bool )1)\n"
8067                "  continue;", Spaces);
8068   verifyFormat("for (;;)\n"
8069                "  continue;", Spaces);
8070   verifyFormat("if (true)\n"
8071                "  f( );\n"
8072                "else if (true)\n"
8073                "  f( );", Spaces);
8074   verifyFormat("do {\n"
8075                "  do_something(( int )i);\n"
8076                "} while (something( ));", Spaces);
8077   verifyFormat("switch (x) {\n"
8078                "default:\n"
8079                "  break;\n"
8080                "}", Spaces);
8081 
8082   Spaces.SpaceAfterCStyleCast = true;
8083   verifyFormat("call(x, y, z);", Spaces);
8084   verifyFormat("while (( bool ) 1)\n"
8085                "  continue;",
8086                Spaces);
8087   verifyFormat("for (;;)\n"
8088                "  continue;",
8089                Spaces);
8090   verifyFormat("if (true)\n"
8091                "  f( );\n"
8092                "else if (true)\n"
8093                "  f( );",
8094                Spaces);
8095   verifyFormat("do {\n"
8096                "  do_something(( int ) i);\n"
8097                "} while (something( ));",
8098                Spaces);
8099   verifyFormat("switch (x) {\n"
8100                "default:\n"
8101                "  break;\n"
8102                "}",
8103                Spaces);
8104   Spaces.SpacesInCStyleCastParentheses = false;
8105   Spaces.SpaceAfterCStyleCast = true;
8106   verifyFormat("while ((bool) 1)\n"
8107                "  continue;",
8108                Spaces);
8109   verifyFormat("do {\n"
8110                "  do_something((int) i);\n"
8111                "} while (something( ));",
8112                Spaces);
8113 }
8114 
TEST_F(FormatTest,ConfigurableSpacesInSquareBrackets)8115 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
8116   verifyFormat("int a[5];");
8117   verifyFormat("a[3] += 42;");
8118 
8119   FormatStyle Spaces = getLLVMStyle();
8120   Spaces.SpacesInSquareBrackets = true;
8121   // Lambdas unchanged.
8122   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
8123   verifyFormat("return [i, args...] {};", Spaces);
8124 
8125   // Not lambdas.
8126   verifyFormat("int a[ 5 ];", Spaces);
8127   verifyFormat("a[ 3 ] += 42;", Spaces);
8128   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
8129   verifyFormat("double &operator[](int i) { return 0; }\n"
8130                "int i;",
8131                Spaces);
8132   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
8133   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
8134   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
8135 }
8136 
TEST_F(FormatTest,ConfigurableSpaceBeforeAssignmentOperators)8137 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
8138   verifyFormat("int a = 5;");
8139   verifyFormat("a += 42;");
8140   verifyFormat("a or_eq 8;");
8141 
8142   FormatStyle Spaces = getLLVMStyle();
8143   Spaces.SpaceBeforeAssignmentOperators = false;
8144   verifyFormat("int a= 5;", Spaces);
8145   verifyFormat("a+= 42;", Spaces);
8146   verifyFormat("a or_eq 8;", Spaces);
8147 }
8148 
TEST_F(FormatTest,LinuxBraceBreaking)8149 TEST_F(FormatTest, LinuxBraceBreaking) {
8150   FormatStyle LinuxBraceStyle = getLLVMStyle();
8151   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
8152   verifyFormat("namespace a\n"
8153                "{\n"
8154                "class A\n"
8155                "{\n"
8156                "  void f()\n"
8157                "  {\n"
8158                "    if (true) {\n"
8159                "      a();\n"
8160                "      b();\n"
8161                "    }\n"
8162                "  }\n"
8163                "  void g() { return; }\n"
8164                "};\n"
8165                "struct B {\n"
8166                "  int x;\n"
8167                "};\n"
8168                "}\n",
8169                LinuxBraceStyle);
8170   verifyFormat("enum X {\n"
8171                "  Y = 0,\n"
8172                "}\n",
8173                LinuxBraceStyle);
8174   verifyFormat("struct S {\n"
8175                "  int Type;\n"
8176                "  union {\n"
8177                "    int x;\n"
8178                "    double y;\n"
8179                "  } Value;\n"
8180                "  class C\n"
8181                "  {\n"
8182                "    MyFavoriteType Value;\n"
8183                "  } Class;\n"
8184                "}\n",
8185                LinuxBraceStyle);
8186 }
8187 
TEST_F(FormatTest,StroustrupBraceBreaking)8188 TEST_F(FormatTest, StroustrupBraceBreaking) {
8189   FormatStyle StroustrupBraceStyle = getLLVMStyle();
8190   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8191   verifyFormat("namespace a {\n"
8192                "class A {\n"
8193                "  void f()\n"
8194                "  {\n"
8195                "    if (true) {\n"
8196                "      a();\n"
8197                "      b();\n"
8198                "    }\n"
8199                "  }\n"
8200                "  void g() { return; }\n"
8201                "};\n"
8202                "struct B {\n"
8203                "  int x;\n"
8204                "};\n"
8205                "}\n",
8206                StroustrupBraceStyle);
8207 
8208   verifyFormat("void foo()\n"
8209                "{\n"
8210                "  if (a) {\n"
8211                "    a();\n"
8212                "  }\n"
8213                "  else {\n"
8214                "    b();\n"
8215                "  }\n"
8216                "}\n",
8217                StroustrupBraceStyle);
8218 
8219   verifyFormat("#ifdef _DEBUG\n"
8220                "int foo(int i = 0)\n"
8221                "#else\n"
8222                "int foo(int i = 5)\n"
8223                "#endif\n"
8224                "{\n"
8225                "  return i;\n"
8226                "}",
8227                StroustrupBraceStyle);
8228 
8229   verifyFormat("void foo() {}\n"
8230                "void bar()\n"
8231                "#ifdef _DEBUG\n"
8232                "{\n"
8233                "  foo();\n"
8234                "}\n"
8235                "#else\n"
8236                "{\n"
8237                "}\n"
8238                "#endif",
8239                StroustrupBraceStyle);
8240 
8241   verifyFormat("void foobar() { int i = 5; }\n"
8242                "#ifdef _DEBUG\n"
8243                "void bar() {}\n"
8244                "#else\n"
8245                "void bar() { foobar(); }\n"
8246                "#endif",
8247                StroustrupBraceStyle);
8248 }
8249 
TEST_F(FormatTest,AllmanBraceBreaking)8250 TEST_F(FormatTest, AllmanBraceBreaking) {
8251   FormatStyle AllmanBraceStyle = getLLVMStyle();
8252   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
8253   verifyFormat("namespace a\n"
8254                "{\n"
8255                "class A\n"
8256                "{\n"
8257                "  void f()\n"
8258                "  {\n"
8259                "    if (true)\n"
8260                "    {\n"
8261                "      a();\n"
8262                "      b();\n"
8263                "    }\n"
8264                "  }\n"
8265                "  void g() { return; }\n"
8266                "};\n"
8267                "struct B\n"
8268                "{\n"
8269                "  int x;\n"
8270                "};\n"
8271                "}",
8272                AllmanBraceStyle);
8273 
8274   verifyFormat("void f()\n"
8275                "{\n"
8276                "  if (true)\n"
8277                "  {\n"
8278                "    a();\n"
8279                "  }\n"
8280                "  else if (false)\n"
8281                "  {\n"
8282                "    b();\n"
8283                "  }\n"
8284                "  else\n"
8285                "  {\n"
8286                "    c();\n"
8287                "  }\n"
8288                "}\n",
8289                AllmanBraceStyle);
8290 
8291   verifyFormat("void f()\n"
8292                "{\n"
8293                "  for (int i = 0; i < 10; ++i)\n"
8294                "  {\n"
8295                "    a();\n"
8296                "  }\n"
8297                "  while (false)\n"
8298                "  {\n"
8299                "    b();\n"
8300                "  }\n"
8301                "  do\n"
8302                "  {\n"
8303                "    c();\n"
8304                "  } while (false)\n"
8305                "}\n",
8306                AllmanBraceStyle);
8307 
8308   verifyFormat("void f(int a)\n"
8309                "{\n"
8310                "  switch (a)\n"
8311                "  {\n"
8312                "  case 0:\n"
8313                "    break;\n"
8314                "  case 1:\n"
8315                "  {\n"
8316                "    break;\n"
8317                "  }\n"
8318                "  case 2:\n"
8319                "  {\n"
8320                "  }\n"
8321                "  break;\n"
8322                "  default:\n"
8323                "    break;\n"
8324                "  }\n"
8325                "}\n",
8326                AllmanBraceStyle);
8327 
8328   verifyFormat("enum X\n"
8329                "{\n"
8330                "  Y = 0,\n"
8331                "}\n",
8332                AllmanBraceStyle);
8333   verifyFormat("enum X\n"
8334                "{\n"
8335                "  Y = 0\n"
8336                "}\n",
8337                AllmanBraceStyle);
8338 
8339   verifyFormat("@interface BSApplicationController ()\n"
8340                "{\n"
8341                "@private\n"
8342                "  id _extraIvar;\n"
8343                "}\n"
8344                "@end\n",
8345                AllmanBraceStyle);
8346 
8347   verifyFormat("#ifdef _DEBUG\n"
8348                "int foo(int i = 0)\n"
8349                "#else\n"
8350                "int foo(int i = 5)\n"
8351                "#endif\n"
8352                "{\n"
8353                "  return i;\n"
8354                "}",
8355                AllmanBraceStyle);
8356 
8357   verifyFormat("void foo() {}\n"
8358                "void bar()\n"
8359                "#ifdef _DEBUG\n"
8360                "{\n"
8361                "  foo();\n"
8362                "}\n"
8363                "#else\n"
8364                "{\n"
8365                "}\n"
8366                "#endif",
8367                AllmanBraceStyle);
8368 
8369   verifyFormat("void foobar() { int i = 5; }\n"
8370                "#ifdef _DEBUG\n"
8371                "void bar() {}\n"
8372                "#else\n"
8373                "void bar() { foobar(); }\n"
8374                "#endif",
8375                AllmanBraceStyle);
8376 
8377   // This shouldn't affect ObjC blocks..
8378   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
8379                "  // ...\n"
8380                "  int i;\n"
8381                "}];",
8382                AllmanBraceStyle);
8383   verifyFormat("void (^block)(void) = ^{\n"
8384                "  // ...\n"
8385                "  int i;\n"
8386                "};",
8387                AllmanBraceStyle);
8388   // .. or dict literals.
8389   verifyFormat("void f()\n"
8390                "{\n"
8391                "  [object someMethod:@{ @\"a\" : @\"b\" }];\n"
8392                "}",
8393                AllmanBraceStyle);
8394   verifyFormat("int f()\n"
8395                "{ // comment\n"
8396                "  return 42;\n"
8397                "}",
8398                AllmanBraceStyle);
8399 
8400   AllmanBraceStyle.ColumnLimit = 19;
8401   verifyFormat("void f() { int i; }", AllmanBraceStyle);
8402   AllmanBraceStyle.ColumnLimit = 18;
8403   verifyFormat("void f()\n"
8404                "{\n"
8405                "  int i;\n"
8406                "}",
8407                AllmanBraceStyle);
8408   AllmanBraceStyle.ColumnLimit = 80;
8409 
8410   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
8411   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = true;
8412   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
8413   verifyFormat("void f(bool b)\n"
8414                "{\n"
8415                "  if (b)\n"
8416                "  {\n"
8417                "    return;\n"
8418                "  }\n"
8419                "}\n",
8420                BreakBeforeBraceShortIfs);
8421   verifyFormat("void f(bool b)\n"
8422                "{\n"
8423                "  if (b) return;\n"
8424                "}\n",
8425                BreakBeforeBraceShortIfs);
8426   verifyFormat("void f(bool b)\n"
8427                "{\n"
8428                "  while (b)\n"
8429                "  {\n"
8430                "    return;\n"
8431                "  }\n"
8432                "}\n",
8433                BreakBeforeBraceShortIfs);
8434 }
8435 
TEST_F(FormatTest,GNUBraceBreaking)8436 TEST_F(FormatTest, GNUBraceBreaking) {
8437   FormatStyle GNUBraceStyle = getLLVMStyle();
8438   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
8439   verifyFormat("namespace a\n"
8440                "{\n"
8441                "class A\n"
8442                "{\n"
8443                "  void f()\n"
8444                "  {\n"
8445                "    int a;\n"
8446                "    {\n"
8447                "      int b;\n"
8448                "    }\n"
8449                "    if (true)\n"
8450                "      {\n"
8451                "        a();\n"
8452                "        b();\n"
8453                "      }\n"
8454                "  }\n"
8455                "  void g() { return; }\n"
8456                "}\n"
8457                "}",
8458                GNUBraceStyle);
8459 
8460   verifyFormat("void f()\n"
8461                "{\n"
8462                "  if (true)\n"
8463                "    {\n"
8464                "      a();\n"
8465                "    }\n"
8466                "  else if (false)\n"
8467                "    {\n"
8468                "      b();\n"
8469                "    }\n"
8470                "  else\n"
8471                "    {\n"
8472                "      c();\n"
8473                "    }\n"
8474                "}\n",
8475                GNUBraceStyle);
8476 
8477   verifyFormat("void f()\n"
8478                "{\n"
8479                "  for (int i = 0; i < 10; ++i)\n"
8480                "    {\n"
8481                "      a();\n"
8482                "    }\n"
8483                "  while (false)\n"
8484                "    {\n"
8485                "      b();\n"
8486                "    }\n"
8487                "  do\n"
8488                "    {\n"
8489                "      c();\n"
8490                "    }\n"
8491                "  while (false);\n"
8492                "}\n",
8493                GNUBraceStyle);
8494 
8495   verifyFormat("void f(int a)\n"
8496                "{\n"
8497                "  switch (a)\n"
8498                "    {\n"
8499                "    case 0:\n"
8500                "      break;\n"
8501                "    case 1:\n"
8502                "      {\n"
8503                "        break;\n"
8504                "      }\n"
8505                "    case 2:\n"
8506                "      {\n"
8507                "      }\n"
8508                "      break;\n"
8509                "    default:\n"
8510                "      break;\n"
8511                "    }\n"
8512                "}\n",
8513                GNUBraceStyle);
8514 
8515   verifyFormat("enum X\n"
8516                "{\n"
8517                "  Y = 0,\n"
8518                "}\n",
8519                GNUBraceStyle);
8520 
8521   verifyFormat("@interface BSApplicationController ()\n"
8522                "{\n"
8523                "@private\n"
8524                "  id _extraIvar;\n"
8525                "}\n"
8526                "@end\n",
8527                GNUBraceStyle);
8528 
8529   verifyFormat("#ifdef _DEBUG\n"
8530                "int foo(int i = 0)\n"
8531                "#else\n"
8532                "int foo(int i = 5)\n"
8533                "#endif\n"
8534                "{\n"
8535                "  return i;\n"
8536                "}",
8537                GNUBraceStyle);
8538 
8539   verifyFormat("void foo() {}\n"
8540                "void bar()\n"
8541                "#ifdef _DEBUG\n"
8542                "{\n"
8543                "  foo();\n"
8544                "}\n"
8545                "#else\n"
8546                "{\n"
8547                "}\n"
8548                "#endif",
8549                GNUBraceStyle);
8550 
8551   verifyFormat("void foobar() { int i = 5; }\n"
8552                "#ifdef _DEBUG\n"
8553                "void bar() {}\n"
8554                "#else\n"
8555                "void bar() { foobar(); }\n"
8556                "#endif",
8557                GNUBraceStyle);
8558 }
TEST_F(FormatTest,CatchExceptionReferenceBinding)8559 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
8560   verifyFormat("void f() {\n"
8561                "  try {\n"
8562                "  } catch (const Exception &e) {\n"
8563                "  }\n"
8564                "}\n",
8565                getLLVMStyle());
8566 }
8567 
TEST_F(FormatTest,UnderstandsPragmas)8568 TEST_F(FormatTest, UnderstandsPragmas) {
8569   verifyFormat("#pragma omp reduction(| : var)");
8570   verifyFormat("#pragma omp reduction(+ : var)");
8571 
8572   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
8573             "(including parentheses).",
8574             format("#pragma    mark   Any non-hyphenated or hyphenated string "
8575                    "(including parentheses)."));
8576 }
8577 
8578 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
8579   for (size_t i = 1; i < Styles.size(); ++i)                                   \
8580     EXPECT_EQ(Styles[0], Styles[i]) << "Style #" << i << " of "                \
8581                                     << Styles.size()                           \
8582                                     << " differs from Style #0"
8583 
TEST_F(FormatTest,GetsPredefinedStyleByName)8584 TEST_F(FormatTest, GetsPredefinedStyleByName) {
8585   SmallVector<FormatStyle, 3> Styles;
8586   Styles.resize(3);
8587 
8588   Styles[0] = getLLVMStyle();
8589   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
8590   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
8591   EXPECT_ALL_STYLES_EQUAL(Styles);
8592 
8593   Styles[0] = getGoogleStyle();
8594   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
8595   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
8596   EXPECT_ALL_STYLES_EQUAL(Styles);
8597 
8598   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
8599   EXPECT_TRUE(
8600       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
8601   EXPECT_TRUE(
8602       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
8603   EXPECT_ALL_STYLES_EQUAL(Styles);
8604 
8605   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
8606   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
8607   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
8608   EXPECT_ALL_STYLES_EQUAL(Styles);
8609 
8610   Styles[0] = getMozillaStyle();
8611   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
8612   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
8613   EXPECT_ALL_STYLES_EQUAL(Styles);
8614 
8615   Styles[0] = getWebKitStyle();
8616   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
8617   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
8618   EXPECT_ALL_STYLES_EQUAL(Styles);
8619 
8620   Styles[0] = getGNUStyle();
8621   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
8622   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
8623   EXPECT_ALL_STYLES_EQUAL(Styles);
8624 
8625   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
8626 }
8627 
TEST_F(FormatTest,GetsCorrectBasedOnStyle)8628 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
8629   SmallVector<FormatStyle, 8> Styles;
8630   Styles.resize(2);
8631 
8632   Styles[0] = getGoogleStyle();
8633   Styles[1] = getLLVMStyle();
8634   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
8635   EXPECT_ALL_STYLES_EQUAL(Styles);
8636 
8637   Styles.resize(5);
8638   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
8639   Styles[1] = getLLVMStyle();
8640   Styles[1].Language = FormatStyle::LK_JavaScript;
8641   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
8642 
8643   Styles[2] = getLLVMStyle();
8644   Styles[2].Language = FormatStyle::LK_JavaScript;
8645   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
8646                                   "BasedOnStyle: Google",
8647                                   &Styles[2]).value());
8648 
8649   Styles[3] = getLLVMStyle();
8650   Styles[3].Language = FormatStyle::LK_JavaScript;
8651   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
8652                                   "Language: JavaScript",
8653                                   &Styles[3]).value());
8654 
8655   Styles[4] = getLLVMStyle();
8656   Styles[4].Language = FormatStyle::LK_JavaScript;
8657   EXPECT_EQ(0, parseConfiguration("---\n"
8658                                   "BasedOnStyle: LLVM\n"
8659                                   "IndentWidth: 123\n"
8660                                   "---\n"
8661                                   "BasedOnStyle: Google\n"
8662                                   "Language: JavaScript",
8663                                   &Styles[4]).value());
8664   EXPECT_ALL_STYLES_EQUAL(Styles);
8665 }
8666 
8667 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
8668   Style.FIELD = false;                                                         \
8669   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
8670   EXPECT_TRUE(Style.FIELD);                                                    \
8671   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
8672   EXPECT_FALSE(Style.FIELD);
8673 
8674 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
8675 
8676 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
8677   EXPECT_NE(VALUE, Style.FIELD);                                               \
8678   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
8679   EXPECT_EQ(VALUE, Style.FIELD)
8680 
TEST_F(FormatTest,ParsesConfigurationBools)8681 TEST_F(FormatTest, ParsesConfigurationBools) {
8682   FormatStyle Style = {};
8683   Style.Language = FormatStyle::LK_Cpp;
8684   CHECK_PARSE_BOOL(AlignAfterOpenBracket);
8685   CHECK_PARSE_BOOL(AlignEscapedNewlinesLeft);
8686   CHECK_PARSE_BOOL(AlignOperands);
8687   CHECK_PARSE_BOOL(AlignTrailingComments);
8688   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
8689   CHECK_PARSE_BOOL(AllowShortBlocksOnASingleLine);
8690   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
8691   CHECK_PARSE_BOOL(AllowShortIfStatementsOnASingleLine);
8692   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
8693   CHECK_PARSE_BOOL(AlwaysBreakAfterDefinitionReturnType);
8694   CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
8695   CHECK_PARSE_BOOL(BinPackParameters);
8696   CHECK_PARSE_BOOL(BinPackArguments);
8697   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
8698   CHECK_PARSE_BOOL(BreakConstructorInitializersBeforeComma);
8699   CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
8700   CHECK_PARSE_BOOL(DerivePointerAlignment);
8701   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
8702   CHECK_PARSE_BOOL(IndentCaseLabels);
8703   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
8704   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
8705   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
8706   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
8707   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
8708   CHECK_PARSE_BOOL(SpacesInParentheses);
8709   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
8710   CHECK_PARSE_BOOL(SpacesInAngles);
8711   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
8712   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
8713   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
8714   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
8715   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
8716 }
8717 
8718 #undef CHECK_PARSE_BOOL
8719 
TEST_F(FormatTest,ParsesConfiguration)8720 TEST_F(FormatTest, ParsesConfiguration) {
8721   FormatStyle Style = {};
8722   Style.Language = FormatStyle::LK_Cpp;
8723   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
8724   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
8725               ConstructorInitializerIndentWidth, 1234u);
8726   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
8727   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
8728   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
8729   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
8730               PenaltyBreakBeforeFirstCallParameter, 1234u);
8731   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
8732   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
8733               PenaltyReturnTypeOnItsOwnLine, 1234u);
8734   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
8735               SpacesBeforeTrailingComments, 1234u);
8736   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
8737   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
8738 
8739   Style.PointerAlignment = FormatStyle::PAS_Middle;
8740   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
8741               FormatStyle::PAS_Left);
8742   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
8743               FormatStyle::PAS_Right);
8744   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
8745               FormatStyle::PAS_Middle);
8746   // For backward compatibility:
8747   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
8748               FormatStyle::PAS_Left);
8749   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
8750               FormatStyle::PAS_Right);
8751   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
8752               FormatStyle::PAS_Middle);
8753 
8754   Style.Standard = FormatStyle::LS_Auto;
8755   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
8756   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Cpp11);
8757   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
8758   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
8759   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
8760 
8761   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
8762   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
8763               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
8764   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
8765               FormatStyle::BOS_None);
8766   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
8767               FormatStyle::BOS_All);
8768   // For backward compatibility:
8769   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
8770               FormatStyle::BOS_None);
8771   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
8772               FormatStyle::BOS_All);
8773 
8774   Style.UseTab = FormatStyle::UT_ForIndentation;
8775   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
8776   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
8777   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
8778   // For backward compatibility:
8779   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
8780   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
8781 
8782   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
8783   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
8784               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
8785   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
8786               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
8787   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
8788               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
8789   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
8790               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
8791   // For backward compatibility:
8792   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
8793               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
8794   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
8795               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
8796 
8797   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
8798   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
8799               FormatStyle::SBPO_Never);
8800   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
8801               FormatStyle::SBPO_Always);
8802   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
8803               FormatStyle::SBPO_ControlStatements);
8804   // For backward compatibility:
8805   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
8806               FormatStyle::SBPO_Never);
8807   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
8808               FormatStyle::SBPO_ControlStatements);
8809 
8810   Style.ColumnLimit = 123;
8811   FormatStyle BaseStyle = getLLVMStyle();
8812   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
8813   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
8814 
8815   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8816   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
8817               FormatStyle::BS_Attach);
8818   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
8819               FormatStyle::BS_Linux);
8820   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
8821               FormatStyle::BS_Stroustrup);
8822   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
8823               FormatStyle::BS_Allman);
8824   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
8825 
8826   Style.NamespaceIndentation = FormatStyle::NI_All;
8827   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
8828               FormatStyle::NI_None);
8829   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
8830               FormatStyle::NI_Inner);
8831   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
8832               FormatStyle::NI_All);
8833 
8834   Style.ForEachMacros.clear();
8835   std::vector<std::string> BoostForeach;
8836   BoostForeach.push_back("BOOST_FOREACH");
8837   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
8838   std::vector<std::string> BoostAndQForeach;
8839   BoostAndQForeach.push_back("BOOST_FOREACH");
8840   BoostAndQForeach.push_back("Q_FOREACH");
8841   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
8842               BoostAndQForeach);
8843 }
8844 
TEST_F(FormatTest,ParsesConfigurationWithLanguages)8845 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
8846   FormatStyle Style = {};
8847   Style.Language = FormatStyle::LK_Cpp;
8848   CHECK_PARSE("Language: Cpp\n"
8849               "IndentWidth: 12",
8850               IndentWidth, 12u);
8851   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
8852                                "IndentWidth: 34",
8853                                &Style),
8854             ParseError::Unsuitable);
8855   EXPECT_EQ(12u, Style.IndentWidth);
8856   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
8857   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
8858 
8859   Style.Language = FormatStyle::LK_JavaScript;
8860   CHECK_PARSE("Language: JavaScript\n"
8861               "IndentWidth: 12",
8862               IndentWidth, 12u);
8863   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
8864   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
8865                                "IndentWidth: 34",
8866                                &Style),
8867             ParseError::Unsuitable);
8868   EXPECT_EQ(23u, Style.IndentWidth);
8869   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
8870   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
8871 
8872   CHECK_PARSE("BasedOnStyle: LLVM\n"
8873               "IndentWidth: 67",
8874               IndentWidth, 67u);
8875 
8876   CHECK_PARSE("---\n"
8877               "Language: JavaScript\n"
8878               "IndentWidth: 12\n"
8879               "---\n"
8880               "Language: Cpp\n"
8881               "IndentWidth: 34\n"
8882               "...\n",
8883               IndentWidth, 12u);
8884 
8885   Style.Language = FormatStyle::LK_Cpp;
8886   CHECK_PARSE("---\n"
8887               "Language: JavaScript\n"
8888               "IndentWidth: 12\n"
8889               "---\n"
8890               "Language: Cpp\n"
8891               "IndentWidth: 34\n"
8892               "...\n",
8893               IndentWidth, 34u);
8894   CHECK_PARSE("---\n"
8895               "IndentWidth: 78\n"
8896               "---\n"
8897               "Language: JavaScript\n"
8898               "IndentWidth: 56\n"
8899               "...\n",
8900               IndentWidth, 78u);
8901 
8902   Style.ColumnLimit = 123;
8903   Style.IndentWidth = 234;
8904   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
8905   Style.TabWidth = 345;
8906   EXPECT_FALSE(parseConfiguration("---\n"
8907                                   "IndentWidth: 456\n"
8908                                   "BreakBeforeBraces: Allman\n"
8909                                   "---\n"
8910                                   "Language: JavaScript\n"
8911                                   "IndentWidth: 111\n"
8912                                   "TabWidth: 111\n"
8913                                   "---\n"
8914                                   "Language: Cpp\n"
8915                                   "BreakBeforeBraces: Stroustrup\n"
8916                                   "TabWidth: 789\n"
8917                                   "...\n",
8918                                   &Style));
8919   EXPECT_EQ(123u, Style.ColumnLimit);
8920   EXPECT_EQ(456u, Style.IndentWidth);
8921   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
8922   EXPECT_EQ(789u, Style.TabWidth);
8923 
8924   EXPECT_EQ(parseConfiguration("---\n"
8925                                "Language: JavaScript\n"
8926                                "IndentWidth: 56\n"
8927                                "---\n"
8928                                "IndentWidth: 78\n"
8929                                "...\n",
8930                                &Style),
8931             ParseError::Error);
8932   EXPECT_EQ(parseConfiguration("---\n"
8933                                "Language: JavaScript\n"
8934                                "IndentWidth: 56\n"
8935                                "---\n"
8936                                "Language: JavaScript\n"
8937                                "IndentWidth: 78\n"
8938                                "...\n",
8939                                &Style),
8940             ParseError::Error);
8941 
8942   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
8943 }
8944 
8945 #undef CHECK_PARSE
8946 
TEST_F(FormatTest,UsesLanguageForBasedOnStyle)8947 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
8948   FormatStyle Style = {};
8949   Style.Language = FormatStyle::LK_JavaScript;
8950   Style.BreakBeforeTernaryOperators = true;
8951   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
8952   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
8953 
8954   Style.BreakBeforeTernaryOperators = true;
8955   EXPECT_EQ(0, parseConfiguration("---\n"
8956               "BasedOnStyle: Google\n"
8957               "---\n"
8958               "Language: JavaScript\n"
8959               "IndentWidth: 76\n"
8960               "...\n", &Style).value());
8961   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
8962   EXPECT_EQ(76u, Style.IndentWidth);
8963   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
8964 }
8965 
TEST_F(FormatTest,ConfigurationRoundTripTest)8966 TEST_F(FormatTest, ConfigurationRoundTripTest) {
8967   FormatStyle Style = getLLVMStyle();
8968   std::string YAML = configurationAsText(Style);
8969   FormatStyle ParsedStyle = {};
8970   ParsedStyle.Language = FormatStyle::LK_Cpp;
8971   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
8972   EXPECT_EQ(Style, ParsedStyle);
8973 }
8974 
TEST_F(FormatTest,WorksFor8bitEncodings)8975 TEST_F(FormatTest, WorksFor8bitEncodings) {
8976   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
8977             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
8978             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
8979             "\"\xef\xee\xf0\xf3...\"",
8980             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
8981                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
8982                    "\xef\xee\xf0\xf3...\"",
8983                    getLLVMStyleWithColumns(12)));
8984 }
8985 
TEST_F(FormatTest,HandlesUTF8BOM)8986 TEST_F(FormatTest, HandlesUTF8BOM) {
8987   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
8988   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
8989             format("\xef\xbb\xbf#include <iostream>"));
8990   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
8991             format("\xef\xbb\xbf\n#include <iostream>"));
8992 }
8993 
8994 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
8995 #if !defined(_MSC_VER)
8996 
TEST_F(FormatTest,CountsUTF8CharactersProperly)8997 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
8998   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
8999                getLLVMStyleWithColumns(35));
9000   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
9001                getLLVMStyleWithColumns(31));
9002   verifyFormat("// Однажды в студёную зимнюю пору...",
9003                getLLVMStyleWithColumns(36));
9004   verifyFormat("// 一 二 三 四 五 六 七 八 九 十",
9005                getLLVMStyleWithColumns(32));
9006   verifyFormat("/* Однажды в студёную зимнюю пору... */",
9007                getLLVMStyleWithColumns(39));
9008   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
9009                getLLVMStyleWithColumns(35));
9010 }
9011 
TEST_F(FormatTest,SplitsUTF8Strings)9012 TEST_F(FormatTest, SplitsUTF8Strings) {
9013   // Non-printable characters' width is currently considered to be the length in
9014   // bytes in UTF8. The characters can be displayed in very different manner
9015   // (zero-width, single width with a substitution glyph, expanded to their code
9016   // (e.g. "<8d>"), so there's no single correct way to handle them.
9017   EXPECT_EQ("\"aaaaÄ\"\n"
9018             "\"\xc2\x8d\";",
9019             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
9020   EXPECT_EQ("\"aaaaaaaÄ\"\n"
9021             "\"\xc2\x8d\";",
9022             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
9023   EXPECT_EQ(
9024       "\"Однажды, в \"\n"
9025       "\"студёную \"\n"
9026       "\"зимнюю \"\n"
9027       "\"пору,\"",
9028       format("\"Однажды, в студёную зимнюю пору,\"",
9029              getLLVMStyleWithColumns(13)));
9030   EXPECT_EQ("\"一 二 三 \"\n"
9031             "\"四 五六 \"\n"
9032             "\"七 八 九 \"\n"
9033             "\"十\"",
9034             format("\"一 二 三 四 五六 七 八 九 十\"",
9035                    getLLVMStyleWithColumns(11)));
9036   EXPECT_EQ("\"一\t二 \"\n"
9037             "\"\t三 \"\n"
9038             "\"四 五\t六 \"\n"
9039             "\"\t七 \"\n"
9040             "\"八九十\tqq\"",
9041             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
9042                    getLLVMStyleWithColumns(11)));
9043 }
9044 
9045 
TEST_F(FormatTest,HandlesDoubleWidthCharsInMultiLineStrings)9046 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
9047   EXPECT_EQ("const char *sssss =\n"
9048             "    \"一二三四五六七八\\\n"
9049             " 九 十\";",
9050             format("const char *sssss = \"一二三四五六七八\\\n"
9051                    " 九 十\";",
9052                    getLLVMStyleWithColumns(30)));
9053 }
9054 
TEST_F(FormatTest,SplitsUTF8LineComments)9055 TEST_F(FormatTest, SplitsUTF8LineComments) {
9056   EXPECT_EQ("// aaaaÄ\xc2\x8d",
9057             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
9058   EXPECT_EQ("// Я из лесу\n"
9059             "// вышел; был\n"
9060             "// сильный\n"
9061             "// мороз.",
9062             format("// Я из лесу вышел; был сильный мороз.",
9063                    getLLVMStyleWithColumns(13)));
9064   EXPECT_EQ("// 一二三\n"
9065             "// 四五六七\n"
9066             "// 八  九\n"
9067             "// 十",
9068             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
9069 }
9070 
TEST_F(FormatTest,SplitsUTF8BlockComments)9071 TEST_F(FormatTest, SplitsUTF8BlockComments) {
9072   EXPECT_EQ("/* Гляжу,\n"
9073             " * поднимается\n"
9074             " * медленно в\n"
9075             " * гору\n"
9076             " * Лошадка,\n"
9077             " * везущая\n"
9078             " * хворосту\n"
9079             " * воз. */",
9080             format("/* Гляжу, поднимается медленно в гору\n"
9081                    " * Лошадка, везущая хворосту воз. */",
9082                    getLLVMStyleWithColumns(13)));
9083   EXPECT_EQ(
9084       "/* 一二三\n"
9085       " * 四五六七\n"
9086       " * 八  九\n"
9087       " * 十  */",
9088       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
9089   EXPECT_EQ("/* �������� ��������\n"
9090             " * ��������\n"
9091             " * ������-�� */",
9092             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
9093 }
9094 
9095 #endif // _MSC_VER
9096 
TEST_F(FormatTest,ConstructorInitializerIndentWidth)9097 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
9098   FormatStyle Style = getLLVMStyle();
9099 
9100   Style.ConstructorInitializerIndentWidth = 4;
9101   verifyFormat(
9102       "SomeClass::Constructor()\n"
9103       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
9104       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
9105       Style);
9106 
9107   Style.ConstructorInitializerIndentWidth = 2;
9108   verifyFormat(
9109       "SomeClass::Constructor()\n"
9110       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
9111       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
9112       Style);
9113 
9114   Style.ConstructorInitializerIndentWidth = 0;
9115   verifyFormat(
9116       "SomeClass::Constructor()\n"
9117       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
9118       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
9119       Style);
9120 }
9121 
TEST_F(FormatTest,BreakConstructorInitializersBeforeComma)9122 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
9123   FormatStyle Style = getLLVMStyle();
9124   Style.BreakConstructorInitializersBeforeComma = true;
9125   Style.ConstructorInitializerIndentWidth = 4;
9126   verifyFormat("SomeClass::Constructor()\n"
9127                "    : a(a)\n"
9128                "    , b(b)\n"
9129                "    , c(c) {}",
9130                Style);
9131   verifyFormat("SomeClass::Constructor()\n"
9132                "    : a(a) {}",
9133                Style);
9134 
9135   Style.ColumnLimit = 0;
9136   verifyFormat("SomeClass::Constructor()\n"
9137                "    : a(a) {}",
9138                Style);
9139   verifyFormat("SomeClass::Constructor()\n"
9140                "    : a(a)\n"
9141                "    , b(b)\n"
9142                "    , c(c) {}",
9143                Style);
9144   verifyFormat("SomeClass::Constructor()\n"
9145                "    : a(a) {\n"
9146                "  foo();\n"
9147                "  bar();\n"
9148                "}",
9149                Style);
9150 
9151   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9152   verifyFormat("SomeClass::Constructor()\n"
9153                "    : a(a)\n"
9154                "    , b(b)\n"
9155                "    , c(c) {\n}",
9156                Style);
9157   verifyFormat("SomeClass::Constructor()\n"
9158                "    : a(a) {\n}",
9159                Style);
9160 
9161   Style.ColumnLimit = 80;
9162   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
9163   Style.ConstructorInitializerIndentWidth = 2;
9164   verifyFormat("SomeClass::Constructor()\n"
9165                "  : a(a)\n"
9166                "  , b(b)\n"
9167                "  , c(c) {}",
9168                Style);
9169 
9170   Style.ConstructorInitializerIndentWidth = 0;
9171   verifyFormat("SomeClass::Constructor()\n"
9172                ": a(a)\n"
9173                ", b(b)\n"
9174                ", c(c) {}",
9175                Style);
9176 
9177   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
9178   Style.ConstructorInitializerIndentWidth = 4;
9179   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
9180   verifyFormat(
9181       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
9182       Style);
9183   verifyFormat(
9184       "SomeClass::Constructor()\n"
9185       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
9186       Style);
9187   Style.ConstructorInitializerIndentWidth = 4;
9188   Style.ColumnLimit = 60;
9189   verifyFormat("SomeClass::Constructor()\n"
9190                "    : aaaaaaaa(aaaaaaaa)\n"
9191                "    , aaaaaaaa(aaaaaaaa)\n"
9192                "    , aaaaaaaa(aaaaaaaa) {}",
9193                Style);
9194 }
9195 
TEST_F(FormatTest,Destructors)9196 TEST_F(FormatTest, Destructors) {
9197   verifyFormat("void F(int &i) { i.~int(); }");
9198   verifyFormat("void F(int &i) { i->~int(); }");
9199 }
9200 
TEST_F(FormatTest,FormatsWithWebKitStyle)9201 TEST_F(FormatTest, FormatsWithWebKitStyle) {
9202   FormatStyle Style = getWebKitStyle();
9203 
9204   // Don't indent in outer namespaces.
9205   verifyFormat("namespace outer {\n"
9206                "int i;\n"
9207                "namespace inner {\n"
9208                "    int i;\n"
9209                "} // namespace inner\n"
9210                "} // namespace outer\n"
9211                "namespace other_outer {\n"
9212                "int i;\n"
9213                "}",
9214                Style);
9215 
9216   // Don't indent case labels.
9217   verifyFormat("switch (variable) {\n"
9218                "case 1:\n"
9219                "case 2:\n"
9220                "    doSomething();\n"
9221                "    break;\n"
9222                "default:\n"
9223                "    ++variable;\n"
9224                "}",
9225                Style);
9226 
9227   // Wrap before binary operators.
9228   EXPECT_EQ(
9229       "void f()\n"
9230       "{\n"
9231       "    if (aaaaaaaaaaaaaaaa\n"
9232       "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
9233       "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
9234       "        return;\n"
9235       "}",
9236       format(
9237           "void f() {\n"
9238           "if (aaaaaaaaaaaaaaaa\n"
9239           "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
9240           "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
9241           "return;\n"
9242           "}",
9243           Style));
9244 
9245   // Allow functions on a single line.
9246   verifyFormat("void f() { return; }", Style);
9247 
9248   // Constructor initializers are formatted one per line with the "," on the
9249   // new line.
9250   verifyFormat("Constructor()\n"
9251                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
9252                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
9253                "          aaaaaaaaaaaaaa)\n"
9254                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
9255                "{\n"
9256                "}",
9257                Style);
9258   verifyFormat("SomeClass::Constructor()\n"
9259                "    : a(a)\n"
9260                "{\n"
9261                "}",
9262                Style);
9263   EXPECT_EQ("SomeClass::Constructor()\n"
9264             "    : a(a)\n"
9265             "{\n"
9266             "}",
9267             format("SomeClass::Constructor():a(a){}", Style));
9268   verifyFormat("SomeClass::Constructor()\n"
9269                "    : a(a)\n"
9270                "    , b(b)\n"
9271                "    , c(c)\n"
9272                "{\n"
9273                "}", Style);
9274   verifyFormat("SomeClass::Constructor()\n"
9275                "    : a(a)\n"
9276                "{\n"
9277                "    foo();\n"
9278                "    bar();\n"
9279                "}",
9280                Style);
9281 
9282   // Access specifiers should be aligned left.
9283   verifyFormat("class C {\n"
9284                "public:\n"
9285                "    int i;\n"
9286                "};",
9287                Style);
9288 
9289   // Do not align comments.
9290   verifyFormat("int a; // Do not\n"
9291                "double b; // align comments.",
9292                Style);
9293 
9294   // Do not align operands.
9295   EXPECT_EQ("ASSERT(aaaa\n"
9296             "    || bbbb);",
9297             format("ASSERT ( aaaa\n||bbbb);", Style));
9298 
9299   // Accept input's line breaks.
9300   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
9301             "    || bbbbbbbbbbbbbbb) {\n"
9302             "    i++;\n"
9303             "}",
9304             format("if (aaaaaaaaaaaaaaa\n"
9305                    "|| bbbbbbbbbbbbbbb) { i++; }",
9306                    Style));
9307   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
9308             "    i++;\n"
9309             "}",
9310             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
9311 
9312   // Don't automatically break all macro definitions (llvm.org/PR17842).
9313   verifyFormat("#define aNumber 10", Style);
9314   // However, generally keep the line breaks that the user authored.
9315   EXPECT_EQ("#define aNumber \\\n"
9316             "    10",
9317             format("#define aNumber \\\n"
9318                    " 10",
9319                    Style));
9320 
9321   // Keep empty and one-element array literals on a single line.
9322   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
9323             "                                  copyItems:YES];",
9324             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
9325                    "copyItems:YES];",
9326                    Style));
9327   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
9328             "                                  copyItems:YES];",
9329             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
9330                    "             copyItems:YES];",
9331                    Style));
9332   // FIXME: This does not seem right, there should be more indentation before
9333   // the array literal's entries. Nested blocks have the same problem.
9334   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
9335             "    @\"a\",\n"
9336             "    @\"a\"\n"
9337             "]\n"
9338             "                                  copyItems:YES];",
9339             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
9340                    "     @\"a\",\n"
9341                    "     @\"a\"\n"
9342                    "     ]\n"
9343                    "       copyItems:YES];",
9344                    Style));
9345   EXPECT_EQ(
9346       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
9347       "                                  copyItems:YES];",
9348       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
9349              "   copyItems:YES];",
9350              Style));
9351 
9352   verifyFormat("[self.a b:c c:d];", Style);
9353   EXPECT_EQ("[self.a b:c\n"
9354             "        c:d];",
9355             format("[self.a b:c\n"
9356                    "c:d];",
9357                    Style));
9358 }
9359 
TEST_F(FormatTest,FormatsLambdas)9360 TEST_F(FormatTest, FormatsLambdas) {
9361   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
9362   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
9363   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
9364   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
9365   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
9366   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
9367   verifyFormat("void f() {\n"
9368                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
9369                "}\n");
9370   verifyFormat("void f() {\n"
9371                "  other(x.begin(), //\n"
9372                "        x.end(),   //\n"
9373                "        [&](int, int) { return 1; });\n"
9374                "}\n");
9375   verifyFormat("SomeFunction([]() { // A cool function...\n"
9376                "  return 43;\n"
9377                "});");
9378   EXPECT_EQ("SomeFunction([]() {\n"
9379             "#define A a\n"
9380             "  return 43;\n"
9381             "});",
9382             format("SomeFunction([](){\n"
9383                    "#define A a\n"
9384                    "return 43;\n"
9385                    "});"));
9386   verifyFormat("void f() {\n"
9387                "  SomeFunction([](decltype(x), A *a) {});\n"
9388                "}");
9389   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9390                "    [](const aaaaaaaaaa &a) { return a; });");
9391   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
9392                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
9393                "});");
9394   verifyFormat("Constructor()\n"
9395                "    : Field([] { // comment\n"
9396                "        int i;\n"
9397                "      }) {}");
9398 
9399   // Lambdas with return types.
9400   verifyFormat("int c = []() -> int { return 2; }();\n");
9401   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
9402   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
9403   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
9404   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
9405   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
9406   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
9407   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
9408                "                   int j) -> int {\n"
9409                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
9410                "};");
9411 
9412   // Multiple lambdas in the same parentheses change indentation rules.
9413   verifyFormat("SomeFunction(\n"
9414                "    []() {\n"
9415                "      int i = 42;\n"
9416                "      return i;\n"
9417                "    },\n"
9418                "    []() {\n"
9419                "      int j = 43;\n"
9420                "      return j;\n"
9421                "    });");
9422 
9423   // More complex introducers.
9424   verifyFormat("return [i, args...] {};");
9425 
9426   // Not lambdas.
9427   verifyFormat("constexpr char hello[]{\"hello\"};");
9428   verifyFormat("double &operator[](int i) { return 0; }\n"
9429                "int i;");
9430   verifyFormat("std::unique_ptr<int[]> foo() {}");
9431   verifyFormat("int i = a[a][a]->f();");
9432   verifyFormat("int i = (*b)[a]->f();");
9433 
9434   // Other corner cases.
9435   verifyFormat("void f() {\n"
9436                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
9437                "      );\n"
9438                "}");
9439 
9440   // Lambdas created through weird macros.
9441   verifyFormat("void f() {\n"
9442                "  MACRO((const AA &a) { return 1; });\n"
9443                "}");
9444 
9445   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
9446                "      doo_dah();\n"
9447                "      doo_dah();\n"
9448                "    })) {\n"
9449                "}");
9450 }
9451 
TEST_F(FormatTest,FormatsBlocks)9452 TEST_F(FormatTest, FormatsBlocks) {
9453   FormatStyle ShortBlocks = getLLVMStyle();
9454   ShortBlocks.AllowShortBlocksOnASingleLine = true;
9455   verifyFormat("int (^Block)(int, int);", ShortBlocks);
9456   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
9457   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
9458   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
9459   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
9460   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
9461 
9462   verifyFormat("foo(^{ bar(); });", ShortBlocks);
9463   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
9464   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
9465 
9466   verifyFormat("[operation setCompletionBlock:^{\n"
9467                "  [self onOperationDone];\n"
9468                "}];");
9469   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
9470                "  [self onOperationDone];\n"
9471                "}]};");
9472   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
9473                "  f();\n"
9474                "}];");
9475   verifyFormat("int a = [operation block:^int(int *i) {\n"
9476                "  return 1;\n"
9477                "}];");
9478   verifyFormat("[myObject doSomethingWith:arg1\n"
9479                "                      aaa:^int(int *a) {\n"
9480                "                        return 1;\n"
9481                "                      }\n"
9482                "                      bbb:f(a * bbbbbbbb)];");
9483 
9484   verifyFormat("[operation setCompletionBlock:^{\n"
9485                "  [self.delegate newDataAvailable];\n"
9486                "}];",
9487                getLLVMStyleWithColumns(60));
9488   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
9489                "  NSString *path = [self sessionFilePath];\n"
9490                "  if (path) {\n"
9491                "    // ...\n"
9492                "  }\n"
9493                "});");
9494   verifyFormat("[[SessionService sharedService]\n"
9495                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
9496                "      if (window) {\n"
9497                "        [self windowDidLoad:window];\n"
9498                "      } else {\n"
9499                "        [self errorLoadingWindow];\n"
9500                "      }\n"
9501                "    }];");
9502   verifyFormat("void (^largeBlock)(void) = ^{\n"
9503                "  // ...\n"
9504                "};\n",
9505                getLLVMStyleWithColumns(40));
9506   verifyFormat("[[SessionService sharedService]\n"
9507                "    loadWindowWithCompletionBlock: //\n"
9508                "        ^(SessionWindow *window) {\n"
9509                "          if (window) {\n"
9510                "            [self windowDidLoad:window];\n"
9511                "          } else {\n"
9512                "            [self errorLoadingWindow];\n"
9513                "          }\n"
9514                "        }];",
9515                getLLVMStyleWithColumns(60));
9516   verifyFormat("[myObject doSomethingWith:arg1\n"
9517                "    firstBlock:^(Foo *a) {\n"
9518                "      // ...\n"
9519                "      int i;\n"
9520                "    }\n"
9521                "    secondBlock:^(Bar *b) {\n"
9522                "      // ...\n"
9523                "      int i;\n"
9524                "    }\n"
9525                "    thirdBlock:^Foo(Bar *b) {\n"
9526                "      // ...\n"
9527                "      int i;\n"
9528                "    }];");
9529   verifyFormat("[myObject doSomethingWith:arg1\n"
9530                "               firstBlock:-1\n"
9531                "              secondBlock:^(Bar *b) {\n"
9532                "                // ...\n"
9533                "                int i;\n"
9534                "              }];");
9535 
9536   verifyFormat("f(^{\n"
9537                "  @autoreleasepool {\n"
9538                "    if (a) {\n"
9539                "      g();\n"
9540                "    }\n"
9541                "  }\n"
9542                "});");
9543   verifyFormat("Block b = ^int *(A *a, B *b) {}");
9544 
9545   FormatStyle FourIndent = getLLVMStyle();
9546   FourIndent.ObjCBlockIndentWidth = 4;
9547   verifyFormat("[operation setCompletionBlock:^{\n"
9548                "    [self onOperationDone];\n"
9549                "}];",
9550                FourIndent);
9551 }
9552 
TEST_F(FormatTest,SupportsCRLF)9553 TEST_F(FormatTest, SupportsCRLF) {
9554   EXPECT_EQ("int a;\r\n"
9555             "int b;\r\n"
9556             "int c;\r\n",
9557             format("int a;\r\n"
9558                    "  int b;\r\n"
9559                    "    int c;\r\n",
9560                    getLLVMStyle()));
9561   EXPECT_EQ("int a;\r\n"
9562             "int b;\r\n"
9563             "int c;\r\n",
9564             format("int a;\r\n"
9565                    "  int b;\n"
9566                    "    int c;\r\n",
9567                    getLLVMStyle()));
9568   EXPECT_EQ("int a;\n"
9569             "int b;\n"
9570             "int c;\n",
9571             format("int a;\r\n"
9572                    "  int b;\n"
9573                    "    int c;\n",
9574                    getLLVMStyle()));
9575   EXPECT_EQ("\"aaaaaaa \"\r\n"
9576             "\"bbbbbbb\";\r\n",
9577             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
9578   EXPECT_EQ("#define A \\\r\n"
9579             "  b;      \\\r\n"
9580             "  c;      \\\r\n"
9581             "  d;\r\n",
9582             format("#define A \\\r\n"
9583                    "  b; \\\r\n"
9584                    "  c; d; \r\n",
9585                    getGoogleStyle()));
9586 
9587   EXPECT_EQ("/*\r\n"
9588             "multi line block comments\r\n"
9589             "should not introduce\r\n"
9590             "an extra carriage return\r\n"
9591             "*/\r\n",
9592             format("/*\r\n"
9593                    "multi line block comments\r\n"
9594                    "should not introduce\r\n"
9595                    "an extra carriage return\r\n"
9596                    "*/\r\n"));
9597 }
9598 
TEST_F(FormatTest,MunchSemicolonAfterBlocks)9599 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
9600   verifyFormat("MY_CLASS(C) {\n"
9601                "  int i;\n"
9602                "  int j;\n"
9603                "};");
9604 }
9605 
TEST_F(FormatTest,ConfigurableContinuationIndentWidth)9606 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
9607   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
9608   TwoIndent.ContinuationIndentWidth = 2;
9609 
9610   EXPECT_EQ("int i =\n"
9611             "  longFunction(\n"
9612             "    arg);",
9613             format("int i = longFunction(arg);", TwoIndent));
9614 
9615   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
9616   SixIndent.ContinuationIndentWidth = 6;
9617 
9618   EXPECT_EQ("int i =\n"
9619             "      longFunction(\n"
9620             "            arg);",
9621             format("int i = longFunction(arg);", SixIndent));
9622 }
9623 
TEST_F(FormatTest,SpacesInAngles)9624 TEST_F(FormatTest, SpacesInAngles) {
9625   FormatStyle Spaces = getLLVMStyle();
9626   Spaces.SpacesInAngles = true;
9627 
9628   verifyFormat("static_cast< int >(arg);", Spaces);
9629   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
9630   verifyFormat("f< int, float >();", Spaces);
9631   verifyFormat("template <> g() {}", Spaces);
9632   verifyFormat("template < std::vector< int > > f() {}", Spaces);
9633 
9634   Spaces.Standard = FormatStyle::LS_Cpp03;
9635   Spaces.SpacesInAngles = true;
9636   verifyFormat("A< A< int > >();", Spaces);
9637 
9638   Spaces.SpacesInAngles = false;
9639   verifyFormat("A<A<int> >();", Spaces);
9640 
9641   Spaces.Standard = FormatStyle::LS_Cpp11;
9642   Spaces.SpacesInAngles = true;
9643   verifyFormat("A< A< int > >();", Spaces);
9644 
9645   Spaces.SpacesInAngles = false;
9646   verifyFormat("A<A<int>>();", Spaces);
9647 }
9648 
TEST_F(FormatTest,HandleUnbalancedImplicitBracesAcrossPPBranches)9649 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
9650   std::string code = "#if A\n"
9651                      "#if B\n"
9652                      "a.\n"
9653                      "#endif\n"
9654                      "    a = 1;\n"
9655                      "#else\n"
9656                      "#endif\n"
9657                      "#if C\n"
9658                      "#else\n"
9659                      "#endif\n";
9660   EXPECT_EQ(code, format(code));
9661 }
9662 
TEST_F(FormatTest,HandleConflictMarkers)9663 TEST_F(FormatTest, HandleConflictMarkers) {
9664   // Git/SVN conflict markers.
9665   EXPECT_EQ("int a;\n"
9666             "void f() {\n"
9667             "  callme(some(parameter1,\n"
9668             "<<<<<<< text by the vcs\n"
9669             "              parameter2),\n"
9670             "||||||| text by the vcs\n"
9671             "              parameter2),\n"
9672             "         parameter3,\n"
9673             "======= text by the vcs\n"
9674             "              parameter2, parameter3),\n"
9675             ">>>>>>> text by the vcs\n"
9676             "         otherparameter);\n",
9677             format("int a;\n"
9678                    "void f() {\n"
9679                    "  callme(some(parameter1,\n"
9680                    "<<<<<<< text by the vcs\n"
9681                    "  parameter2),\n"
9682                    "||||||| text by the vcs\n"
9683                    "  parameter2),\n"
9684                    "  parameter3,\n"
9685                    "======= text by the vcs\n"
9686                    "  parameter2,\n"
9687                    "  parameter3),\n"
9688                    ">>>>>>> text by the vcs\n"
9689                    "  otherparameter);\n"));
9690 
9691   // Perforce markers.
9692   EXPECT_EQ("void f() {\n"
9693             "  function(\n"
9694             ">>>> text by the vcs\n"
9695             "      parameter,\n"
9696             "==== text by the vcs\n"
9697             "      parameter,\n"
9698             "==== text by the vcs\n"
9699             "      parameter,\n"
9700             "<<<< text by the vcs\n"
9701             "      parameter);\n",
9702             format("void f() {\n"
9703                    "  function(\n"
9704                    ">>>> text by the vcs\n"
9705                    "  parameter,\n"
9706                    "==== text by the vcs\n"
9707                    "  parameter,\n"
9708                    "==== text by the vcs\n"
9709                    "  parameter,\n"
9710                    "<<<< text by the vcs\n"
9711                    "  parameter);\n"));
9712 
9713   EXPECT_EQ("<<<<<<<\n"
9714             "|||||||\n"
9715             "=======\n"
9716             ">>>>>>>",
9717             format("<<<<<<<\n"
9718                    "|||||||\n"
9719                    "=======\n"
9720                    ">>>>>>>"));
9721 
9722   EXPECT_EQ("<<<<<<<\n"
9723             "|||||||\n"
9724             "int i;\n"
9725             "=======\n"
9726             ">>>>>>>",
9727             format("<<<<<<<\n"
9728                    "|||||||\n"
9729                    "int i;\n"
9730                    "=======\n"
9731                    ">>>>>>>"));
9732 
9733   // FIXME: Handle parsing of macros around conflict markers correctly:
9734   EXPECT_EQ("#define Macro \\\n"
9735             "<<<<<<<\n"
9736             "Something \\\n"
9737             "|||||||\n"
9738             "Else \\\n"
9739             "=======\n"
9740             "Other \\\n"
9741             ">>>>>>>\n"
9742             "    End int i;\n",
9743             format("#define Macro \\\n"
9744                    "<<<<<<<\n"
9745                    "  Something \\\n"
9746                    "|||||||\n"
9747                    "  Else \\\n"
9748                    "=======\n"
9749                    "  Other \\\n"
9750                    ">>>>>>>\n"
9751                    "  End\n"
9752                    "int i;\n"));
9753 }
9754 
TEST_F(FormatTest,DisableRegions)9755 TEST_F(FormatTest, DisableRegions) {
9756   EXPECT_EQ("int i;\n"
9757             "// clang-format off\n"
9758             "  int j;\n"
9759             "// clang-format on\n"
9760             "int k;",
9761             format(" int  i;\n"
9762                    "   // clang-format off\n"
9763                    "  int j;\n"
9764                    " // clang-format on\n"
9765                    "   int   k;"));
9766   EXPECT_EQ("int i;\n"
9767             "/* clang-format off */\n"
9768             "  int j;\n"
9769             "/* clang-format on */\n"
9770             "int k;",
9771             format(" int  i;\n"
9772                    "   /* clang-format off */\n"
9773                    "  int j;\n"
9774                    " /* clang-format on */\n"
9775                    "   int   k;"));
9776 }
9777 
TEST_F(FormatTest,DoNotCrashOnInvalidInput)9778 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
9779   format("? ) =");
9780 }
9781 
9782 } // end namespace tooling
9783 } // end namespace clang
9784