]> granicus.if.org Git - clang/blob - unittests/Format/FormatTest.cpp
22c469815b169d718a599e9013f8b13e1aa7a0fe
[clang] / unittests / Format / FormatTest.cpp
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 namespace {
20
21 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
22
23 class FormatTest : public ::testing::Test {
24 protected:
25   enum IncompleteCheck {
26     IC_ExpectComplete,
27     IC_ExpectIncomplete,
28     IC_DoNotCheck
29   };
30
31   std::string format(llvm::StringRef Code,
32                      const FormatStyle &Style = getLLVMStyle(),
33                      IncompleteCheck CheckIncomplete = IC_ExpectComplete) {
34     DEBUG(llvm::errs() << "---\n");
35     DEBUG(llvm::errs() << Code << "\n\n");
36     std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
37     bool IncompleteFormat = false;
38     tooling::Replacements Replaces =
39         reformat(Style, Code, Ranges, "<stdin>", &IncompleteFormat);
40     if (CheckIncomplete != IC_DoNotCheck) {
41       bool ExpectedIncompleteFormat = CheckIncomplete == IC_ExpectIncomplete;
42       EXPECT_EQ(ExpectedIncompleteFormat, IncompleteFormat) << Code << "\n\n";
43     }
44     ReplacementCount = Replaces.size();
45     std::string Result = applyAllReplacements(Code, Replaces);
46     EXPECT_NE("", Result);
47     DEBUG(llvm::errs() << "\n" << Result << "\n\n");
48     return Result;
49   }
50
51   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
52     FormatStyle Style = getLLVMStyle();
53     Style.ColumnLimit = ColumnLimit;
54     return Style;
55   }
56
57   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
58     FormatStyle Style = getGoogleStyle();
59     Style.ColumnLimit = ColumnLimit;
60     return Style;
61   }
62
63   void verifyFormat(llvm::StringRef Code,
64                     const FormatStyle &Style = getLLVMStyle()) {
65     EXPECT_EQ(Code.str(), format(test::messUp(Code), Style));
66   }
67
68   void verifyIncompleteFormat(llvm::StringRef Code,
69                               const FormatStyle &Style = getLLVMStyle()) {
70     EXPECT_EQ(Code.str(),
71               format(test::messUp(Code), Style, IC_ExpectIncomplete));
72   }
73
74   void verifyGoogleFormat(llvm::StringRef Code) {
75     verifyFormat(Code, getGoogleStyle());
76   }
77
78   void verifyIndependentOfContext(llvm::StringRef text) {
79     verifyFormat(text);
80     verifyFormat(llvm::Twine("void f() { " + text + " }").str());
81   }
82
83   /// \brief Verify that clang-format does not crash on the given input.
84   void verifyNoCrash(llvm::StringRef Code,
85                      const FormatStyle &Style = getLLVMStyle()) {
86     format(Code, Style, IC_DoNotCheck);
87   }
88
89   int ReplacementCount;
90 };
91
92 TEST_F(FormatTest, MessUp) {
93   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
94   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
95   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
96   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
97   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
98 }
99
100 //===----------------------------------------------------------------------===//
101 // Basic function tests.
102 //===----------------------------------------------------------------------===//
103
104 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
105   EXPECT_EQ(";", format(";"));
106 }
107
108 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
109   EXPECT_EQ("int i;", format("  int i;"));
110   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
111   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
112   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
113 }
114
115 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
116   EXPECT_EQ("int i;", format("int\ni;"));
117 }
118
119 TEST_F(FormatTest, FormatsNestedBlockStatements) {
120   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
121 }
122
123 TEST_F(FormatTest, FormatsNestedCall) {
124   verifyFormat("Method(f1, f2(f3));");
125   verifyFormat("Method(f1(f2, f3()));");
126   verifyFormat("Method(f1(f2, (f3())));");
127 }
128
129 TEST_F(FormatTest, NestedNameSpecifiers) {
130   verifyFormat("vector<::Type> v;");
131   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
132   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
133   verifyFormat("bool a = 2 < ::SomeFunction();");
134 }
135
136 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
137   EXPECT_EQ("if (a) {\n"
138             "  f();\n"
139             "}",
140             format("if(a){f();}"));
141   EXPECT_EQ(4, ReplacementCount);
142   EXPECT_EQ("if (a) {\n"
143             "  f();\n"
144             "}",
145             format("if (a) {\n"
146                    "  f();\n"
147                    "}"));
148   EXPECT_EQ(0, ReplacementCount);
149   EXPECT_EQ("/*\r\n"
150             "\r\n"
151             "*/\r\n",
152             format("/*\r\n"
153                    "\r\n"
154                    "*/\r\n"));
155   EXPECT_EQ(0, ReplacementCount);
156 }
157
158 TEST_F(FormatTest, RemovesEmptyLines) {
159   EXPECT_EQ("class C {\n"
160             "  int i;\n"
161             "};",
162             format("class C {\n"
163                    " int i;\n"
164                    "\n"
165                    "};"));
166
167   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
168   EXPECT_EQ("namespace N {\n"
169             "\n"
170             "int i;\n"
171             "}",
172             format("namespace N {\n"
173                    "\n"
174                    "int    i;\n"
175                    "}",
176                    getGoogleStyle()));
177   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
178             "\n"
179             "int i;\n"
180             "}",
181             format("extern /**/ \"C\" /**/ {\n"
182                    "\n"
183                    "int    i;\n"
184                    "}",
185                    getGoogleStyle()));
186
187   // ...but do keep inlining and removing empty lines for non-block extern "C"
188   // functions.
189   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
190   EXPECT_EQ("extern \"C\" int f() {\n"
191             "  int i = 42;\n"
192             "  return i;\n"
193             "}",
194             format("extern \"C\" int f() {\n"
195                    "\n"
196                    "  int i = 42;\n"
197                    "  return i;\n"
198                    "}",
199                    getGoogleStyle()));
200
201   // Remove empty lines at the beginning and end of blocks.
202   EXPECT_EQ("void f() {\n"
203             "\n"
204             "  if (a) {\n"
205             "\n"
206             "    f();\n"
207             "  }\n"
208             "}",
209             format("void f() {\n"
210                    "\n"
211                    "  if (a) {\n"
212                    "\n"
213                    "    f();\n"
214                    "\n"
215                    "  }\n"
216                    "\n"
217                    "}",
218                    getLLVMStyle()));
219   EXPECT_EQ("void f() {\n"
220             "  if (a) {\n"
221             "    f();\n"
222             "  }\n"
223             "}",
224             format("void f() {\n"
225                    "\n"
226                    "  if (a) {\n"
227                    "\n"
228                    "    f();\n"
229                    "\n"
230                    "  }\n"
231                    "\n"
232                    "}",
233                    getGoogleStyle()));
234
235   // Don't remove empty lines in more complex control statements.
236   EXPECT_EQ("void f() {\n"
237             "  if (a) {\n"
238             "    f();\n"
239             "\n"
240             "  } else if (b) {\n"
241             "    f();\n"
242             "  }\n"
243             "}",
244             format("void f() {\n"
245                    "  if (a) {\n"
246                    "    f();\n"
247                    "\n"
248                    "  } else if (b) {\n"
249                    "    f();\n"
250                    "\n"
251                    "  }\n"
252                    "\n"
253                    "}"));
254
255   // FIXME: This is slightly inconsistent.
256   EXPECT_EQ("namespace {\n"
257             "int i;\n"
258             "}",
259             format("namespace {\n"
260                    "int i;\n"
261                    "\n"
262                    "}"));
263   EXPECT_EQ("namespace {\n"
264             "int i;\n"
265             "\n"
266             "} // namespace",
267             format("namespace {\n"
268                    "int i;\n"
269                    "\n"
270                    "}  // namespace"));
271 }
272
273 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
274   verifyFormat("x = (a) and (b);");
275   verifyFormat("x = (a) or (b);");
276   verifyFormat("x = (a) bitand (b);");
277   verifyFormat("x = (a) bitor (b);");
278   verifyFormat("x = (a) not_eq (b);");
279   verifyFormat("x = (a) and_eq (b);");
280   verifyFormat("x = (a) or_eq (b);");
281   verifyFormat("x = (a) xor (b);");
282 }
283
284 //===----------------------------------------------------------------------===//
285 // Tests for control statements.
286 //===----------------------------------------------------------------------===//
287
288 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
289   verifyFormat("if (true)\n  f();\ng();");
290   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
291   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
292
293   FormatStyle AllowsMergedIf = getLLVMStyle();
294   AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
295   verifyFormat("if (a)\n"
296                "  // comment\n"
297                "  f();",
298                AllowsMergedIf);
299   verifyFormat("if (a)\n"
300                "  ;",
301                AllowsMergedIf);
302   verifyFormat("if (a)\n"
303                "  if (b) return;",
304                AllowsMergedIf);
305
306   verifyFormat("if (a) // Can't merge this\n"
307                "  f();\n",
308                AllowsMergedIf);
309   verifyFormat("if (a) /* still don't merge */\n"
310                "  f();",
311                AllowsMergedIf);
312   verifyFormat("if (a) { // Never merge this\n"
313                "  f();\n"
314                "}",
315                AllowsMergedIf);
316   verifyFormat("if (a) { /* Never merge this */\n"
317                "  f();\n"
318                "}",
319                AllowsMergedIf);
320
321   AllowsMergedIf.ColumnLimit = 14;
322   verifyFormat("if (a) return;", AllowsMergedIf);
323   verifyFormat("if (aaaaaaaaa)\n"
324                "  return;",
325                AllowsMergedIf);
326
327   AllowsMergedIf.ColumnLimit = 13;
328   verifyFormat("if (a)\n  return;", AllowsMergedIf);
329 }
330
331 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
332   FormatStyle AllowsMergedLoops = getLLVMStyle();
333   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
334   verifyFormat("while (true) continue;", AllowsMergedLoops);
335   verifyFormat("for (;;) continue;", AllowsMergedLoops);
336   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
337   verifyFormat("while (true)\n"
338                "  ;",
339                AllowsMergedLoops);
340   verifyFormat("for (;;)\n"
341                "  ;",
342                AllowsMergedLoops);
343   verifyFormat("for (;;)\n"
344                "  for (;;) continue;",
345                AllowsMergedLoops);
346   verifyFormat("for (;;) // Can't merge this\n"
347                "  continue;",
348                AllowsMergedLoops);
349   verifyFormat("for (;;) /* still don't merge */\n"
350                "  continue;",
351                AllowsMergedLoops);
352 }
353
354 TEST_F(FormatTest, FormatShortBracedStatements) {
355   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
356   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine = true;
357
358   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = true;
359   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
360
361   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
362   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
363   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
364   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
365   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
366   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
367   verifyFormat("if (true) { //\n"
368                "  f();\n"
369                "}",
370                AllowSimpleBracedStatements);
371   verifyFormat("if (true) {\n"
372                "  f();\n"
373                "  f();\n"
374                "}",
375                AllowSimpleBracedStatements);
376   verifyFormat("if (true) {\n"
377                "  f();\n"
378                "} else {\n"
379                "  f();\n"
380                "}",
381                AllowSimpleBracedStatements);
382
383   verifyFormat("template <int> struct A2 {\n"
384                "  struct B {};\n"
385                "};",
386                AllowSimpleBracedStatements);
387
388   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine = false;
389   verifyFormat("if (true) {\n"
390                "  f();\n"
391                "}",
392                AllowSimpleBracedStatements);
393   verifyFormat("if (true) {\n"
394                "  f();\n"
395                "} else {\n"
396                "  f();\n"
397                "}",
398                AllowSimpleBracedStatements);
399
400   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
401   verifyFormat("while (true) {\n"
402                "  f();\n"
403                "}",
404                AllowSimpleBracedStatements);
405   verifyFormat("for (;;) {\n"
406                "  f();\n"
407                "}",
408                AllowSimpleBracedStatements);
409 }
410
411 TEST_F(FormatTest, ParseIfElse) {
412   verifyFormat("if (true)\n"
413                "  if (true)\n"
414                "    if (true)\n"
415                "      f();\n"
416                "    else\n"
417                "      g();\n"
418                "  else\n"
419                "    h();\n"
420                "else\n"
421                "  i();");
422   verifyFormat("if (true)\n"
423                "  if (true)\n"
424                "    if (true) {\n"
425                "      if (true)\n"
426                "        f();\n"
427                "    } else {\n"
428                "      g();\n"
429                "    }\n"
430                "  else\n"
431                "    h();\n"
432                "else {\n"
433                "  i();\n"
434                "}");
435   verifyFormat("void f() {\n"
436                "  if (a) {\n"
437                "  } else {\n"
438                "  }\n"
439                "}");
440 }
441
442 TEST_F(FormatTest, ElseIf) {
443   verifyFormat("if (a) {\n} else if (b) {\n}");
444   verifyFormat("if (a)\n"
445                "  f();\n"
446                "else if (b)\n"
447                "  g();\n"
448                "else\n"
449                "  h();");
450   verifyFormat("if (a) {\n"
451                "  f();\n"
452                "}\n"
453                "// or else ..\n"
454                "else {\n"
455                "  g()\n"
456                "}");
457
458   verifyFormat("if (a) {\n"
459                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
460                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
461                "}");
462   verifyFormat("if (a) {\n"
463                "} else if (\n"
464                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
465                "}",
466                getLLVMStyleWithColumns(62));
467 }
468
469 TEST_F(FormatTest, FormatsForLoop) {
470   verifyFormat(
471       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
472       "     ++VeryVeryLongLoopVariable)\n"
473       "  ;");
474   verifyFormat("for (;;)\n"
475                "  f();");
476   verifyFormat("for (;;) {\n}");
477   verifyFormat("for (;;) {\n"
478                "  f();\n"
479                "}");
480   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
481
482   verifyFormat(
483       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
484       "                                          E = UnwrappedLines.end();\n"
485       "     I != E; ++I) {\n}");
486
487   verifyFormat(
488       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
489       "     ++IIIII) {\n}");
490   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
491                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
492                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
493   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
494                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
495                "         E = FD->getDeclsInPrototypeScope().end();\n"
496                "     I != E; ++I) {\n}");
497   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
498                "         I = Container.begin(),\n"
499                "         E = Container.end();\n"
500                "     I != E; ++I) {\n}",
501                getLLVMStyleWithColumns(76));
502
503   verifyFormat(
504       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
505       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
506       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
507       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
508       "     ++aaaaaaaaaaa) {\n}");
509   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
510                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
511                "     ++i) {\n}");
512   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
513                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
514                "}");
515   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
516                "         aaaaaaaaaa);\n"
517                "     iter; ++iter) {\n"
518                "}");
519   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
520                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
521                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
522                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
523
524   FormatStyle NoBinPacking = getLLVMStyle();
525   NoBinPacking.BinPackParameters = false;
526   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
527                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
528                "                                           aaaaaaaaaaaaaaaa,\n"
529                "                                           aaaaaaaaaaaaaaaa,\n"
530                "                                           aaaaaaaaaaaaaaaa);\n"
531                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
532                "}",
533                NoBinPacking);
534   verifyFormat(
535       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
536       "                                          E = UnwrappedLines.end();\n"
537       "     I != E;\n"
538       "     ++I) {\n}",
539       NoBinPacking);
540 }
541
542 TEST_F(FormatTest, RangeBasedForLoops) {
543   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
544                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
545   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
546                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
547   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
548                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
549   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
550                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
551 }
552
553 TEST_F(FormatTest, ForEachLoops) {
554   verifyFormat("void f() {\n"
555                "  foreach (Item *item, itemlist) {}\n"
556                "  Q_FOREACH (Item *item, itemlist) {}\n"
557                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
558                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
559                "}");
560
561   // As function-like macros.
562   verifyFormat("#define foreach(x, y)\n"
563                "#define Q_FOREACH(x, y)\n"
564                "#define BOOST_FOREACH(x, y)\n"
565                "#define UNKNOWN_FOREACH(x, y)\n");
566
567   // Not as function-like macros.
568   verifyFormat("#define foreach (x, y)\n"
569                "#define Q_FOREACH (x, y)\n"
570                "#define BOOST_FOREACH (x, y)\n"
571                "#define UNKNOWN_FOREACH (x, y)\n");
572 }
573
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
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
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                "  }",
668                getLLVMStyleWithColumns(20));
669   verifyFormat("#define OPERATION_CASE(name)           \\\n"
670                "  case OP_name:                        \\\n"
671                "    return operations::Operation##name\n",
672                getLLVMStyleWithColumns(40));
673   verifyFormat("switch (x) {\n"
674                "case 1:;\n"
675                "default:;\n"
676                "  int i;\n"
677                "}");
678
679   verifyGoogleFormat("switch (x) {\n"
680                      "  case 1:\n"
681                      "    f();\n"
682                      "    break;\n"
683                      "  case kFoo:\n"
684                      "  case ns::kBar:\n"
685                      "  case kBaz:\n"
686                      "    break;\n"
687                      "  default:\n"
688                      "    g();\n"
689                      "    break;\n"
690                      "}");
691   verifyGoogleFormat("switch (x) {\n"
692                      "  case 1: {\n"
693                      "    f();\n"
694                      "    break;\n"
695                      "  }\n"
696                      "}");
697   verifyGoogleFormat("switch (test)\n"
698                      "  ;");
699
700   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
701                      "  case OP_name:              \\\n"
702                      "    return operations::Operation##name\n");
703   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
704                      "  // Get the correction operation class.\n"
705                      "  switch (OpCode) {\n"
706                      "    CASE(Add);\n"
707                      "    CASE(Subtract);\n"
708                      "    default:\n"
709                      "      return operations::Unknown;\n"
710                      "  }\n"
711                      "#undef OPERATION_CASE\n"
712                      "}");
713   verifyFormat("DEBUG({\n"
714                "  switch (x) {\n"
715                "  case A:\n"
716                "    f();\n"
717                "    break;\n"
718                "  // On B:\n"
719                "  case B:\n"
720                "    g();\n"
721                "    break;\n"
722                "  }\n"
723                "});");
724   verifyFormat("switch (a) {\n"
725                "case (b):\n"
726                "  return;\n"
727                "}");
728
729   verifyFormat("switch (a) {\n"
730                "case some_namespace::\n"
731                "    some_constant:\n"
732                "  return;\n"
733                "}",
734                getLLVMStyleWithColumns(34));
735 }
736
737 TEST_F(FormatTest, CaseRanges) {
738   verifyFormat("switch (x) {\n"
739                "case 'A' ... 'Z':\n"
740                "case 1 ... 5:\n"
741                "  break;\n"
742                "}");
743 }
744
745 TEST_F(FormatTest, ShortCaseLabels) {
746   FormatStyle Style = getLLVMStyle();
747   Style.AllowShortCaseLabelsOnASingleLine = true;
748   verifyFormat("switch (a) {\n"
749                "case 1: x = 1; break;\n"
750                "case 2: return;\n"
751                "case 3:\n"
752                "case 4:\n"
753                "case 5: return;\n"
754                "case 6: // comment\n"
755                "  return;\n"
756                "case 7:\n"
757                "  // comment\n"
758                "  return;\n"
759                "case 8:\n"
760                "  x = 8; // comment\n"
761                "  break;\n"
762                "default: y = 1; break;\n"
763                "}",
764                Style);
765   verifyFormat("switch (a) {\n"
766                "#if FOO\n"
767                "case 0: return 0;\n"
768                "#endif\n"
769                "}",
770                Style);
771   verifyFormat("switch (a) {\n"
772                "case 1: {\n"
773                "}\n"
774                "case 2: {\n"
775                "  return;\n"
776                "}\n"
777                "case 3: {\n"
778                "  x = 1;\n"
779                "  return;\n"
780                "}\n"
781                "case 4:\n"
782                "  if (x)\n"
783                "    return;\n"
784                "}",
785                Style);
786   Style.ColumnLimit = 21;
787   verifyFormat("switch (a) {\n"
788                "case 1: x = 1; break;\n"
789                "case 2: return;\n"
790                "case 3:\n"
791                "case 4:\n"
792                "case 5: return;\n"
793                "default:\n"
794                "  y = 1;\n"
795                "  break;\n"
796                "}",
797                Style);
798 }
799
800 TEST_F(FormatTest, FormatsLabels) {
801   verifyFormat("void f() {\n"
802                "  some_code();\n"
803                "test_label:\n"
804                "  some_other_code();\n"
805                "  {\n"
806                "    some_more_code();\n"
807                "  another_label:\n"
808                "    some_more_code();\n"
809                "  }\n"
810                "}");
811   verifyFormat("{\n"
812                "  some_code();\n"
813                "test_label:\n"
814                "  some_other_code();\n"
815                "}");
816   verifyFormat("{\n"
817                "  some_code();\n"
818                "test_label:;\n"
819                "  int i = 0;\n"
820                "}");
821 }
822
823 //===----------------------------------------------------------------------===//
824 // Tests for comments.
825 //===----------------------------------------------------------------------===//
826
827 TEST_F(FormatTest, UnderstandsSingleLineComments) {
828   verifyFormat("//* */");
829   verifyFormat("// line 1\n"
830                "// line 2\n"
831                "void f() {}\n");
832
833   verifyFormat("void f() {\n"
834                "  // Doesn't do anything\n"
835                "}");
836   verifyFormat("SomeObject\n"
837                "    // Calling someFunction on SomeObject\n"
838                "    .someFunction();");
839   verifyFormat("auto result = SomeObject\n"
840                "                  // Calling someFunction on SomeObject\n"
841                "                  .someFunction();");
842   verifyFormat("void f(int i,  // some comment (probably for i)\n"
843                "       int j,  // some comment (probably for j)\n"
844                "       int k); // some comment (probably for k)");
845   verifyFormat("void f(int i,\n"
846                "       // some comment (probably for j)\n"
847                "       int j,\n"
848                "       // some comment (probably for k)\n"
849                "       int k);");
850
851   verifyFormat("int i    // This is a fancy variable\n"
852                "    = 5; // with nicely aligned comment.");
853
854   verifyFormat("// Leading comment.\n"
855                "int a; // Trailing comment.");
856   verifyFormat("int a; // Trailing comment\n"
857                "       // on 2\n"
858                "       // or 3 lines.\n"
859                "int b;");
860   verifyFormat("int a; // Trailing comment\n"
861                "\n"
862                "// Leading comment.\n"
863                "int b;");
864   verifyFormat("int a;    // Comment.\n"
865                "          // More details.\n"
866                "int bbbb; // Another comment.");
867   verifyFormat(
868       "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
869       "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   // comment\n"
870       "int cccccccccccccccccccccccccccccc;       // comment\n"
871       "int ddd;                     // looooooooooooooooooooooooong comment\n"
872       "int aaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
873       "int bbbbbbbbbbbbbbbbbbbbb;   // comment\n"
874       "int ccccccccccccccccccc;     // comment");
875
876   verifyFormat("#include \"a\"     // comment\n"
877                "#include \"a/b/c\" // comment");
878   verifyFormat("#include <a>     // comment\n"
879                "#include <a/b/c> // comment");
880   EXPECT_EQ("#include \"a\"     // comment\n"
881             "#include \"a/b/c\" // comment",
882             format("#include \\\n"
883                    "  \"a\" // comment\n"
884                    "#include \"a/b/c\" // comment"));
885
886   verifyFormat("enum E {\n"
887                "  // comment\n"
888                "  VAL_A, // comment\n"
889                "  VAL_B\n"
890                "};");
891
892   verifyFormat(
893       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
894       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // Trailing comment");
895   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
896                "    // Comment inside a statement.\n"
897                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
898   verifyFormat("SomeFunction(a,\n"
899                "             // comment\n"
900                "             b + x);");
901   verifyFormat("SomeFunction(a, a,\n"
902                "             // comment\n"
903                "             b + x);");
904   verifyFormat(
905       "bool aaaaaaaaaaaaa = // comment\n"
906       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
907       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
908
909   verifyFormat("int aaaa; // aaaaa\n"
910                "int aa;   // aaaaaaa",
911                getLLVMStyleWithColumns(20));
912
913   EXPECT_EQ("void f() { // This does something ..\n"
914             "}\n"
915             "int a; // This is unrelated",
916             format("void f()    {     // This does something ..\n"
917                    "  }\n"
918                    "int   a;     // This is unrelated"));
919   EXPECT_EQ("class C {\n"
920             "  void f() { // This does something ..\n"
921             "  }          // awesome..\n"
922             "\n"
923             "  int a; // This is unrelated\n"
924             "};",
925             format("class C{void f()    { // This does something ..\n"
926                    "      } // awesome..\n"
927                    " \n"
928                    "int a;    // This is unrelated\n"
929                    "};"));
930
931   EXPECT_EQ("int i; // single line trailing comment",
932             format("int i;\\\n// single line trailing comment"));
933
934   verifyGoogleFormat("int a;  // Trailing comment.");
935
936   verifyFormat("someFunction(anotherFunction( // Force break.\n"
937                "    parameter));");
938
939   verifyGoogleFormat("#endif  // HEADER_GUARD");
940
941   verifyFormat("const char *test[] = {\n"
942                "    // A\n"
943                "    \"aaaa\",\n"
944                "    // B\n"
945                "    \"aaaaa\"};");
946   verifyGoogleFormat(
947       "aaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
948       "    aaaaaaaaaaaaaaaaaaaaaa);  // 81_cols_with_this_comment");
949   EXPECT_EQ("D(a, {\n"
950             "  // test\n"
951             "  int a;\n"
952             "});",
953             format("D(a, {\n"
954                    "// test\n"
955                    "int a;\n"
956                    "});"));
957
958   EXPECT_EQ("lineWith(); // comment\n"
959             "// at start\n"
960             "otherLine();",
961             format("lineWith();   // comment\n"
962                    "// at start\n"
963                    "otherLine();"));
964   EXPECT_EQ("lineWith(); // comment\n"
965             "            // at start\n"
966             "otherLine();",
967             format("lineWith();   // comment\n"
968                    " // at start\n"
969                    "otherLine();"));
970
971   EXPECT_EQ("lineWith(); // comment\n"
972             "// at start\n"
973             "otherLine(); // comment",
974             format("lineWith();   // comment\n"
975                    "// at start\n"
976                    "otherLine();   // comment"));
977   EXPECT_EQ("lineWith();\n"
978             "// at start\n"
979             "otherLine(); // comment",
980             format("lineWith();\n"
981                    " // at start\n"
982                    "otherLine();   // comment"));
983   EXPECT_EQ("// first\n"
984             "// at start\n"
985             "otherLine(); // comment",
986             format("// first\n"
987                    " // at start\n"
988                    "otherLine();   // comment"));
989   EXPECT_EQ("f();\n"
990             "// first\n"
991             "// at start\n"
992             "otherLine(); // comment",
993             format("f();\n"
994                    "// first\n"
995                    " // at start\n"
996                    "otherLine();   // comment"));
997   verifyFormat("f(); // comment\n"
998                "// first\n"
999                "// at start\n"
1000                "otherLine();");
1001   EXPECT_EQ("f(); // comment\n"
1002             "// first\n"
1003             "// at start\n"
1004             "otherLine();",
1005             format("f();   // comment\n"
1006                    "// first\n"
1007                    " // at start\n"
1008                    "otherLine();"));
1009   EXPECT_EQ("f(); // comment\n"
1010             "     // first\n"
1011             "// at start\n"
1012             "otherLine();",
1013             format("f();   // comment\n"
1014                    " // first\n"
1015                    "// at start\n"
1016                    "otherLine();"));
1017   EXPECT_EQ("void f() {\n"
1018             "  lineWith(); // comment\n"
1019             "  // at start\n"
1020             "}",
1021             format("void              f() {\n"
1022                    "  lineWith(); // comment\n"
1023                    "  // at start\n"
1024                    "}"));
1025
1026   verifyFormat("#define A                                                  \\\n"
1027                "  int i; /* iiiiiiiiiiiiiiiiiiiii */                       \\\n"
1028                "  int jjjjjjjjjjjjjjjjjjjjjjjj; /* */",
1029                getLLVMStyleWithColumns(60));
1030   verifyFormat(
1031       "#define A                                                   \\\n"
1032       "  int i;                        /* iiiiiiiiiiiiiiiiiiiii */ \\\n"
1033       "  int jjjjjjjjjjjjjjjjjjjjjjjj; /* */",
1034       getLLVMStyleWithColumns(61));
1035
1036   verifyFormat("if ( // This is some comment\n"
1037                "    x + 3) {\n"
1038                "}");
1039   EXPECT_EQ("if ( // This is some comment\n"
1040             "     // spanning two lines\n"
1041             "    x + 3) {\n"
1042             "}",
1043             format("if( // This is some comment\n"
1044                    "     // spanning two lines\n"
1045                    " x + 3) {\n"
1046                    "}"));
1047
1048   verifyNoCrash("/\\\n/");
1049   verifyNoCrash("/\\\n* */");
1050   // The 0-character somehow makes the lexer return a proper comment.
1051   verifyNoCrash(StringRef("/*\\\0\n/", 6));
1052 }
1053
1054 TEST_F(FormatTest, KeepsParameterWithTrailingCommentsOnTheirOwnLine) {
1055   EXPECT_EQ("SomeFunction(a,\n"
1056             "             b, // comment\n"
1057             "             c);",
1058             format("SomeFunction(a,\n"
1059                    "          b, // comment\n"
1060                    "      c);"));
1061   EXPECT_EQ("SomeFunction(a, b,\n"
1062             "             // comment\n"
1063             "             c);",
1064             format("SomeFunction(a,\n"
1065                    "          b,\n"
1066                    "  // comment\n"
1067                    "      c);"));
1068   EXPECT_EQ("SomeFunction(a, b, // comment (unclear relation)\n"
1069             "             c);",
1070             format("SomeFunction(a, b, // comment (unclear relation)\n"
1071                    "      c);"));
1072   EXPECT_EQ("SomeFunction(a, // comment\n"
1073             "             b,\n"
1074             "             c); // comment",
1075             format("SomeFunction(a,     // comment\n"
1076                    "          b,\n"
1077                    "      c); // comment"));
1078 }
1079
1080 TEST_F(FormatTest, RemovesTrailingWhitespaceOfComments) {
1081   EXPECT_EQ("// comment", format("// comment  "));
1082   EXPECT_EQ("int aaaaaaa, bbbbbbb; // comment",
1083             format("int aaaaaaa, bbbbbbb; // comment                   ",
1084                    getLLVMStyleWithColumns(33)));
1085   EXPECT_EQ("// comment\\\n", format("// comment\\\n  \t \v   \f   "));
1086   EXPECT_EQ("// comment    \\\n", format("// comment    \\\n  \t \v   \f   "));
1087 }
1088
1089 TEST_F(FormatTest, UnderstandsBlockComments) {
1090   verifyFormat("f(/*noSpaceAfterParameterNamingComment=*/true);");
1091   verifyFormat("void f() { g(/*aaa=*/x, /*bbb=*/!y); }");
1092   EXPECT_EQ("f(aaaaaaaaaaaaaaaaaaaaaaaaa, /* Trailing comment for aa... */\n"
1093             "  bbbbbbbbbbbbbbbbbbbbbbbbb);",
1094             format("f(aaaaaaaaaaaaaaaaaaaaaaaaa ,   \\\n"
1095                    "/* Trailing comment for aa... */\n"
1096                    "  bbbbbbbbbbbbbbbbbbbbbbbbb);"));
1097   EXPECT_EQ(
1098       "f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1099       "  /* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);",
1100       format("f(aaaaaaaaaaaaaaaaaaaaaaaaa    ,   \n"
1101              "/* Leading comment for bb... */   bbbbbbbbbbbbbbbbbbbbbbbbb);"));
1102   EXPECT_EQ(
1103       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1104       "    aaaaaaaaaaaaaaaaaa,\n"
1105       "    aaaaaaaaaaaaaaaaaa) { /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
1106       "}",
1107       format("void      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1108              "                      aaaaaaaaaaaaaaaaaa  ,\n"
1109              "    aaaaaaaaaaaaaaaaaa) {   /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
1110              "}"));
1111
1112   FormatStyle NoBinPacking = getLLVMStyle();
1113   NoBinPacking.BinPackParameters = false;
1114   verifyFormat("aaaaaaaa(/* parameter 1 */ aaaaaa,\n"
1115                "         /* parameter 2 */ aaaaaa,\n"
1116                "         /* parameter 3 */ aaaaaa,\n"
1117                "         /* parameter 4 */ aaaaaa);",
1118                NoBinPacking);
1119
1120   // Aligning block comments in macros.
1121   verifyGoogleFormat("#define A        \\\n"
1122                      "  int i;   /*a*/ \\\n"
1123                      "  int jjj; /*b*/");
1124 }
1125
1126 TEST_F(FormatTest, AlignsBlockComments) {
1127   EXPECT_EQ("/*\n"
1128             " * Really multi-line\n"
1129             " * comment.\n"
1130             " */\n"
1131             "void f() {}",
1132             format("  /*\n"
1133                    "   * Really multi-line\n"
1134                    "   * comment.\n"
1135                    "   */\n"
1136                    "  void f() {}"));
1137   EXPECT_EQ("class C {\n"
1138             "  /*\n"
1139             "   * Another multi-line\n"
1140             "   * comment.\n"
1141             "   */\n"
1142             "  void f() {}\n"
1143             "};",
1144             format("class C {\n"
1145                    "/*\n"
1146                    " * Another multi-line\n"
1147                    " * comment.\n"
1148                    " */\n"
1149                    "void f() {}\n"
1150                    "};"));
1151   EXPECT_EQ("/*\n"
1152             "  1. This is a comment with non-trivial formatting.\n"
1153             "     1.1. We have to indent/outdent all lines equally\n"
1154             "         1.1.1. to keep the formatting.\n"
1155             " */",
1156             format("  /*\n"
1157                    "    1. This is a comment with non-trivial formatting.\n"
1158                    "       1.1. We have to indent/outdent all lines equally\n"
1159                    "           1.1.1. to keep the formatting.\n"
1160                    "   */"));
1161   EXPECT_EQ("/*\n"
1162             "Don't try to outdent if there's not enough indentation.\n"
1163             "*/",
1164             format("  /*\n"
1165                    " Don't try to outdent if there's not enough indentation.\n"
1166                    " */"));
1167
1168   EXPECT_EQ("int i; /* Comment with empty...\n"
1169             "        *\n"
1170             "        * line. */",
1171             format("int i; /* Comment with empty...\n"
1172                    "        *\n"
1173                    "        * line. */"));
1174   EXPECT_EQ("int foobar = 0; /* comment */\n"
1175             "int bar = 0;    /* multiline\n"
1176             "                   comment 1 */\n"
1177             "int baz = 0;    /* multiline\n"
1178             "                   comment 2 */\n"
1179             "int bzz = 0;    /* multiline\n"
1180             "                   comment 3 */",
1181             format("int foobar = 0; /* comment */\n"
1182                    "int bar = 0;    /* multiline\n"
1183                    "                   comment 1 */\n"
1184                    "int baz = 0; /* multiline\n"
1185                    "                comment 2 */\n"
1186                    "int bzz = 0;         /* multiline\n"
1187                    "                        comment 3 */"));
1188   EXPECT_EQ("int foobar = 0; /* comment */\n"
1189             "int bar = 0;    /* multiline\n"
1190             "   comment */\n"
1191             "int baz = 0;    /* multiline\n"
1192             "comment */",
1193             format("int foobar = 0; /* comment */\n"
1194                    "int bar = 0; /* multiline\n"
1195                    "comment */\n"
1196                    "int baz = 0;        /* multiline\n"
1197                    "comment */"));
1198 }
1199
1200 TEST_F(FormatTest, CommentReflowingCanBeTurnedOff) {
1201   FormatStyle Style = getLLVMStyleWithColumns(20);
1202   Style.ReflowComments = false;
1203   verifyFormat("// aaaaaaaaa aaaaaaaaaa aaaaaaaaaa", Style);
1204   verifyFormat("/* aaaaaaaaa aaaaaaaaaa aaaaaaaaaa */", Style);
1205 }
1206
1207 TEST_F(FormatTest, CorrectlyHandlesLengthOfBlockComments) {
1208   EXPECT_EQ("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1209             "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */",
1210             format("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1211                    "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */"));
1212   EXPECT_EQ(
1213       "void ffffffffffff(\n"
1214       "    int aaaaaaaa, int bbbbbbbb,\n"
1215       "    int cccccccccccc) { /*\n"
1216       "                           aaaaaaaaaa\n"
1217       "                           aaaaaaaaaaaaa\n"
1218       "                           bbbbbbbbbbbbbb\n"
1219       "                           bbbbbbbbbb\n"
1220       "                         */\n"
1221       "}",
1222       format("void ffffffffffff(int aaaaaaaa, int bbbbbbbb, int cccccccccccc)\n"
1223              "{ /*\n"
1224              "     aaaaaaaaaa aaaaaaaaaaaaa\n"
1225              "     bbbbbbbbbbbbbb bbbbbbbbbb\n"
1226              "   */\n"
1227              "}",
1228              getLLVMStyleWithColumns(40)));
1229 }
1230
1231 TEST_F(FormatTest, DontBreakNonTrailingBlockComments) {
1232   EXPECT_EQ("void ffffffffff(\n"
1233             "    int aaaaa /* test */);",
1234             format("void ffffffffff(int aaaaa /* test */);",
1235                    getLLVMStyleWithColumns(35)));
1236 }
1237
1238 TEST_F(FormatTest, SplitsLongCxxComments) {
1239   EXPECT_EQ("// A comment that\n"
1240             "// doesn't fit on\n"
1241             "// one line",
1242             format("// A comment that doesn't fit on one line",
1243                    getLLVMStyleWithColumns(20)));
1244   EXPECT_EQ("/// A comment that\n"
1245             "/// doesn't fit on\n"
1246             "/// one line",
1247             format("/// A comment that doesn't fit on one line",
1248                    getLLVMStyleWithColumns(20)));
1249   EXPECT_EQ("//! A comment that\n"
1250             "//! doesn't fit on\n"
1251             "//! one line",
1252             format("//! A comment that doesn't fit on one line",
1253                    getLLVMStyleWithColumns(20)));
1254   EXPECT_EQ("// a b c d\n"
1255             "// e f  g\n"
1256             "// h i j k",
1257             format("// a b c d e f  g h i j k", getLLVMStyleWithColumns(10)));
1258   EXPECT_EQ(
1259       "// a b c d\n"
1260       "// e f  g\n"
1261       "// h i j k",
1262       format("\\\n// a b c d e f  g h i j k", getLLVMStyleWithColumns(10)));
1263   EXPECT_EQ("if (true) // A comment that\n"
1264             "          // doesn't fit on\n"
1265             "          // one line",
1266             format("if (true) // A comment that doesn't fit on one line   ",
1267                    getLLVMStyleWithColumns(30)));
1268   EXPECT_EQ("//    Don't_touch_leading_whitespace",
1269             format("//    Don't_touch_leading_whitespace",
1270                    getLLVMStyleWithColumns(20)));
1271   EXPECT_EQ("// Add leading\n"
1272             "// whitespace",
1273             format("//Add leading whitespace", getLLVMStyleWithColumns(20)));
1274   EXPECT_EQ("/// Add leading\n"
1275             "/// whitespace",
1276             format("///Add leading whitespace", getLLVMStyleWithColumns(20)));
1277   EXPECT_EQ("//! Add leading\n"
1278             "//! whitespace",
1279             format("//!Add leading whitespace", getLLVMStyleWithColumns(20)));
1280   EXPECT_EQ("// whitespace", format("//whitespace", getLLVMStyle()));
1281   EXPECT_EQ("// Even if it makes the line exceed the column\n"
1282             "// limit",
1283             format("//Even if it makes the line exceed the column limit",
1284                    getLLVMStyleWithColumns(51)));
1285   EXPECT_EQ("//--But not here", format("//--But not here", getLLVMStyle()));
1286
1287   EXPECT_EQ("// aa bb cc dd",
1288             format("// aa bb             cc dd                   ",
1289                    getLLVMStyleWithColumns(15)));
1290
1291   EXPECT_EQ("// A comment before\n"
1292             "// a macro\n"
1293             "// definition\n"
1294             "#define a b",
1295             format("// A comment before a macro definition\n"
1296                    "#define a b",
1297                    getLLVMStyleWithColumns(20)));
1298   EXPECT_EQ("void ffffff(\n"
1299             "    int aaaaaaaaa,  // wwww\n"
1300             "    int bbbbbbbbbb, // xxxxxxx\n"
1301             "                    // yyyyyyyyyy\n"
1302             "    int c, int d, int e) {}",
1303             format("void ffffff(\n"
1304                    "    int aaaaaaaaa, // wwww\n"
1305                    "    int bbbbbbbbbb, // xxxxxxx yyyyyyyyyy\n"
1306                    "    int c, int d, int e) {}",
1307                    getLLVMStyleWithColumns(40)));
1308   EXPECT_EQ("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1309             format("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1310                    getLLVMStyleWithColumns(20)));
1311   EXPECT_EQ(
1312       "#define XXX // a b c d\n"
1313       "            // e f g h",
1314       format("#define XXX // a b c d e f g h", getLLVMStyleWithColumns(22)));
1315   EXPECT_EQ(
1316       "#define XXX // q w e r\n"
1317       "            // t y u i",
1318       format("#define XXX //q w e r t y u i", getLLVMStyleWithColumns(22)));
1319 }
1320
1321 TEST_F(FormatTest, PreservesHangingIndentInCxxComments) {
1322   EXPECT_EQ("//     A comment\n"
1323             "//     that doesn't\n"
1324             "//     fit on one\n"
1325             "//     line",
1326             format("//     A comment that doesn't fit on one line",
1327                    getLLVMStyleWithColumns(20)));
1328   EXPECT_EQ("///     A comment\n"
1329             "///     that doesn't\n"
1330             "///     fit on one\n"
1331             "///     line",
1332             format("///     A comment that doesn't fit on one line",
1333                    getLLVMStyleWithColumns(20)));
1334 }
1335
1336 TEST_F(FormatTest, DontSplitLineCommentsWithEscapedNewlines) {
1337   EXPECT_EQ("// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1338             "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1339             "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
1340             format("// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1341                    "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
1342                    "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
1343   EXPECT_EQ("int a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1344             "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1345             "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1346             format("int a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1347                    "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1348                    "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1349                    getLLVMStyleWithColumns(50)));
1350   // FIXME: One day we might want to implement adjustment of leading whitespace
1351   // of the consecutive lines in this kind of comment:
1352   EXPECT_EQ("double\n"
1353             "    a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1354             "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1355             "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1356             format("double a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1357                    "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
1358                    "          // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
1359                    getLLVMStyleWithColumns(49)));
1360 }
1361
1362 TEST_F(FormatTest, DontSplitLineCommentsWithPragmas) {
1363   FormatStyle Pragmas = getLLVMStyleWithColumns(30);
1364   Pragmas.CommentPragmas = "^ IWYU pragma:";
1365   EXPECT_EQ(
1366       "// IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb",
1367       format("// IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb", Pragmas));
1368   EXPECT_EQ(
1369       "/* IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb */",
1370       format("/* IWYU pragma: aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb */", Pragmas));
1371 }
1372
1373 TEST_F(FormatTest, PriorityOfCommentBreaking) {
1374   EXPECT_EQ("if (xxx ==\n"
1375             "        yyy && // aaaaaaaaaaaa bbbbbbbbb\n"
1376             "    zzz)\n"
1377             "  q();",
1378             format("if (xxx == yyy && // aaaaaaaaaaaa bbbbbbbbb\n"
1379                    "    zzz) q();",
1380                    getLLVMStyleWithColumns(40)));
1381   EXPECT_EQ("if (xxxxxxxxxx ==\n"
1382             "        yyy && // aaaaaa bbbbbbbb cccc\n"
1383             "    zzz)\n"
1384             "  q();",
1385             format("if (xxxxxxxxxx == yyy && // aaaaaa bbbbbbbb cccc\n"
1386                    "    zzz) q();",
1387                    getLLVMStyleWithColumns(40)));
1388   EXPECT_EQ("if (xxxxxxxxxx &&\n"
1389             "        yyy || // aaaaaa bbbbbbbb cccc\n"
1390             "    zzz)\n"
1391             "  q();",
1392             format("if (xxxxxxxxxx && yyy || // aaaaaa bbbbbbbb cccc\n"
1393                    "    zzz) q();",
1394                    getLLVMStyleWithColumns(40)));
1395   EXPECT_EQ("fffffffff(\n"
1396             "    &xxx, // aaaaaaaaaaaa bbbbbbbbbbb\n"
1397             "    zzz);",
1398             format("fffffffff(&xxx, // aaaaaaaaaaaa bbbbbbbbbbb\n"
1399                    " zzz);",
1400                    getLLVMStyleWithColumns(40)));
1401 }
1402
1403 TEST_F(FormatTest, MultiLineCommentsInDefines) {
1404   EXPECT_EQ("#define A(x) /* \\\n"
1405             "  a comment     \\\n"
1406             "  inside */     \\\n"
1407             "  f();",
1408             format("#define A(x) /* \\\n"
1409                    "  a comment     \\\n"
1410                    "  inside */     \\\n"
1411                    "  f();",
1412                    getLLVMStyleWithColumns(17)));
1413   EXPECT_EQ("#define A(      \\\n"
1414             "    x) /*       \\\n"
1415             "  a comment     \\\n"
1416             "  inside */     \\\n"
1417             "  f();",
1418             format("#define A(      \\\n"
1419                    "    x) /*       \\\n"
1420                    "  a comment     \\\n"
1421                    "  inside */     \\\n"
1422                    "  f();",
1423                    getLLVMStyleWithColumns(17)));
1424 }
1425
1426 TEST_F(FormatTest, ParsesCommentsAdjacentToPPDirectives) {
1427   EXPECT_EQ("namespace {}\n// Test\n#define A",
1428             format("namespace {}\n   // Test\n#define A"));
1429   EXPECT_EQ("namespace {}\n/* Test */\n#define A",
1430             format("namespace {}\n   /* Test */\n#define A"));
1431   EXPECT_EQ("namespace {}\n/* Test */ #define A",
1432             format("namespace {}\n   /* Test */    #define A"));
1433 }
1434
1435 TEST_F(FormatTest, SplitsLongLinesInComments) {
1436   EXPECT_EQ("/* This is a long\n"
1437             " * comment that\n"
1438             " * doesn't\n"
1439             " * fit on one line.\n"
1440             " */",
1441             format("/* "
1442                    "This is a long                                         "
1443                    "comment that "
1444                    "doesn't                                    "
1445                    "fit on one line.  */",
1446                    getLLVMStyleWithColumns(20)));
1447   EXPECT_EQ(
1448       "/* a b c d\n"
1449       " * e f  g\n"
1450       " * h i j k\n"
1451       " */",
1452       format("/* a b c d e f  g h i j k */", getLLVMStyleWithColumns(10)));
1453   EXPECT_EQ(
1454       "/* a b c d\n"
1455       " * e f  g\n"
1456       " * h i j k\n"
1457       " */",
1458       format("\\\n/* a b c d e f  g h i j k */", getLLVMStyleWithColumns(10)));
1459   EXPECT_EQ("/*\n"
1460             "This is a long\n"
1461             "comment that doesn't\n"
1462             "fit on one line.\n"
1463             "*/",
1464             format("/*\n"
1465                    "This is a long                                         "
1466                    "comment that doesn't                                    "
1467                    "fit on one line.                                      \n"
1468                    "*/",
1469                    getLLVMStyleWithColumns(20)));
1470   EXPECT_EQ("/*\n"
1471             " * This is a long\n"
1472             " * comment that\n"
1473             " * doesn't fit on\n"
1474             " * one line.\n"
1475             " */",
1476             format("/*      \n"
1477                    " * This is a long "
1478                    "   comment that     "
1479                    "   doesn't fit on   "
1480                    "   one line.                                            \n"
1481                    " */",
1482                    getLLVMStyleWithColumns(20)));
1483   EXPECT_EQ("/*\n"
1484             " * This_is_a_comment_with_words_that_dont_fit_on_one_line\n"
1485             " * so_it_should_be_broken\n"
1486             " * wherever_a_space_occurs\n"
1487             " */",
1488             format("/*\n"
1489                    " * This_is_a_comment_with_words_that_dont_fit_on_one_line "
1490                    "   so_it_should_be_broken "
1491                    "   wherever_a_space_occurs                             \n"
1492                    " */",
1493                    getLLVMStyleWithColumns(20)));
1494   EXPECT_EQ("/*\n"
1495             " *    This_comment_can_not_be_broken_into_lines\n"
1496             " */",
1497             format("/*\n"
1498                    " *    This_comment_can_not_be_broken_into_lines\n"
1499                    " */",
1500                    getLLVMStyleWithColumns(20)));
1501   EXPECT_EQ("{\n"
1502             "  /*\n"
1503             "  This is another\n"
1504             "  long comment that\n"
1505             "  doesn't fit on one\n"
1506             "  line    1234567890\n"
1507             "  */\n"
1508             "}",
1509             format("{\n"
1510                    "/*\n"
1511                    "This is another     "
1512                    "  long comment that "
1513                    "  doesn't fit on one"
1514                    "  line    1234567890\n"
1515                    "*/\n"
1516                    "}",
1517                    getLLVMStyleWithColumns(20)));
1518   EXPECT_EQ("{\n"
1519             "  /*\n"
1520             "   * This        i s\n"
1521             "   * another comment\n"
1522             "   * t hat  doesn' t\n"
1523             "   * fit on one l i\n"
1524             "   * n e\n"
1525             "   */\n"
1526             "}",
1527             format("{\n"
1528                    "/*\n"
1529                    " * This        i s"
1530                    "   another comment"
1531                    "   t hat  doesn' t"
1532                    "   fit on one l i"
1533                    "   n e\n"
1534                    " */\n"
1535                    "}",
1536                    getLLVMStyleWithColumns(20)));
1537   EXPECT_EQ("/*\n"
1538             " * This is a long\n"
1539             " * comment that\n"
1540             " * doesn't fit on\n"
1541             " * one line\n"
1542             " */",
1543             format("   /*\n"
1544                    "    * This is a long comment that doesn't fit on one line\n"
1545                    "    */",
1546                    getLLVMStyleWithColumns(20)));
1547   EXPECT_EQ("{\n"
1548             "  if (something) /* This is a\n"
1549             "                    long\n"
1550             "                    comment */\n"
1551             "    ;\n"
1552             "}",
1553             format("{\n"
1554                    "  if (something) /* This is a long comment */\n"
1555                    "    ;\n"
1556                    "}",
1557                    getLLVMStyleWithColumns(30)));
1558
1559   EXPECT_EQ("/* A comment before\n"
1560             " * a macro\n"
1561             " * definition */\n"
1562             "#define a b",
1563             format("/* A comment before a macro definition */\n"
1564                    "#define a b",
1565                    getLLVMStyleWithColumns(20)));
1566
1567   EXPECT_EQ("/* some comment\n"
1568             "     *   a comment\n"
1569             "* that we break\n"
1570             " * another comment\n"
1571             "* we have to break\n"
1572             "* a left comment\n"
1573             " */",
1574             format("  /* some comment\n"
1575                    "       *   a comment that we break\n"
1576                    "   * another comment we have to break\n"
1577                    "* a left comment\n"
1578                    "   */",
1579                    getLLVMStyleWithColumns(20)));
1580
1581   EXPECT_EQ("/**\n"
1582             " * multiline block\n"
1583             " * comment\n"
1584             " *\n"
1585             " */",
1586             format("/**\n"
1587                    " * multiline block comment\n"
1588                    " *\n"
1589                    " */",
1590                    getLLVMStyleWithColumns(20)));
1591
1592   EXPECT_EQ("/*\n"
1593             "\n"
1594             "\n"
1595             "    */\n",
1596             format("  /*       \n"
1597                    "      \n"
1598                    "               \n"
1599                    "      */\n"));
1600
1601   EXPECT_EQ("/* a a */",
1602             format("/* a a            */", getLLVMStyleWithColumns(15)));
1603   EXPECT_EQ("/* a a bc  */",
1604             format("/* a a            bc  */", getLLVMStyleWithColumns(15)));
1605   EXPECT_EQ("/* aaa aaa\n"
1606             " * aaaaa */",
1607             format("/* aaa aaa aaaaa       */", getLLVMStyleWithColumns(15)));
1608   EXPECT_EQ("/* aaa aaa\n"
1609             " * aaaaa     */",
1610             format("/* aaa aaa aaaaa     */", getLLVMStyleWithColumns(15)));
1611 }
1612
1613 TEST_F(FormatTest, SplitsLongLinesInCommentsInPreprocessor) {
1614   EXPECT_EQ("#define X          \\\n"
1615             "  /*               \\\n"
1616             "   Test            \\\n"
1617             "   Macro comment   \\\n"
1618             "   with a long     \\\n"
1619             "   line            \\\n"
1620             "   */              \\\n"
1621             "  A + B",
1622             format("#define X \\\n"
1623                    "  /*\n"
1624                    "   Test\n"
1625                    "   Macro comment with a long  line\n"
1626                    "   */ \\\n"
1627                    "  A + B",
1628                    getLLVMStyleWithColumns(20)));
1629   EXPECT_EQ("#define X          \\\n"
1630             "  /* Macro comment \\\n"
1631             "     with a long   \\\n"
1632             "     line */       \\\n"
1633             "  A + B",
1634             format("#define X \\\n"
1635                    "  /* Macro comment with a long\n"
1636                    "     line */ \\\n"
1637                    "  A + B",
1638                    getLLVMStyleWithColumns(20)));
1639   EXPECT_EQ("#define X          \\\n"
1640             "  /* Macro comment \\\n"
1641             "   * with a long   \\\n"
1642             "   * line */       \\\n"
1643             "  A + B",
1644             format("#define X \\\n"
1645                    "  /* Macro comment with a long  line */ \\\n"
1646                    "  A + B",
1647                    getLLVMStyleWithColumns(20)));
1648 }
1649
1650 TEST_F(FormatTest, CommentsInStaticInitializers) {
1651   EXPECT_EQ(
1652       "static SomeType type = {aaaaaaaaaaaaaaaaaaaa, /* comment */\n"
1653       "                        aaaaaaaaaaaaaaaaaaaa /* comment */,\n"
1654       "                        /* comment */ aaaaaaaaaaaaaaaaaaaa,\n"
1655       "                        aaaaaaaaaaaaaaaaaaaa, // comment\n"
1656       "                        aaaaaaaaaaaaaaaaaaaa};",
1657       format("static SomeType type = { aaaaaaaaaaaaaaaaaaaa  ,  /* comment */\n"
1658              "                   aaaaaaaaaaaaaaaaaaaa   /* comment */ ,\n"
1659              "                     /* comment */   aaaaaaaaaaaaaaaaaaaa ,\n"
1660              "              aaaaaaaaaaaaaaaaaaaa ,   // comment\n"
1661              "                  aaaaaaaaaaaaaaaaaaaa };"));
1662   verifyFormat("static SomeType type = {aaaaaaaaaaa, // comment for aa...\n"
1663                "                        bbbbbbbbbbb, ccccccccccc};");
1664   verifyFormat("static SomeType type = {aaaaaaaaaaa,\n"
1665                "                        // comment for bb....\n"
1666                "                        bbbbbbbbbbb, ccccccccccc};");
1667   verifyGoogleFormat(
1668       "static SomeType type = {aaaaaaaaaaa,  // comment for aa...\n"
1669       "                        bbbbbbbbbbb, ccccccccccc};");
1670   verifyGoogleFormat("static SomeType type = {aaaaaaaaaaa,\n"
1671                      "                        // comment for bb....\n"
1672                      "                        bbbbbbbbbbb, ccccccccccc};");
1673
1674   verifyFormat("S s = {{a, b, c},  // Group #1\n"
1675                "       {d, e, f},  // Group #2\n"
1676                "       {g, h, i}}; // Group #3");
1677   verifyFormat("S s = {{// Group #1\n"
1678                "        a, b, c},\n"
1679                "       {// Group #2\n"
1680                "        d, e, f},\n"
1681                "       {// Group #3\n"
1682                "        g, h, i}};");
1683
1684   EXPECT_EQ("S s = {\n"
1685             "    // Some comment\n"
1686             "    a,\n"
1687             "\n"
1688             "    // Comment after empty line\n"
1689             "    b}",
1690             format("S s =    {\n"
1691                    "      // Some comment\n"
1692                    "  a,\n"
1693                    "  \n"
1694                    "     // Comment after empty line\n"
1695                    "      b\n"
1696                    "}"));
1697   EXPECT_EQ("S s = {\n"
1698             "    /* Some comment */\n"
1699             "    a,\n"
1700             "\n"
1701             "    /* Comment after empty line */\n"
1702             "    b}",
1703             format("S s =    {\n"
1704                    "      /* Some comment */\n"
1705                    "  a,\n"
1706                    "  \n"
1707                    "     /* Comment after empty line */\n"
1708                    "      b\n"
1709                    "}"));
1710   verifyFormat("const uint8_t aaaaaaaaaaaaaaaaaaaaaa[0] = {\n"
1711                "    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1712                "    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1713                "    0x00, 0x00, 0x00, 0x00};            // comment\n");
1714 }
1715
1716 TEST_F(FormatTest, IgnoresIf0Contents) {
1717   EXPECT_EQ("#if 0\n"
1718             "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1719             "#endif\n"
1720             "void f() {}",
1721             format("#if 0\n"
1722                    "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1723                    "#endif\n"
1724                    "void f(  ) {  }"));
1725   EXPECT_EQ("#if false\n"
1726             "void f(  ) {  }\n"
1727             "#endif\n"
1728             "void g() {}\n",
1729             format("#if false\n"
1730                    "void f(  ) {  }\n"
1731                    "#endif\n"
1732                    "void g(  ) {  }\n"));
1733   EXPECT_EQ("enum E {\n"
1734             "  One,\n"
1735             "  Two,\n"
1736             "#if 0\n"
1737             "Three,\n"
1738             "      Four,\n"
1739             "#endif\n"
1740             "  Five\n"
1741             "};",
1742             format("enum E {\n"
1743                    "  One,Two,\n"
1744                    "#if 0\n"
1745                    "Three,\n"
1746                    "      Four,\n"
1747                    "#endif\n"
1748                    "  Five};"));
1749   EXPECT_EQ("enum F {\n"
1750             "  One,\n"
1751             "#if 1\n"
1752             "  Two,\n"
1753             "#if 0\n"
1754             "Three,\n"
1755             "      Four,\n"
1756             "#endif\n"
1757             "  Five\n"
1758             "#endif\n"
1759             "};",
1760             format("enum F {\n"
1761                    "One,\n"
1762                    "#if 1\n"
1763                    "Two,\n"
1764                    "#if 0\n"
1765                    "Three,\n"
1766                    "      Four,\n"
1767                    "#endif\n"
1768                    "Five\n"
1769                    "#endif\n"
1770                    "};"));
1771   EXPECT_EQ("enum G {\n"
1772             "  One,\n"
1773             "#if 0\n"
1774             "Two,\n"
1775             "#else\n"
1776             "  Three,\n"
1777             "#endif\n"
1778             "  Four\n"
1779             "};",
1780             format("enum G {\n"
1781                    "One,\n"
1782                    "#if 0\n"
1783                    "Two,\n"
1784                    "#else\n"
1785                    "Three,\n"
1786                    "#endif\n"
1787                    "Four\n"
1788                    "};"));
1789   EXPECT_EQ("enum H {\n"
1790             "  One,\n"
1791             "#if 0\n"
1792             "#ifdef Q\n"
1793             "Two,\n"
1794             "#else\n"
1795             "Three,\n"
1796             "#endif\n"
1797             "#endif\n"
1798             "  Four\n"
1799             "};",
1800             format("enum H {\n"
1801                    "One,\n"
1802                    "#if 0\n"
1803                    "#ifdef Q\n"
1804                    "Two,\n"
1805                    "#else\n"
1806                    "Three,\n"
1807                    "#endif\n"
1808                    "#endif\n"
1809                    "Four\n"
1810                    "};"));
1811   EXPECT_EQ("enum I {\n"
1812             "  One,\n"
1813             "#if /* test */ 0 || 1\n"
1814             "Two,\n"
1815             "Three,\n"
1816             "#endif\n"
1817             "  Four\n"
1818             "};",
1819             format("enum I {\n"
1820                    "One,\n"
1821                    "#if /* test */ 0 || 1\n"
1822                    "Two,\n"
1823                    "Three,\n"
1824                    "#endif\n"
1825                    "Four\n"
1826                    "};"));
1827   EXPECT_EQ("enum J {\n"
1828             "  One,\n"
1829             "#if 0\n"
1830             "#if 0\n"
1831             "Two,\n"
1832             "#else\n"
1833             "Three,\n"
1834             "#endif\n"
1835             "Four,\n"
1836             "#endif\n"
1837             "  Five\n"
1838             "};",
1839             format("enum J {\n"
1840                    "One,\n"
1841                    "#if 0\n"
1842                    "#if 0\n"
1843                    "Two,\n"
1844                    "#else\n"
1845                    "Three,\n"
1846                    "#endif\n"
1847                    "Four,\n"
1848                    "#endif\n"
1849                    "Five\n"
1850                    "};"));
1851 }
1852
1853 //===----------------------------------------------------------------------===//
1854 // Tests for classes, namespaces, etc.
1855 //===----------------------------------------------------------------------===//
1856
1857 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1858   verifyFormat("class A {};");
1859 }
1860
1861 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1862   verifyFormat("class A {\n"
1863                "public:\n"
1864                "public: // comment\n"
1865                "protected:\n"
1866                "private:\n"
1867                "  void f() {}\n"
1868                "};");
1869   verifyGoogleFormat("class A {\n"
1870                      " public:\n"
1871                      " protected:\n"
1872                      " private:\n"
1873                      "  void f() {}\n"
1874                      "};");
1875   verifyFormat("class A {\n"
1876                "public slots:\n"
1877                "  void f1() {}\n"
1878                "public Q_SLOTS:\n"
1879                "  void f2() {}\n"
1880                "protected slots:\n"
1881                "  void f3() {}\n"
1882                "protected Q_SLOTS:\n"
1883                "  void f4() {}\n"
1884                "private slots:\n"
1885                "  void f5() {}\n"
1886                "private Q_SLOTS:\n"
1887                "  void f6() {}\n"
1888                "signals:\n"
1889                "  void g1();\n"
1890                "Q_SIGNALS:\n"
1891                "  void g2();\n"
1892                "};");
1893
1894   // Don't interpret 'signals' the wrong way.
1895   verifyFormat("signals.set();");
1896   verifyFormat("for (Signals signals : f()) {\n}");
1897   verifyFormat("{\n"
1898                "  signals.set(); // This needs indentation.\n"
1899                "}");
1900 }
1901
1902 TEST_F(FormatTest, SeparatesLogicalBlocks) {
1903   EXPECT_EQ("class A {\n"
1904             "public:\n"
1905             "  void f();\n"
1906             "\n"
1907             "private:\n"
1908             "  void g() {}\n"
1909             "  // test\n"
1910             "protected:\n"
1911             "  int h;\n"
1912             "};",
1913             format("class A {\n"
1914                    "public:\n"
1915                    "void f();\n"
1916                    "private:\n"
1917                    "void g() {}\n"
1918                    "// test\n"
1919                    "protected:\n"
1920                    "int h;\n"
1921                    "};"));
1922   EXPECT_EQ("class A {\n"
1923             "protected:\n"
1924             "public:\n"
1925             "  void f();\n"
1926             "};",
1927             format("class A {\n"
1928                    "protected:\n"
1929                    "\n"
1930                    "public:\n"
1931                    "\n"
1932                    "  void f();\n"
1933                    "};"));
1934
1935   // Even ensure proper spacing inside macros.
1936   EXPECT_EQ("#define B     \\\n"
1937             "  class A {   \\\n"
1938             "   protected: \\\n"
1939             "   public:    \\\n"
1940             "    void f(); \\\n"
1941             "  };",
1942             format("#define B     \\\n"
1943                    "  class A {   \\\n"
1944                    "   protected: \\\n"
1945                    "              \\\n"
1946                    "   public:    \\\n"
1947                    "              \\\n"
1948                    "    void f(); \\\n"
1949                    "  };",
1950                    getGoogleStyle()));
1951   // But don't remove empty lines after macros ending in access specifiers.
1952   EXPECT_EQ("#define A private:\n"
1953             "\n"
1954             "int i;",
1955             format("#define A         private:\n"
1956                    "\n"
1957                    "int              i;"));
1958 }
1959
1960 TEST_F(FormatTest, FormatsClasses) {
1961   verifyFormat("class A : public B {};");
1962   verifyFormat("class A : public ::B {};");
1963
1964   verifyFormat(
1965       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1966       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1967   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
1968                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1969                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1970   verifyFormat(
1971       "class A : public B, public C, public D, public E, public F {};");
1972   verifyFormat("class AAAAAAAAAAAA : public B,\n"
1973                "                     public C,\n"
1974                "                     public D,\n"
1975                "                     public E,\n"
1976                "                     public F,\n"
1977                "                     public G {};");
1978
1979   verifyFormat("class\n"
1980                "    ReallyReallyLongClassName {\n"
1981                "  int i;\n"
1982                "};",
1983                getLLVMStyleWithColumns(32));
1984   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
1985                "                           aaaaaaaaaaaaaaaa> {};");
1986   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
1987                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
1988                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
1989   verifyFormat("template <class R, class C>\n"
1990                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
1991                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
1992   verifyFormat("class ::A::B {};");
1993 }
1994
1995 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
1996   verifyFormat("class A {\n} a, b;");
1997   verifyFormat("struct A {\n} a, b;");
1998   verifyFormat("union A {\n} a;");
1999 }
2000
2001 TEST_F(FormatTest, FormatsEnum) {
2002   verifyFormat("enum {\n"
2003                "  Zero,\n"
2004                "  One = 1,\n"
2005                "  Two = One + 1,\n"
2006                "  Three = (One + Two),\n"
2007                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2008                "  Five = (One, Two, Three, Four, 5)\n"
2009                "};");
2010   verifyGoogleFormat("enum {\n"
2011                      "  Zero,\n"
2012                      "  One = 1,\n"
2013                      "  Two = One + 1,\n"
2014                      "  Three = (One + Two),\n"
2015                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2016                      "  Five = (One, Two, Three, Four, 5)\n"
2017                      "};");
2018   verifyFormat("enum Enum {};");
2019   verifyFormat("enum {};");
2020   verifyFormat("enum X E {} d;");
2021   verifyFormat("enum __attribute__((...)) E {} d;");
2022   verifyFormat("enum __declspec__((...)) E {} d;");
2023   verifyFormat("enum {\n"
2024                "  Bar = Foo<int, int>::value\n"
2025                "};",
2026                getLLVMStyleWithColumns(30));
2027
2028   verifyFormat("enum ShortEnum { A, B, C };");
2029   verifyGoogleFormat("enum ShortEnum { A, B, C };");
2030
2031   EXPECT_EQ("enum KeepEmptyLines {\n"
2032             "  ONE,\n"
2033             "\n"
2034             "  TWO,\n"
2035             "\n"
2036             "  THREE\n"
2037             "}",
2038             format("enum KeepEmptyLines {\n"
2039                    "  ONE,\n"
2040                    "\n"
2041                    "  TWO,\n"
2042                    "\n"
2043                    "\n"
2044                    "  THREE\n"
2045                    "}"));
2046   verifyFormat("enum E { // comment\n"
2047                "  ONE,\n"
2048                "  TWO\n"
2049                "};\n"
2050                "int i;");
2051   // Not enums.
2052   verifyFormat("enum X f() {\n"
2053                "  a();\n"
2054                "  return 42;\n"
2055                "}");
2056   verifyFormat("enum X Type::f() {\n"
2057                "  a();\n"
2058                "  return 42;\n"
2059                "}");
2060   verifyFormat("enum ::X f() {\n"
2061                "  a();\n"
2062                "  return 42;\n"
2063                "}");
2064   verifyFormat("enum ns::X f() {\n"
2065                "  a();\n"
2066                "  return 42;\n"
2067                "}");
2068 }
2069
2070 TEST_F(FormatTest, FormatsEnumsWithErrors) {
2071   verifyFormat("enum Type {\n"
2072                "  One = 0; // These semicolons should be commas.\n"
2073                "  Two = 1;\n"
2074                "};");
2075   verifyFormat("namespace n {\n"
2076                "enum Type {\n"
2077                "  One,\n"
2078                "  Two, // missing };\n"
2079                "  int i;\n"
2080                "}\n"
2081                "void g() {}");
2082 }
2083
2084 TEST_F(FormatTest, FormatsEnumStruct) {
2085   verifyFormat("enum struct {\n"
2086                "  Zero,\n"
2087                "  One = 1,\n"
2088                "  Two = One + 1,\n"
2089                "  Three = (One + Two),\n"
2090                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2091                "  Five = (One, Two, Three, Four, 5)\n"
2092                "};");
2093   verifyFormat("enum struct Enum {};");
2094   verifyFormat("enum struct {};");
2095   verifyFormat("enum struct X E {} d;");
2096   verifyFormat("enum struct __attribute__((...)) E {} d;");
2097   verifyFormat("enum struct __declspec__((...)) E {} d;");
2098   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
2099 }
2100
2101 TEST_F(FormatTest, FormatsEnumClass) {
2102   verifyFormat("enum class {\n"
2103                "  Zero,\n"
2104                "  One = 1,\n"
2105                "  Two = One + 1,\n"
2106                "  Three = (One + Two),\n"
2107                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2108                "  Five = (One, Two, Three, Four, 5)\n"
2109                "};");
2110   verifyFormat("enum class Enum {};");
2111   verifyFormat("enum class {};");
2112   verifyFormat("enum class X E {} d;");
2113   verifyFormat("enum class __attribute__((...)) E {} d;");
2114   verifyFormat("enum class __declspec__((...)) E {} d;");
2115   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
2116 }
2117
2118 TEST_F(FormatTest, FormatsEnumTypes) {
2119   verifyFormat("enum X : int {\n"
2120                "  A, // Force multiple lines.\n"
2121                "  B\n"
2122                "};");
2123   verifyFormat("enum X : int { A, B };");
2124   verifyFormat("enum X : std::uint32_t { A, B };");
2125 }
2126
2127 TEST_F(FormatTest, FormatsNSEnums) {
2128   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
2129   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
2130                      "  // Information about someDecentlyLongValue.\n"
2131                      "  someDecentlyLongValue,\n"
2132                      "  // Information about anotherDecentlyLongValue.\n"
2133                      "  anotherDecentlyLongValue,\n"
2134                      "  // Information about aThirdDecentlyLongValue.\n"
2135                      "  aThirdDecentlyLongValue\n"
2136                      "};");
2137   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
2138                      "  a = 1,\n"
2139                      "  b = 2,\n"
2140                      "  c = 3,\n"
2141                      "};");
2142   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
2143                      "  a = 1,\n"
2144                      "  b = 2,\n"
2145                      "  c = 3,\n"
2146                      "};");
2147   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
2148                      "  a = 1,\n"
2149                      "  b = 2,\n"
2150                      "  c = 3,\n"
2151                      "};");
2152 }
2153
2154 TEST_F(FormatTest, FormatsBitfields) {
2155   verifyFormat("struct Bitfields {\n"
2156                "  unsigned sClass : 8;\n"
2157                "  unsigned ValueKind : 2;\n"
2158                "};");
2159   verifyFormat("struct A {\n"
2160                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
2161                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
2162                "};");
2163   verifyFormat("struct MyStruct {\n"
2164                "  uchar data;\n"
2165                "  uchar : 8;\n"
2166                "  uchar : 8;\n"
2167                "  uchar other;\n"
2168                "};");
2169 }
2170
2171 TEST_F(FormatTest, FormatsNamespaces) {
2172   verifyFormat("namespace some_namespace {\n"
2173                "class A {};\n"
2174                "void f() { f(); }\n"
2175                "}");
2176   verifyFormat("namespace {\n"
2177                "class A {};\n"
2178                "void f() { f(); }\n"
2179                "}");
2180   verifyFormat("inline namespace X {\n"
2181                "class A {};\n"
2182                "void f() { f(); }\n"
2183                "}");
2184   verifyFormat("using namespace some_namespace;\n"
2185                "class A {};\n"
2186                "void f() { f(); }");
2187
2188   // This code is more common than we thought; if we
2189   // layout this correctly the semicolon will go into
2190   // its own line, which is undesirable.
2191   verifyFormat("namespace {};");
2192   verifyFormat("namespace {\n"
2193                "class A {};\n"
2194                "};");
2195
2196   verifyFormat("namespace {\n"
2197                "int SomeVariable = 0; // comment\n"
2198                "} // namespace");
2199   EXPECT_EQ("#ifndef HEADER_GUARD\n"
2200             "#define HEADER_GUARD\n"
2201             "namespace my_namespace {\n"
2202             "int i;\n"
2203             "} // my_namespace\n"
2204             "#endif // HEADER_GUARD",
2205             format("#ifndef HEADER_GUARD\n"
2206                    " #define HEADER_GUARD\n"
2207                    "   namespace my_namespace {\n"
2208                    "int i;\n"
2209                    "}    // my_namespace\n"
2210                    "#endif    // HEADER_GUARD"));
2211
2212   EXPECT_EQ("namespace A::B {\n"
2213             "class C {};\n"
2214             "}",
2215             format("namespace A::B {\n"
2216                    "class C {};\n"
2217                    "}"));
2218
2219   FormatStyle Style = getLLVMStyle();
2220   Style.NamespaceIndentation = FormatStyle::NI_All;
2221   EXPECT_EQ("namespace out {\n"
2222             "  int i;\n"
2223             "  namespace in {\n"
2224             "    int i;\n"
2225             "  } // namespace\n"
2226             "} // namespace",
2227             format("namespace out {\n"
2228                    "int i;\n"
2229                    "namespace in {\n"
2230                    "int i;\n"
2231                    "} // namespace\n"
2232                    "} // namespace",
2233                    Style));
2234
2235   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2236   EXPECT_EQ("namespace out {\n"
2237             "int i;\n"
2238             "namespace in {\n"
2239             "  int i;\n"
2240             "} // namespace\n"
2241             "} // namespace",
2242             format("namespace out {\n"
2243                    "int i;\n"
2244                    "namespace in {\n"
2245                    "int i;\n"
2246                    "} // namespace\n"
2247                    "} // namespace",
2248                    Style));
2249 }
2250
2251 TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
2252
2253 TEST_F(FormatTest, FormatsInlineASM) {
2254   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
2255   verifyFormat("asm(\"nop\" ::: \"memory\");");
2256   verifyFormat(
2257       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
2258       "    \"cpuid\\n\\t\"\n"
2259       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
2260       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
2261       "    : \"a\"(value));");
2262   EXPECT_EQ(
2263       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
2264       "  __asm {\n"
2265       "        mov     edx,[that] // vtable in edx\n"
2266       "        mov     eax,methodIndex\n"
2267       "        call    [edx][eax*4] // stdcall\n"
2268       "  }\n"
2269       "}",
2270       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
2271              "    __asm {\n"
2272              "        mov     edx,[that] // vtable in edx\n"
2273              "        mov     eax,methodIndex\n"
2274              "        call    [edx][eax*4] // stdcall\n"
2275              "    }\n"
2276              "}"));
2277   EXPECT_EQ("_asm {\n"
2278             "  xor eax, eax;\n"
2279             "  cpuid;\n"
2280             "}",
2281             format("_asm {\n"
2282                    "  xor eax, eax;\n"
2283                    "  cpuid;\n"
2284                    "}"));
2285   verifyFormat("void function() {\n"
2286                "  // comment\n"
2287                "  asm(\"\");\n"
2288                "}");
2289   EXPECT_EQ("__asm {\n"
2290             "}\n"
2291             "int i;",
2292             format("__asm   {\n"
2293                    "}\n"
2294                    "int   i;"));
2295 }
2296
2297 TEST_F(FormatTest, FormatTryCatch) {
2298   verifyFormat("try {\n"
2299                "  throw a * b;\n"
2300                "} catch (int a) {\n"
2301                "  // Do nothing.\n"
2302                "} catch (...) {\n"
2303                "  exit(42);\n"
2304                "}");
2305
2306   // Function-level try statements.
2307   verifyFormat("int f() try { return 4; } catch (...) {\n"
2308                "  return 5;\n"
2309                "}");
2310   verifyFormat("class A {\n"
2311                "  int a;\n"
2312                "  A() try : a(0) {\n"
2313                "  } catch (...) {\n"
2314                "    throw;\n"
2315                "  }\n"
2316                "};\n");
2317
2318   // Incomplete try-catch blocks.
2319   verifyIncompleteFormat("try {} catch (");
2320 }
2321
2322 TEST_F(FormatTest, FormatSEHTryCatch) {
2323   verifyFormat("__try {\n"
2324                "  int a = b * c;\n"
2325                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
2326                "  // Do nothing.\n"
2327                "}");
2328
2329   verifyFormat("__try {\n"
2330                "  int a = b * c;\n"
2331                "} __finally {\n"
2332                "  // Do nothing.\n"
2333                "}");
2334
2335   verifyFormat("DEBUG({\n"
2336                "  __try {\n"
2337                "  } __finally {\n"
2338                "  }\n"
2339                "});\n");
2340 }
2341
2342 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
2343   verifyFormat("try {\n"
2344                "  f();\n"
2345                "} catch {\n"
2346                "  g();\n"
2347                "}");
2348   verifyFormat("try {\n"
2349                "  f();\n"
2350                "} catch (A a) MACRO(x) {\n"
2351                "  g();\n"
2352                "} catch (B b) MACRO(x) {\n"
2353                "  g();\n"
2354                "}");
2355 }
2356
2357 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
2358   FormatStyle Style = getLLVMStyle();
2359   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
2360                           FormatStyle::BS_WebKit}) {
2361     Style.BreakBeforeBraces = BraceStyle;
2362     verifyFormat("try {\n"
2363                  "  // something\n"
2364                  "} catch (...) {\n"
2365                  "  // something\n"
2366                  "}",
2367                  Style);
2368   }
2369   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
2370   verifyFormat("try {\n"
2371                "  // something\n"
2372                "}\n"
2373                "catch (...) {\n"
2374                "  // something\n"
2375                "}",
2376                Style);
2377   verifyFormat("__try {\n"
2378                "  // something\n"
2379                "}\n"
2380                "__finally {\n"
2381                "  // something\n"
2382                "}",
2383                Style);
2384   verifyFormat("@try {\n"
2385                "  // something\n"
2386                "}\n"
2387                "@finally {\n"
2388                "  // something\n"
2389                "}",
2390                Style);
2391   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
2392   verifyFormat("try\n"
2393                "{\n"
2394                "  // something\n"
2395                "}\n"
2396                "catch (...)\n"
2397                "{\n"
2398                "  // something\n"
2399                "}",
2400                Style);
2401   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2402   verifyFormat("try\n"
2403                "  {\n"
2404                "    // something\n"
2405                "  }\n"
2406                "catch (...)\n"
2407                "  {\n"
2408                "    // something\n"
2409                "  }",
2410                Style);
2411   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2412   Style.BraceWrapping.BeforeCatch = true;
2413   verifyFormat("try {\n"
2414                "  // something\n"
2415                "}\n"
2416                "catch (...) {\n"
2417                "  // something\n"
2418                "}",
2419                Style);
2420 }
2421
2422 TEST_F(FormatTest, FormatObjCTryCatch) {
2423   verifyFormat("@try {\n"
2424                "  f();\n"
2425                "} @catch (NSException e) {\n"
2426                "  @throw;\n"
2427                "} @finally {\n"
2428                "  exit(42);\n"
2429                "}");
2430   verifyFormat("DEBUG({\n"
2431                "  @try {\n"
2432                "  } @finally {\n"
2433                "  }\n"
2434                "});\n");
2435 }
2436
2437 TEST_F(FormatTest, FormatObjCAutoreleasepool) {
2438   FormatStyle Style = getLLVMStyle();
2439   verifyFormat("@autoreleasepool {\n"
2440                "  f();\n"
2441                "}\n"
2442                "@autoreleasepool {\n"
2443                "  f();\n"
2444                "}\n",
2445                Style);
2446   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
2447   verifyFormat("@autoreleasepool\n"
2448                "{\n"
2449                "  f();\n"
2450                "}\n"
2451                "@autoreleasepool\n"
2452                "{\n"
2453                "  f();\n"
2454                "}\n",
2455                Style);
2456 }
2457
2458 TEST_F(FormatTest, StaticInitializers) {
2459   verifyFormat("static SomeClass SC = {1, 'a'};");
2460
2461   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
2462                "    100000000, "
2463                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
2464
2465   // Here, everything other than the "}" would fit on a line.
2466   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
2467                "    10000000000000000000000000};");
2468   EXPECT_EQ("S s = {a,\n"
2469             "\n"
2470             "       b};",
2471             format("S s = {\n"
2472                    "  a,\n"
2473                    "\n"
2474                    "  b\n"
2475                    "};"));
2476
2477   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
2478   // line. However, the formatting looks a bit off and this probably doesn't
2479   // happen often in practice.
2480   verifyFormat("static int Variable[1] = {\n"
2481                "    {1000000000000000000000000000000000000}};",
2482                getLLVMStyleWithColumns(40));
2483 }
2484
2485 TEST_F(FormatTest, DesignatedInitializers) {
2486   verifyFormat("const struct A a = {.a = 1, .b = 2};");
2487   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
2488                "                    .bbbbbbbbbb = 2,\n"
2489                "                    .cccccccccc = 3,\n"
2490                "                    .dddddddddd = 4,\n"
2491                "                    .eeeeeeeeee = 5};");
2492   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2493                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
2494                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
2495                "    .ccccccccccccccccccccccccccc = 3,\n"
2496                "    .ddddddddddddddddddddddddddd = 4,\n"
2497                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
2498
2499   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
2500 }
2501
2502 TEST_F(FormatTest, NestedStaticInitializers) {
2503   verifyFormat("static A x = {{{}}};\n");
2504   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
2505                "               {init1, init2, init3, init4}}};",
2506                getLLVMStyleWithColumns(50));
2507
2508   verifyFormat("somes Status::global_reps[3] = {\n"
2509                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2510                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2511                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
2512                getLLVMStyleWithColumns(60));
2513   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
2514                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2515                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2516                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
2517   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
2518                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
2519                "rect.fTop}};");
2520
2521   verifyFormat(
2522       "SomeArrayOfSomeType a = {\n"
2523       "    {{1, 2, 3},\n"
2524       "     {1, 2, 3},\n"
2525       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
2526       "      333333333333333333333333333333},\n"
2527       "     {1, 2, 3},\n"
2528       "     {1, 2, 3}}};");
2529   verifyFormat(
2530       "SomeArrayOfSomeType a = {\n"
2531       "    {{1, 2, 3}},\n"
2532       "    {{1, 2, 3}},\n"
2533       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
2534       "      333333333333333333333333333333}},\n"
2535       "    {{1, 2, 3}},\n"
2536       "    {{1, 2, 3}}};");
2537
2538   verifyFormat("struct {\n"
2539                "  unsigned bit;\n"
2540                "  const char *const name;\n"
2541                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
2542                "                 {kOsWin, \"Windows\"},\n"
2543                "                 {kOsLinux, \"Linux\"},\n"
2544                "                 {kOsCrOS, \"Chrome OS\"}};");
2545   verifyFormat("struct {\n"
2546                "  unsigned bit;\n"
2547                "  const char *const name;\n"
2548                "} kBitsToOs[] = {\n"
2549                "    {kOsMac, \"Mac\"},\n"
2550                "    {kOsWin, \"Windows\"},\n"
2551                "    {kOsLinux, \"Linux\"},\n"
2552                "    {kOsCrOS, \"Chrome OS\"},\n"
2553                "};");
2554 }
2555
2556 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
2557   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
2558                "                      \\\n"
2559                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
2560 }
2561
2562 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
2563   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
2564                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
2565
2566   // Do break defaulted and deleted functions.
2567   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
2568                "    default;",
2569                getLLVMStyleWithColumns(40));
2570   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
2571                "    delete;",
2572                getLLVMStyleWithColumns(40));
2573 }
2574
2575 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
2576   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
2577                getLLVMStyleWithColumns(40));
2578   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
2579                getLLVMStyleWithColumns(40));
2580   EXPECT_EQ("#define Q                              \\\n"
2581             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
2582             "  \"aaaaaaaa.cpp\"",
2583             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
2584                    getLLVMStyleWithColumns(40)));
2585 }
2586
2587 TEST_F(FormatTest, UnderstandsLinePPDirective) {
2588   EXPECT_EQ("# 123 \"A string literal\"",
2589             format("   #     123    \"A string literal\""));
2590 }
2591
2592 TEST_F(FormatTest, LayoutUnknownPPDirective) {
2593   EXPECT_EQ("#;", format("#;"));
2594   verifyFormat("#\n;\n;\n;");
2595 }
2596
2597 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
2598   EXPECT_EQ("#line 42 \"test\"\n",
2599             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
2600   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
2601                                     getLLVMStyleWithColumns(12)));
2602 }
2603
2604 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
2605   EXPECT_EQ("#line 42 \"test\"",
2606             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
2607   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
2608 }
2609
2610 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
2611   verifyFormat("#define A \\x20");
2612   verifyFormat("#define A \\ x20");
2613   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
2614   verifyFormat("#define A ''");
2615   verifyFormat("#define A ''qqq");
2616   verifyFormat("#define A `qqq");
2617   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
2618   EXPECT_EQ("const char *c = STRINGIFY(\n"
2619             "\\na : b);",
2620             format("const char * c = STRINGIFY(\n"
2621                    "\\na : b);"));
2622
2623   verifyFormat("a\r\\");
2624   verifyFormat("a\v\\");
2625   verifyFormat("a\f\\");
2626 }
2627
2628 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
2629   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
2630   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
2631   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
2632   // FIXME: We never break before the macro name.
2633   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
2634
2635   verifyFormat("#define A A\n#define A A");
2636   verifyFormat("#define A(X) A\n#define A A");
2637
2638   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
2639   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
2640 }
2641
2642 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
2643   EXPECT_EQ("// somecomment\n"
2644             "#include \"a.h\"\n"
2645             "#define A(  \\\n"
2646             "    A, B)\n"
2647             "#include \"b.h\"\n"
2648             "// somecomment\n",
2649             format("  // somecomment\n"
2650                    "  #include \"a.h\"\n"
2651                    "#define A(A,\\\n"
2652                    "    B)\n"
2653                    "    #include \"b.h\"\n"
2654                    " // somecomment\n",
2655                    getLLVMStyleWithColumns(13)));
2656 }
2657
2658 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
2659
2660 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
2661   EXPECT_EQ("#define A    \\\n"
2662             "  c;         \\\n"
2663             "  e;\n"
2664             "f;",
2665             format("#define A c; e;\n"
2666                    "f;",
2667                    getLLVMStyleWithColumns(14)));
2668 }
2669
2670 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
2671
2672 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
2673   EXPECT_EQ("int x,\n"
2674             "#define A\n"
2675             "    y;",
2676             format("int x,\n#define A\ny;"));
2677 }
2678
2679 TEST_F(FormatTest, HashInMacroDefinition) {
2680   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
2681   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
2682   verifyFormat("#define A  \\\n"
2683                "  {        \\\n"
2684                "    f(#c); \\\n"
2685                "  }",
2686                getLLVMStyleWithColumns(11));
2687
2688   verifyFormat("#define A(X)         \\\n"
2689                "  void function##X()",
2690                getLLVMStyleWithColumns(22));
2691
2692   verifyFormat("#define A(a, b, c)   \\\n"
2693                "  void a##b##c()",
2694                getLLVMStyleWithColumns(22));
2695
2696   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
2697 }
2698
2699 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
2700   EXPECT_EQ("#define A (x)", format("#define A (x)"));
2701   EXPECT_EQ("#define A(x)", format("#define A(x)"));
2702 }
2703
2704 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
2705   EXPECT_EQ("#define A b;", format("#define A \\\n"
2706                                    "          \\\n"
2707                                    "  b;",
2708                                    getLLVMStyleWithColumns(25)));
2709   EXPECT_EQ("#define A \\\n"
2710             "          \\\n"
2711             "  a;      \\\n"
2712             "  b;",
2713             format("#define A \\\n"
2714                    "          \\\n"
2715                    "  a;      \\\n"
2716                    "  b;",
2717                    getLLVMStyleWithColumns(11)));
2718   EXPECT_EQ("#define A \\\n"
2719             "  a;      \\\n"
2720             "          \\\n"
2721             "  b;",
2722             format("#define A \\\n"
2723                    "  a;      \\\n"
2724                    "          \\\n"
2725                    "  b;",
2726                    getLLVMStyleWithColumns(11)));
2727 }
2728
2729 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
2730   verifyIncompleteFormat("#define A :");
2731   verifyFormat("#define SOMECASES  \\\n"
2732                "  case 1:          \\\n"
2733                "  case 2\n",
2734                getLLVMStyleWithColumns(20));
2735   verifyFormat("#define A template <typename T>");
2736   verifyIncompleteFormat("#define STR(x) #x\n"
2737                          "f(STR(this_is_a_string_literal{));");
2738   verifyFormat("#pragma omp threadprivate( \\\n"
2739                "    y)), // expected-warning",
2740                getLLVMStyleWithColumns(28));
2741   verifyFormat("#d, = };");
2742   verifyFormat("#if \"a");
2743   verifyIncompleteFormat("({\n"
2744                          "#define b     \\\n"
2745                          "  }           \\\n"
2746                          "  a\n"
2747                          "a",
2748                          getLLVMStyleWithColumns(15));
2749   verifyFormat("#define A     \\\n"
2750                "  {           \\\n"
2751                "    {\n"
2752                "#define B     \\\n"
2753                "  }           \\\n"
2754                "  }",
2755                getLLVMStyleWithColumns(15));
2756   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
2757   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
2758   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
2759   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
2760 }
2761
2762 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
2763   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
2764   EXPECT_EQ("class A : public QObject {\n"
2765             "  Q_OBJECT\n"
2766             "\n"
2767             "  A() {}\n"
2768             "};",
2769             format("class A  :  public QObject {\n"
2770                    "     Q_OBJECT\n"
2771                    "\n"
2772                    "  A() {\n}\n"
2773                    "}  ;"));
2774   EXPECT_EQ("MACRO\n"
2775             "/*static*/ int i;",
2776             format("MACRO\n"
2777                    " /*static*/ int   i;"));
2778   EXPECT_EQ("SOME_MACRO\n"
2779             "namespace {\n"
2780             "void f();\n"
2781             "}",
2782             format("SOME_MACRO\n"
2783                    "  namespace    {\n"
2784                    "void   f(  );\n"
2785                    "}"));
2786   // Only if the identifier contains at least 5 characters.
2787   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
2788   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
2789   // Only if everything is upper case.
2790   EXPECT_EQ("class A : public QObject {\n"
2791             "  Q_Object A() {}\n"
2792             "};",
2793             format("class A  :  public QObject {\n"
2794                    "     Q_Object\n"
2795                    "  A() {\n}\n"
2796                    "}  ;"));
2797
2798   // Only if the next line can actually start an unwrapped line.
2799   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
2800             format("SOME_WEIRD_LOG_MACRO\n"
2801                    "<< SomeThing;"));
2802
2803   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
2804                "(n, buffers))\n",
2805                getChromiumStyle(FormatStyle::LK_Cpp));
2806 }
2807
2808 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
2809   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
2810             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
2811             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
2812             "class X {};\n"
2813             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
2814             "int *createScopDetectionPass() { return 0; }",
2815             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
2816                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
2817                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
2818                    "  class X {};\n"
2819                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
2820                    "  int *createScopDetectionPass() { return 0; }"));
2821   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
2822   // braces, so that inner block is indented one level more.
2823   EXPECT_EQ("int q() {\n"
2824             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
2825             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
2826             "  IPC_END_MESSAGE_MAP()\n"
2827             "}",
2828             format("int q() {\n"
2829                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
2830                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
2831                    "  IPC_END_MESSAGE_MAP()\n"
2832                    "}"));
2833
2834   // Same inside macros.
2835   EXPECT_EQ("#define LIST(L) \\\n"
2836             "  L(A)          \\\n"
2837             "  L(B)          \\\n"
2838             "  L(C)",
2839             format("#define LIST(L) \\\n"
2840                    "  L(A) \\\n"
2841                    "  L(B) \\\n"
2842                    "  L(C)",
2843                    getGoogleStyle()));
2844
2845   // These must not be recognized as macros.
2846   EXPECT_EQ("int q() {\n"
2847             "  f(x);\n"
2848             "  f(x) {}\n"
2849             "  f(x)->g();\n"
2850             "  f(x)->*g();\n"
2851             "  f(x).g();\n"
2852             "  f(x) = x;\n"
2853             "  f(x) += x;\n"
2854             "  f(x) -= x;\n"
2855             "  f(x) *= x;\n"
2856             "  f(x) /= x;\n"
2857             "  f(x) %= x;\n"
2858             "  f(x) &= x;\n"
2859             "  f(x) |= x;\n"
2860             "  f(x) ^= x;\n"
2861             "  f(x) >>= x;\n"
2862             "  f(x) <<= x;\n"
2863             "  f(x)[y].z();\n"
2864             "  LOG(INFO) << x;\n"
2865             "  ifstream(x) >> x;\n"
2866             "}\n",
2867             format("int q() {\n"
2868                    "  f(x)\n;\n"
2869                    "  f(x)\n {}\n"
2870                    "  f(x)\n->g();\n"
2871                    "  f(x)\n->*g();\n"
2872                    "  f(x)\n.g();\n"
2873                    "  f(x)\n = x;\n"
2874                    "  f(x)\n += x;\n"
2875                    "  f(x)\n -= x;\n"
2876                    "  f(x)\n *= x;\n"
2877                    "  f(x)\n /= x;\n"
2878                    "  f(x)\n %= x;\n"
2879                    "  f(x)\n &= x;\n"
2880                    "  f(x)\n |= x;\n"
2881                    "  f(x)\n ^= x;\n"
2882                    "  f(x)\n >>= x;\n"
2883                    "  f(x)\n <<= x;\n"
2884                    "  f(x)\n[y].z();\n"
2885                    "  LOG(INFO)\n << x;\n"
2886                    "  ifstream(x)\n >> x;\n"
2887                    "}\n"));
2888   EXPECT_EQ("int q() {\n"
2889             "  F(x)\n"
2890             "  if (1) {\n"
2891             "  }\n"
2892             "  F(x)\n"
2893             "  while (1) {\n"
2894             "  }\n"
2895             "  F(x)\n"
2896             "  G(x);\n"
2897             "  F(x)\n"
2898             "  try {\n"
2899             "    Q();\n"
2900             "  } catch (...) {\n"
2901             "  }\n"
2902             "}\n",
2903             format("int q() {\n"
2904                    "F(x)\n"
2905                    "if (1) {}\n"
2906                    "F(x)\n"
2907                    "while (1) {}\n"
2908                    "F(x)\n"
2909                    "G(x);\n"
2910                    "F(x)\n"
2911                    "try { Q(); } catch (...) {}\n"
2912                    "}\n"));
2913   EXPECT_EQ("class A {\n"
2914             "  A() : t(0) {}\n"
2915             "  A(int i) noexcept() : {}\n"
2916             "  A(X x)\n" // FIXME: function-level try blocks are broken.
2917             "  try : t(0) {\n"
2918             "  } catch (...) {\n"
2919             "  }\n"
2920             "};",
2921             format("class A {\n"
2922                    "  A()\n : t(0) {}\n"
2923                    "  A(int i)\n noexcept() : {}\n"
2924                    "  A(X x)\n"
2925                    "  try : t(0) {} catch (...) {}\n"
2926                    "};"));
2927   EXPECT_EQ("class SomeClass {\n"
2928             "public:\n"
2929             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2930             "};",
2931             format("class SomeClass {\n"
2932                    "public:\n"
2933                    "  SomeClass()\n"
2934                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2935                    "};"));
2936   EXPECT_EQ("class SomeClass {\n"
2937             "public:\n"
2938             "  SomeClass()\n"
2939             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2940             "};",
2941             format("class SomeClass {\n"
2942                    "public:\n"
2943                    "  SomeClass()\n"
2944                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
2945                    "};",
2946                    getLLVMStyleWithColumns(40)));
2947
2948   verifyFormat("MACRO(>)");
2949 }
2950
2951 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
2952   verifyFormat("#define A \\\n"
2953                "  f({     \\\n"
2954                "    g();  \\\n"
2955                "  });",
2956                getLLVMStyleWithColumns(11));
2957 }
2958
2959 TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
2960   EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
2961 }
2962
2963 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
2964   verifyFormat("{\n  { a #c; }\n}");
2965 }
2966
2967 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
2968   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
2969             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
2970   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
2971             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
2972 }
2973
2974 TEST_F(FormatTest, EscapedNewlines) {
2975   EXPECT_EQ(
2976       "#define A \\\n  int i;  \\\n  int j;",
2977       format("#define A \\\nint i;\\\n  int j;", getLLVMStyleWithColumns(11)));
2978   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
2979   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
2980   EXPECT_EQ("/* \\  \\  \\\n*/", format("\\\n/* \\  \\  \\\n*/"));
2981   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
2982 }
2983
2984 TEST_F(FormatTest, DontCrashOnBlockComments) {
2985   EXPECT_EQ(
2986       "int xxxxxxxxx; /* "
2987       "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy\n"
2988       "zzzzzz\n"
2989       "0*/",
2990       format("int xxxxxxxxx;                          /* "
2991              "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy zzzzzz\n"
2992              "0*/"));
2993 }
2994
2995 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
2996   verifyFormat("#define A \\\n"
2997                "  int v(  \\\n"
2998                "      a); \\\n"
2999                "  int i;",
3000                getLLVMStyleWithColumns(11));
3001 }
3002
3003 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
3004   EXPECT_EQ(
3005       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3006       "                      \\\n"
3007       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3008       "\n"
3009       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3010       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
3011       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
3012              "\\\n"
3013              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3014              "  \n"
3015              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3016              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
3017 }
3018
3019 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
3020   EXPECT_EQ("int\n"
3021             "#define A\n"
3022             "    a;",
3023             format("int\n#define A\na;"));
3024   verifyFormat("functionCallTo(\n"
3025                "    someOtherFunction(\n"
3026                "        withSomeParameters, whichInSequence,\n"
3027                "        areLongerThanALine(andAnotherCall,\n"
3028                "#define A B\n"
3029                "                           withMoreParamters,\n"
3030                "                           whichStronglyInfluenceTheLayout),\n"
3031                "        andMoreParameters),\n"
3032                "    trailing);",
3033                getLLVMStyleWithColumns(69));
3034   verifyFormat("Foo::Foo()\n"
3035                "#ifdef BAR\n"
3036                "    : baz(0)\n"
3037                "#endif\n"
3038                "{\n"
3039                "}");
3040   verifyFormat("void f() {\n"
3041                "  if (true)\n"
3042                "#ifdef A\n"
3043                "    f(42);\n"
3044                "  x();\n"
3045                "#else\n"
3046                "    g();\n"
3047                "  x();\n"
3048                "#endif\n"
3049                "}");
3050   verifyFormat("void f(param1, param2,\n"
3051                "       param3,\n"
3052                "#ifdef A\n"
3053                "       param4(param5,\n"
3054                "#ifdef A1\n"
3055                "              param6,\n"
3056                "#ifdef A2\n"
3057                "              param7),\n"
3058                "#else\n"
3059                "              param8),\n"
3060                "       param9,\n"
3061                "#endif\n"
3062                "       param10,\n"
3063                "#endif\n"
3064                "       param11)\n"
3065                "#else\n"
3066                "       param12)\n"
3067                "#endif\n"
3068                "{\n"
3069                "  x();\n"
3070                "}",
3071                getLLVMStyleWithColumns(28));
3072   verifyFormat("#if 1\n"
3073                "int i;");
3074   verifyFormat("#if 1\n"
3075                "#endif\n"
3076                "#if 1\n"
3077                "#else\n"
3078                "#endif\n");
3079   verifyFormat("DEBUG({\n"
3080                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3081                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
3082                "});\n"
3083                "#if a\n"
3084                "#else\n"
3085                "#endif");
3086
3087   verifyIncompleteFormat("void f(\n"
3088                          "#if A\n"
3089                          "    );\n"
3090                          "#else\n"
3091                          "#endif");
3092 }
3093
3094 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
3095   verifyFormat("#endif\n"
3096                "#if B");
3097 }
3098
3099 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
3100   FormatStyle SingleLine = getLLVMStyle();
3101   SingleLine.AllowShortIfStatementsOnASingleLine = true;
3102   verifyFormat("#if 0\n"
3103                "#elif 1\n"
3104                "#endif\n"
3105                "void foo() {\n"
3106                "  if (test) foo2();\n"
3107                "}",
3108                SingleLine);
3109 }
3110
3111 TEST_F(FormatTest, LayoutBlockInsideParens) {
3112   verifyFormat("functionCall({ int i; });");
3113   verifyFormat("functionCall({\n"
3114                "  int i;\n"
3115                "  int j;\n"
3116                "});");
3117   verifyFormat("functionCall(\n"
3118                "    {\n"
3119                "      int i;\n"
3120                "      int j;\n"
3121                "    },\n"
3122                "    aaaa, bbbb, cccc);");
3123   verifyFormat("functionA(functionB({\n"
3124                "            int i;\n"
3125                "            int j;\n"
3126                "          }),\n"
3127                "          aaaa, bbbb, cccc);");
3128   verifyFormat("functionCall(\n"
3129                "    {\n"
3130                "      int i;\n"
3131                "      int j;\n"
3132                "    },\n"
3133                "    aaaa, bbbb, // comment\n"
3134                "    cccc);");
3135   verifyFormat("functionA(functionB({\n"
3136                "            int i;\n"
3137                "            int j;\n"
3138                "          }),\n"
3139                "          aaaa, bbbb, // comment\n"
3140                "          cccc);");
3141   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
3142   verifyFormat("functionCall(aaaa, bbbb, {\n"
3143                "  int i;\n"
3144                "  int j;\n"
3145                "});");
3146   verifyFormat(
3147       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
3148       "    {\n"
3149       "      int i; // break\n"
3150       "    },\n"
3151       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
3152       "                                     ccccccccccccccccc));");
3153   verifyFormat("DEBUG({\n"
3154                "  if (a)\n"
3155                "    f();\n"
3156                "});");
3157 }
3158
3159 TEST_F(FormatTest, LayoutBlockInsideStatement) {
3160   EXPECT_EQ("SOME_MACRO { int i; }\n"
3161             "int i;",
3162             format("  SOME_MACRO  {int i;}  int i;"));
3163 }
3164
3165 TEST_F(FormatTest, LayoutNestedBlocks) {
3166   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
3167                "  struct s {\n"
3168                "    int i;\n"
3169                "  };\n"
3170                "  s kBitsToOs[] = {{10}};\n"
3171                "  for (int i = 0; i < 10; ++i)\n"
3172                "    return;\n"
3173                "}");
3174   verifyFormat("call(parameter, {\n"
3175                "  something();\n"
3176                "  // Comment using all columns.\n"
3177                "  somethingelse();\n"
3178                "});",
3179                getLLVMStyleWithColumns(40));
3180   verifyFormat("DEBUG( //\n"
3181                "    { f(); }, a);");
3182   verifyFormat("DEBUG( //\n"
3183                "    {\n"
3184                "      f(); //\n"
3185                "    },\n"
3186                "    a);");
3187
3188   EXPECT_EQ("call(parameter, {\n"
3189             "  something();\n"
3190             "  // Comment too\n"
3191             "  // looooooooooong.\n"
3192             "  somethingElse();\n"
3193             "});",
3194             format("call(parameter, {\n"
3195                    "  something();\n"
3196                    "  // Comment too looooooooooong.\n"
3197                    "  somethingElse();\n"
3198                    "});",
3199                    getLLVMStyleWithColumns(29)));
3200   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
3201   EXPECT_EQ("DEBUG({ // comment\n"
3202             "  int i;\n"
3203             "});",
3204             format("DEBUG({ // comment\n"
3205                    "int  i;\n"
3206                    "});"));
3207   EXPECT_EQ("DEBUG({\n"
3208             "  int i;\n"
3209             "\n"
3210             "  // comment\n"
3211             "  int j;\n"
3212             "});",
3213             format("DEBUG({\n"
3214                    "  int  i;\n"
3215                    "\n"
3216                    "  // comment\n"
3217                    "  int  j;\n"
3218                    "});"));
3219
3220   verifyFormat("DEBUG({\n"
3221                "  if (a)\n"
3222                "    return;\n"
3223                "});");
3224   verifyGoogleFormat("DEBUG({\n"
3225                      "  if (a) return;\n"
3226                      "});");
3227   FormatStyle Style = getGoogleStyle();
3228   Style.ColumnLimit = 45;
3229   verifyFormat("Debug(aaaaa,\n"
3230                "      {\n"
3231                "        if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
3232                "      },\n"
3233                "      a);",
3234                Style);
3235
3236   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
3237
3238   verifyNoCrash("^{v^{a}}");
3239 }
3240
3241 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
3242   EXPECT_EQ("#define MACRO()                     \\\n"
3243             "  Debug(aaa, /* force line break */ \\\n"
3244             "        {                           \\\n"
3245             "          int i;                    \\\n"
3246             "          int j;                    \\\n"
3247             "        })",
3248             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
3249                    "          {  int   i;  int  j;   })",
3250                    getGoogleStyle()));
3251
3252   EXPECT_EQ("#define A                                       \\\n"
3253             "  [] {                                          \\\n"
3254             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
3255             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
3256             "  }",
3257             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
3258                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
3259                    getGoogleStyle()));
3260 }
3261
3262 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
3263   EXPECT_EQ("{}", format("{}"));
3264   verifyFormat("enum E {};");
3265   verifyFormat("enum E {}");
3266 }
3267
3268 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
3269   FormatStyle Style = getLLVMStyle();
3270   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
3271   Style.MacroBlockEnd = "^[A-Z_]+_END$";
3272   verifyFormat("FOO_BEGIN\n"
3273                "  FOO_ENTRY\n"
3274                "FOO_END", Style);
3275   verifyFormat("FOO_BEGIN\n"
3276                "  NESTED_FOO_BEGIN\n"
3277                "    NESTED_FOO_ENTRY\n"
3278                "  NESTED_FOO_END\n"
3279                "FOO_END", Style);
3280   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
3281                "  int x;\n"
3282                "  x = 1;\n"
3283                "FOO_END(Baz)", Style);
3284 }
3285
3286 //===----------------------------------------------------------------------===//
3287 // Line break tests.
3288 //===----------------------------------------------------------------------===//
3289
3290 TEST_F(FormatTest, PreventConfusingIndents) {
3291   verifyFormat(
3292       "void f() {\n"
3293       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
3294       "                         parameter, parameter, parameter)),\n"
3295       "                     SecondLongCall(parameter));\n"
3296       "}");
3297   verifyFormat(
3298       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3299       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
3300       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3301       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
3302   verifyFormat(
3303       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3304       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
3305       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3306       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
3307   verifyFormat(
3308       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
3309       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
3310       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
3311       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
3312   verifyFormat("int a = bbbb && ccc && fffff(\n"
3313                "#define A Just forcing a new line\n"
3314                "                           ddd);");
3315 }
3316
3317 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
3318   verifyFormat(
3319       "bool aaaaaaa =\n"
3320       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
3321       "    bbbbbbbb();");
3322   verifyFormat(
3323       "bool aaaaaaa =\n"
3324       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
3325       "    bbbbbbbb();");
3326
3327   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
3328                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
3329                "    ccccccccc == ddddddddddd;");
3330   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
3331                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
3332                "    ccccccccc == ddddddddddd;");
3333   verifyFormat(
3334       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
3335       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
3336       "    ccccccccc == ddddddddddd;");
3337
3338   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
3339                "                 aaaaaa) &&\n"
3340                "         bbbbbb && cccccc;");
3341   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
3342                "                 aaaaaa) >>\n"
3343                "         bbbbbb;");
3344   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
3345                "    SourceMgr.getSpellingColumnNumber(\n"
3346                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
3347                "    1);");
3348
3349   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3350                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
3351                "    cccccc) {\n}");
3352   verifyFormat("b = a &&\n"
3353                "    // Comment\n"
3354                "    b.c && d;");
3355
3356   // If the LHS of a comparison is not a binary expression itself, the
3357   // additional linebreak confuses many people.
3358   verifyFormat(
3359       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3360       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
3361       "}");
3362   verifyFormat(
3363       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3364       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
3365       "}");
3366   verifyFormat(
3367       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
3368       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
3369       "}");
3370   // Even explicit parentheses stress the precedence enough to make the
3371   // additional break unnecessary.
3372   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3373                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
3374                "}");
3375   // This cases is borderline, but with the indentation it is still readable.
3376   verifyFormat(
3377       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3378       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3379       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
3380       "}",
3381       getLLVMStyleWithColumns(75));
3382
3383   // If the LHS is a binary expression, we should still use the additional break
3384   // as otherwise the formatting hides the operator precedence.
3385   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3386                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3387                "    5) {\n"
3388                "}");
3389
3390   FormatStyle OnePerLine = getLLVMStyle();
3391   OnePerLine.BinPackParameters = false;
3392   verifyFormat(
3393       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3394       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3395       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
3396       OnePerLine);
3397 }
3398
3399 TEST_F(FormatTest, ExpressionIndentation) {
3400   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3401                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3402                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3403                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3404                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
3405                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
3406                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3407                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
3408                "                 ccccccccccccccccccccccccccccccccccccccccc;");
3409   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3410                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3411                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3412                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
3413   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3414                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3415                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3416                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
3417   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
3418                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
3419                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3420                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
3421   verifyFormat("if () {\n"
3422                "} else if (aaaaa &&\n"
3423                "           bbbbb > // break\n"
3424                "               ccccc) {\n"
3425                "}");
3426
3427   // Presence of a trailing comment used to change indentation of b.
3428   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
3429                "       b;\n"
3430                "return aaaaaaaaaaaaaaaaaaa +\n"
3431                "       b; //",
3432                getLLVMStyleWithColumns(30));
3433 }
3434
3435 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
3436   // Not sure what the best system is here. Like this, the LHS can be found
3437   // immediately above an operator (everything with the same or a higher
3438   // indent). The RHS is aligned right of the operator and so compasses
3439   // everything until something with the same indent as the operator is found.
3440   // FIXME: Is this a good system?
3441   FormatStyle Style = getLLVMStyle();
3442   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
3443   verifyFormat(
3444       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3445       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3446       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3447       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3448       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3449       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3450       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3451       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3452       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
3453       Style);
3454   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3455                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3456                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3457                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
3458                Style);
3459   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3460                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3461                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3462                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
3463                Style);
3464   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3465                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3466                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3467                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
3468                Style);
3469   verifyFormat("if () {\n"
3470                "} else if (aaaaa\n"
3471                "           && bbbbb // break\n"
3472                "                  > ccccc) {\n"
3473                "}",
3474                Style);
3475   verifyFormat("return (a)\n"
3476                "       // comment\n"
3477                "       + b;",
3478                Style);
3479   verifyFormat(
3480       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3481       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3482       "             + cc;",
3483       Style);
3484
3485   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3486                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
3487                Style);
3488
3489   // Forced by comments.
3490   verifyFormat(
3491       "unsigned ContentSize =\n"
3492       "    sizeof(int16_t)   // DWARF ARange version number\n"
3493       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
3494       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
3495       "    + sizeof(int8_t); // Segment Size (in bytes)");
3496
3497   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
3498                "       == boost::fusion::at_c<1>(iiii).second;",
3499                Style);
3500
3501   Style.ColumnLimit = 60;
3502   verifyFormat("zzzzzzzzzz\n"
3503                "    = bbbbbbbbbbbbbbbbb\n"
3504                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
3505                Style);
3506 }
3507
3508 TEST_F(FormatTest, NoOperandAlignment) {
3509   FormatStyle Style = getLLVMStyle();
3510   Style.AlignOperands = false;
3511   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
3512   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3513                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3514                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3515                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3516                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3517                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3518                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3519                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3520                "        > ccccccccccccccccccccccccccccccccccccccccc;",
3521                Style);
3522
3523   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3524                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3525                "    + cc;",
3526                Style);
3527   verifyFormat("int a = aa\n"
3528                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
3529                "        * cccccccccccccccccccccccccccccccccccc;",
3530                Style);
3531
3532   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
3533   verifyFormat("return (a > b\n"
3534                "    // comment1\n"
3535                "    // comment2\n"
3536                "    || c);",
3537                Style);
3538 }
3539
3540 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
3541   FormatStyle Style = getLLVMStyle();
3542   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
3543   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3544                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3545                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
3546                Style);
3547 }
3548
3549 TEST_F(FormatTest, ConstructorInitializers) {
3550   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
3551   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
3552                getLLVMStyleWithColumns(45));
3553   verifyFormat("Constructor()\n"
3554                "    : Inttializer(FitsOnTheLine) {}",
3555                getLLVMStyleWithColumns(44));
3556   verifyFormat("Constructor()\n"
3557                "    : Inttializer(FitsOnTheLine) {}",
3558                getLLVMStyleWithColumns(43));
3559
3560   verifyFormat("template <typename T>\n"
3561                "Constructor() : Initializer(FitsOnTheLine) {}",
3562                getLLVMStyleWithColumns(45));
3563
3564   verifyFormat(
3565       "SomeClass::Constructor()\n"
3566       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
3567
3568   verifyFormat(
3569       "SomeClass::Constructor()\n"
3570       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3571       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
3572   verifyFormat(
3573       "SomeClass::Constructor()\n"
3574       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3575       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
3576   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3577                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3578                "    : aaaaaaaaaa(aaaaaa) {}");
3579
3580   verifyFormat("Constructor()\n"
3581                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3582                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3583                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
3584                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
3585
3586   verifyFormat("Constructor()\n"
3587                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3588                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
3589
3590   verifyFormat("Constructor(int Parameter = 0)\n"
3591                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
3592                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
3593   verifyFormat("Constructor()\n"
3594                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
3595                "}",
3596                getLLVMStyleWithColumns(60));
3597   verifyFormat("Constructor()\n"
3598                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3599                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
3600
3601   // Here a line could be saved by splitting the second initializer onto two
3602   // lines, but that is not desirable.
3603   verifyFormat("Constructor()\n"
3604                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
3605                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
3606                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
3607
3608   FormatStyle OnePerLine = getLLVMStyle();
3609   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
3610   verifyFormat("SomeClass::Constructor()\n"
3611                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3612                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3613                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
3614                OnePerLine);
3615   verifyFormat("SomeClass::Constructor()\n"
3616                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
3617                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
3618                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
3619                OnePerLine);
3620   verifyFormat("MyClass::MyClass(int var)\n"
3621                "    : some_var_(var),            // 4 space indent\n"
3622                "      some_other_var_(var + 1) { // lined up\n"
3623                "}",
3624                OnePerLine);
3625   verifyFormat("Constructor()\n"
3626                "    : aaaaa(aaaaaa),\n"
3627                "      aaaaa(aaaaaa),\n"
3628                "      aaaaa(aaaaaa),\n"
3629                "      aaaaa(aaaaaa),\n"
3630                "      aaaaa(aaaaaa) {}",
3631                OnePerLine);
3632   verifyFormat("Constructor()\n"
3633                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
3634                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
3635                OnePerLine);
3636   OnePerLine.ColumnLimit = 60;
3637   verifyFormat("Constructor()\n"
3638                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
3639                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
3640                OnePerLine);
3641
3642   EXPECT_EQ("Constructor()\n"
3643             "    : // Comment forcing unwanted break.\n"
3644             "      aaaa(aaaa) {}",
3645             format("Constructor() :\n"
3646                    "    // Comment forcing unwanted break.\n"
3647                    "    aaaa(aaaa) {}"));
3648 }
3649
3650 TEST_F(FormatTest, MemoizationTests) {
3651   // This breaks if the memoization lookup does not take \c Indent and
3652   // \c LastSpace into account.
3653   verifyFormat(
3654       "extern CFRunLoopTimerRef\n"
3655       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
3656       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
3657       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
3658       "                     CFRunLoopTimerContext *context) {}");
3659
3660   // Deep nesting somewhat works around our memoization.
3661   verifyFormat(
3662       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3663       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3664       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3665       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
3666       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
3667       getLLVMStyleWithColumns(65));
3668   verifyFormat(
3669       "aaaaa(\n"
3670       "    aaaaa,\n"
3671       "    aaaaa(\n"
3672       "        aaaaa,\n"
3673       "        aaaaa(\n"
3674       "            aaaaa,\n"
3675       "            aaaaa(\n"
3676       "                aaaaa,\n"
3677       "                aaaaa(\n"
3678       "                    aaaaa,\n"
3679       "                    aaaaa(\n"
3680       "                        aaaaa,\n"
3681       "                        aaaaa(\n"
3682       "                            aaaaa,\n"
3683       "                            aaaaa(\n"
3684       "                                aaaaa,\n"
3685       "                                aaaaa(\n"
3686       "                                    aaaaa,\n"
3687       "                                    aaaaa(\n"
3688       "                                        aaaaa,\n"
3689       "                                        aaaaa(\n"
3690       "                                            aaaaa,\n"
3691       "                                            aaaaa(\n"
3692       "                                                aaaaa,\n"
3693       "                                                aaaaa))))))))))));",
3694       getLLVMStyleWithColumns(65));
3695   verifyFormat(
3696       "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"
3697       "                                  a),\n"
3698       "                                a),\n"
3699       "                              a),\n"
3700       "                            a),\n"
3701       "                          a),\n"
3702       "                        a),\n"
3703       "                      a),\n"
3704       "                    a),\n"
3705       "                  a),\n"
3706       "                a),\n"
3707       "              a),\n"
3708       "            a),\n"
3709       "          a),\n"
3710       "        a),\n"
3711       "      a),\n"
3712       "    a),\n"
3713       "  a)",
3714       getLLVMStyleWithColumns(65));
3715
3716   // This test takes VERY long when memoization is broken.
3717   FormatStyle OnePerLine = getLLVMStyle();
3718   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
3719   OnePerLine.BinPackParameters = false;
3720   std::string input = "Constructor()\n"
3721                       "    : aaaa(a,\n";
3722   for (unsigned i = 0, e = 80; i != e; ++i) {
3723     input += "           a,\n";
3724   }
3725   input += "           a) {}";
3726   verifyFormat(input, OnePerLine);
3727 }
3728
3729 TEST_F(FormatTest, BreaksAsHighAsPossible) {
3730   verifyFormat(
3731       "void f() {\n"
3732       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
3733       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
3734       "    f();\n"
3735       "}");
3736   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
3737                "    Intervals[i - 1].getRange().getLast()) {\n}");
3738 }
3739
3740 TEST_F(FormatTest, BreaksFunctionDeclarations) {
3741   // Principially, we break function declarations in a certain order:
3742   // 1) break amongst arguments.
3743   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
3744                "                              Cccccccccccccc cccccccccccccc);");
3745   verifyFormat("template <class TemplateIt>\n"
3746                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
3747                "                            TemplateIt *stop) {}");
3748
3749   // 2) break after return type.
3750   verifyFormat(
3751       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3752       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
3753       getGoogleStyle());
3754
3755   // 3) break after (.
3756   verifyFormat(
3757       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
3758       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
3759       getGoogleStyle());
3760
3761   // 4) break before after nested name specifiers.
3762   verifyFormat(
3763       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3764       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
3765       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
3766       getGoogleStyle());
3767
3768   // However, there are exceptions, if a sufficient amount of lines can be
3769   // saved.
3770   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
3771   // more adjusting.
3772   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
3773                "                                  Cccccccccccccc cccccccccc,\n"
3774                "                                  Cccccccccccccc cccccccccc,\n"
3775                "                                  Cccccccccccccc cccccccccc,\n"
3776                "                                  Cccccccccccccc cccccccccc);");
3777   verifyFormat(
3778       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3779       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3780       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3781       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
3782       getGoogleStyle());
3783   verifyFormat(
3784       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
3785       "                                          Cccccccccccccc cccccccccc,\n"
3786       "                                          Cccccccccccccc cccccccccc,\n"
3787       "                                          Cccccccccccccc cccccccccc,\n"
3788       "                                          Cccccccccccccc cccccccccc,\n"
3789       "                                          Cccccccccccccc cccccccccc,\n"
3790       "                                          Cccccccccccccc cccccccccc);");
3791   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
3792                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3793                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3794                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
3795                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
3796
3797   // Break after multi-line parameters.
3798   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3799                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3800                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3801                "    bbbb bbbb);");
3802   verifyFormat("void SomeLoooooooooooongFunction(\n"
3803                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
3804                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3805                "    int bbbbbbbbbbbbb);");
3806
3807   // Treat overloaded operators like other functions.
3808   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
3809                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
3810   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
3811                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
3812   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
3813                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
3814   verifyGoogleFormat(
3815       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
3816       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
3817   verifyGoogleFormat(
3818       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
3819       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
3820   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3821                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
3822   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
3823                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
3824   verifyGoogleFormat(
3825       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
3826       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3827       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
3828
3829   FormatStyle Style = getLLVMStyle();
3830   Style.PointerAlignment = FormatStyle::PAS_Left;
3831   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3832                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
3833                Style);
3834   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
3835                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
3836                Style);
3837 }
3838
3839 TEST_F(FormatTest, TrailingReturnType) {
3840   verifyFormat("auto foo() -> int;\n");
3841   verifyFormat("struct S {\n"
3842                "  auto bar() const -> int;\n"
3843                "};");
3844   verifyFormat("template <size_t Order, typename T>\n"
3845                "auto load_img(const std::string &filename)\n"
3846                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
3847   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
3848                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
3849   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
3850   verifyFormat("template <typename T>\n"
3851                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
3852                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
3853
3854   // Not trailing return types.
3855   verifyFormat("void f() { auto a = b->c(); }");
3856 }
3857
3858 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
3859   // Avoid breaking before trailing 'const' or other trailing annotations, if
3860   // they are not function-like.
3861   FormatStyle Style = getGoogleStyle();
3862   Style.ColumnLimit = 47;
3863   verifyFormat("void someLongFunction(\n"
3864                "    int someLoooooooooooooongParameter) const {\n}",
3865                getLLVMStyleWithColumns(47));
3866   verifyFormat("LoooooongReturnType\n"
3867                "someLoooooooongFunction() const {}",
3868                getLLVMStyleWithColumns(47));
3869   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
3870                "    const {}",
3871                Style);
3872   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
3873                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
3874   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
3875                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
3876   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
3877                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
3878   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
3879                "                   aaaaaaaaaaa aaaaa) const override;");
3880   verifyGoogleFormat(
3881       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
3882       "    const override;");
3883
3884   // Even if the first parameter has to be wrapped.
3885   verifyFormat("void someLongFunction(\n"
3886                "    int someLongParameter) const {}",
3887                getLLVMStyleWithColumns(46));
3888   verifyFormat("void someLongFunction(\n"
3889                "    int someLongParameter) const {}",
3890                Style);
3891   verifyFormat("void someLongFunction(\n"
3892                "    int someLongParameter) override {}",
3893                Style);
3894   verifyFormat("void someLongFunction(\n"
3895                "    int someLongParameter) OVERRIDE {}",
3896                Style);
3897   verifyFormat("void someLongFunction(\n"
3898                "    int someLongParameter) final {}",
3899                Style);
3900   verifyFormat("void someLongFunction(\n"
3901                "    int someLongParameter) FINAL {}",
3902                Style);
3903   verifyFormat("void someLongFunction(\n"
3904                "    int parameter) const override {}",
3905                Style);
3906
3907   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
3908   verifyFormat("void someLongFunction(\n"
3909                "    int someLongParameter) const\n"
3910                "{\n"
3911                "}",
3912                Style);
3913
3914   // Unless these are unknown annotations.
3915   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
3916                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3917                "    LONG_AND_UGLY_ANNOTATION;");
3918
3919   // Breaking before function-like trailing annotations is fine to keep them
3920   // close to their arguments.
3921   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3922                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
3923   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
3924                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
3925   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
3926                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
3927   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
3928                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
3929   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
3930
3931   verifyFormat(
3932       "void aaaaaaaaaaaaaaaaaa()\n"
3933       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
3934       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
3935   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3936                "    __attribute__((unused));");
3937   verifyGoogleFormat(
3938       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3939       "    GUARDED_BY(aaaaaaaaaaaa);");
3940   verifyGoogleFormat(
3941       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3942       "    GUARDED_BY(aaaaaaaaaaaa);");
3943   verifyGoogleFormat(
3944       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
3945       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3946   verifyGoogleFormat(
3947       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
3948       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
3949 }
3950
3951 TEST_F(FormatTest, FunctionAnnotations) {
3952   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
3953                "int OldFunction(const string &parameter) {}");
3954   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
3955                "string OldFunction(const string &parameter) {}");
3956   verifyFormat("template <typename T>\n"
3957                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
3958                "string OldFunction(const string &parameter) {}");
3959
3960   // Not function annotations.
3961   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3962                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
3963   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
3964                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
3965 }
3966
3967 TEST_F(FormatTest, BreaksDesireably) {
3968   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
3969                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
3970                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
3971   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3972                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
3973                "}");
3974
3975   verifyFormat(
3976       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3977       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
3978
3979   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3980                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3981                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
3982
3983   verifyFormat(
3984       "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3985       "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
3986       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3987       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
3988
3989   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3990                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3991
3992   verifyFormat(
3993       "void f() {\n"
3994       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
3995       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
3996       "}");
3997   verifyFormat(
3998       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3999       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
4000   verifyFormat(
4001       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4002       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
4003   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4004                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4005                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4006
4007   // Indent consistently independent of call expression and unary operator.
4008   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
4009                "    dddddddddddddddddddddddddddddd));");
4010   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
4011                "    dddddddddddddddddddddddddddddd));");
4012   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
4013                "    dddddddddddddddddddddddddddddd));");
4014
4015   // This test case breaks on an incorrect memoization, i.e. an optimization not
4016   // taking into account the StopAt value.
4017   verifyFormat(
4018       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
4019       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
4020       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
4021       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4022
4023   verifyFormat("{\n  {\n    {\n"
4024                "      Annotation.SpaceRequiredBefore =\n"
4025                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
4026                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
4027                "    }\n  }\n}");
4028
4029   // Break on an outer level if there was a break on an inner level.
4030   EXPECT_EQ("f(g(h(a, // comment\n"
4031             "      b, c),\n"
4032             "    d, e),\n"
4033             "  x, y);",
4034             format("f(g(h(a, // comment\n"
4035                    "    b, c), d, e), x, y);"));
4036
4037   // Prefer breaking similar line breaks.
4038   verifyFormat(
4039       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
4040       "                             NSTrackingMouseEnteredAndExited |\n"
4041       "                             NSTrackingActiveAlways;");
4042 }
4043
4044 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
4045   FormatStyle NoBinPacking = getGoogleStyle();
4046   NoBinPacking.BinPackParameters = false;
4047   NoBinPacking.BinPackArguments = true;
4048   verifyFormat("void f() {\n"
4049                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
4050                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
4051                "}",
4052                NoBinPacking);
4053   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
4054                "       int aaaaaaaaaaaaaaaaaaaa,\n"
4055                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4056                NoBinPacking);
4057 }
4058
4059 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
4060   FormatStyle NoBinPacking = getGoogleStyle();
4061   NoBinPacking.BinPackParameters = false;
4062   NoBinPacking.BinPackArguments = false;
4063   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
4064                "  aaaaaaaaaaaaaaaaaaaa,\n"
4065                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
4066                NoBinPacking);
4067   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
4068                "        aaaaaaaaaaaaa,\n"
4069                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
4070                NoBinPacking);
4071   verifyFormat(
4072       "aaaaaaaa(aaaaaaaaaaaaa,\n"
4073       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4074       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
4075       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4076       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
4077       NoBinPacking);
4078   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
4079                "    .aaaaaaaaaaaaaaaaaa();",
4080                NoBinPacking);
4081   verifyFormat("void f() {\n"
4082                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4083                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
4084                "}",
4085                NoBinPacking);
4086
4087   verifyFormat(
4088       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4089       "             aaaaaaaaaaaa,\n"
4090       "             aaaaaaaaaaaa);",
4091       NoBinPacking);
4092   verifyFormat(
4093       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
4094       "                               ddddddddddddddddddddddddddddd),\n"
4095       "             test);",
4096       NoBinPacking);
4097
4098   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
4099                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
4100                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
4101                "    aaaaaaaaaaaaaaaaaa;",
4102                NoBinPacking);
4103   verifyFormat("a(\"a\"\n"
4104                "  \"a\",\n"
4105                "  a);");
4106
4107   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
4108   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
4109                "                aaaaaaaaa,\n"
4110                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4111                NoBinPacking);
4112   verifyFormat(
4113       "void f() {\n"
4114       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
4115       "      .aaaaaaa();\n"
4116       "}",
4117       NoBinPacking);
4118   verifyFormat(
4119       "template <class SomeType, class SomeOtherType>\n"
4120       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
4121       NoBinPacking);
4122 }
4123
4124 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
4125   FormatStyle Style = getLLVMStyleWithColumns(15);
4126   Style.ExperimentalAutoDetectBinPacking = true;
4127   EXPECT_EQ("aaa(aaaa,\n"
4128             "    aaaa,\n"
4129             "    aaaa);\n"
4130             "aaa(aaaa,\n"
4131             "    aaaa,\n"
4132             "    aaaa);",
4133             format("aaa(aaaa,\n" // one-per-line
4134                    "  aaaa,\n"
4135                    "    aaaa  );\n"
4136                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
4137                    Style));
4138   EXPECT_EQ("aaa(aaaa, aaaa,\n"
4139             "    aaaa);\n"
4140             "aaa(aaaa, aaaa,\n"
4141             "    aaaa);",
4142             format("aaa(aaaa,  aaaa,\n" // bin-packed
4143                    "    aaaa  );\n"
4144                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
4145                    Style));
4146 }
4147
4148 TEST_F(FormatTest, FormatsBuilderPattern) {
4149   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
4150                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
4151                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
4152                "    .StartsWith(\".init\", ORDER_INIT)\n"
4153                "    .StartsWith(\".fini\", ORDER_FINI)\n"
4154                "    .StartsWith(\".hash\", ORDER_HASH)\n"
4155                "    .Default(ORDER_TEXT);\n");
4156
4157   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
4158                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
4159   verifyFormat(
4160       "aaaaaaa->aaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4161       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4162       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
4163   verifyFormat(
4164       "aaaaaaa->aaaaaaa\n"
4165       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4166       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
4167   verifyFormat(
4168       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
4169       "    aaaaaaaaaaaaaa);");
4170   verifyFormat(
4171       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
4172       "    aaaaaa->aaaaaaaaaaaa()\n"
4173       "        ->aaaaaaaaaaaaaaaa(\n"
4174       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4175       "        ->aaaaaaaaaaaaaaaaa();");
4176   verifyGoogleFormat(
4177       "void f() {\n"
4178       "  someo->Add((new util::filetools::Handler(dir))\n"
4179       "                 ->OnEvent1(NewPermanentCallback(\n"
4180       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
4181       "                 ->OnEvent2(NewPermanentCallback(\n"
4182       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
4183       "                 ->OnEvent3(NewPermanentCallback(\n"
4184       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
4185       "                 ->OnEvent5(NewPermanentCallback(\n"
4186       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
4187       "                 ->OnEvent6(NewPermanentCallback(\n"
4188       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
4189       "}");
4190
4191   verifyFormat(
4192       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
4193   verifyFormat("aaaaaaaaaaaaaaa()\n"
4194                "    .aaaaaaaaaaaaaaa()\n"
4195                "    .aaaaaaaaaaaaaaa()\n"
4196                "    .aaaaaaaaaaaaaaa()\n"
4197                "    .aaaaaaaaaaaaaaa();");
4198   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
4199                "    .aaaaaaaaaaaaaaa()\n"
4200                "    .aaaaaaaaaaaaaaa()\n"
4201                "    .aaaaaaaaaaaaaaa();");
4202   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
4203                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
4204                "    .aaaaaaaaaaaaaaa();");
4205   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
4206                "    ->aaaaaaaaaaaaaae(0)\n"
4207                "    ->aaaaaaaaaaaaaaa();");
4208
4209   // Don't linewrap after very short segments.
4210   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4211                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4212                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4213   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4214                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4215                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4216   verifyFormat("aaa()\n"
4217                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4218                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4219                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
4220
4221   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
4222                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
4223                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
4224   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
4225                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
4226                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
4227
4228   // Prefer not to break after empty parentheses.
4229   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
4230                "    First->LastNewlineOffset);");
4231
4232   // Prefer not to create "hanging" indents.
4233   verifyFormat(
4234       "return !soooooooooooooome_map\n"
4235       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4236       "            .second;");
4237 }
4238
4239 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
4240   verifyFormat(
4241       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4242       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
4243   verifyFormat(
4244       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
4245       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
4246
4247   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
4248                "    ccccccccccccccccccccccccc) {\n}");
4249   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
4250                "    ccccccccccccccccccccccccc) {\n}");
4251
4252   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
4253                "    ccccccccccccccccccccccccc) {\n}");
4254   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
4255                "    ccccccccccccccccccccccccc) {\n}");
4256
4257   verifyFormat(
4258       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
4259       "    ccccccccccccccccccccccccc) {\n}");
4260   verifyFormat(
4261       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
4262       "    ccccccccccccccccccccccccc) {\n}");
4263
4264   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
4265                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
4266                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
4267                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
4268   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
4269                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
4270                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
4271                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
4272
4273   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
4274                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
4275                "    aaaaaaaaaaaaaaa != aa) {\n}");
4276   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
4277                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
4278                "    aaaaaaaaaaaaaaa != aa) {\n}");
4279 }
4280
4281 TEST_F(FormatTest, BreaksAfterAssignments) {
4282   verifyFormat(
4283       "unsigned Cost =\n"
4284       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
4285       "                        SI->getPointerAddressSpaceee());\n");
4286   verifyFormat(
4287       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
4288       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
4289
4290   verifyFormat(
4291       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
4292       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
4293   verifyFormat("unsigned OriginalStartColumn =\n"
4294                "    SourceMgr.getSpellingColumnNumber(\n"
4295                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
4296                "    1;");
4297 }
4298
4299 TEST_F(FormatTest, AlignsAfterAssignments) {
4300   verifyFormat(
4301       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4302       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
4303   verifyFormat(
4304       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4305       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
4306   verifyFormat(
4307       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4308       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
4309   verifyFormat(
4310       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4311       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
4312   verifyFormat(
4313       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
4314       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
4315       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
4316 }
4317
4318 TEST_F(FormatTest, AlignsAfterReturn) {
4319   verifyFormat(
4320       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4321       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
4322   verifyFormat(
4323       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4324       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
4325   verifyFormat(
4326       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
4327       "       aaaaaaaaaaaaaaaaaaaaaa();");
4328   verifyFormat(
4329       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
4330       "        aaaaaaaaaaaaaaaaaaaaaa());");
4331   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4332                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4333   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4334                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
4335                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4336   verifyFormat("return\n"
4337                "    // true if code is one of a or b.\n"
4338                "    code == a || code == b;");
4339 }
4340
4341 TEST_F(FormatTest, AlignsAfterOpenBracket) {
4342   verifyFormat(
4343       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
4344       "                                                aaaaaaaaa aaaaaaa) {}");
4345   verifyFormat(
4346       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
4347       "                                               aaaaaaaaaaa aaaaaaaaa);");
4348   verifyFormat(
4349       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
4350       "                                             aaaaaaaaaaaaaaaaaaaaa));");
4351   FormatStyle Style = getLLVMStyle();
4352   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4353   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4354                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
4355                Style);
4356   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
4357                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
4358                Style);
4359   verifyFormat("SomeLongVariableName->someFunction(\n"
4360                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
4361                Style);
4362   verifyFormat(
4363       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
4364       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4365       Style);
4366   verifyFormat(
4367       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
4368       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4369       Style);
4370   verifyFormat(
4371       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
4372       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
4373       Style);
4374
4375   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
4376   Style.BinPackArguments = false;
4377   Style.BinPackParameters = false;
4378   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4379                "    aaaaaaaaaaa aaaaaaaa,\n"
4380                "    aaaaaaaaa aaaaaaa,\n"
4381                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4382                Style);
4383   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
4384                "    aaaaaaaaaaa aaaaaaaaa,\n"
4385                "    aaaaaaaaaaa aaaaaaaaa,\n"
4386                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4387                Style);
4388   verifyFormat("SomeLongVariableName->someFunction(\n"
4389                "    foooooooo(\n"
4390                "        aaaaaaaaaaaaaaa,\n"
4391                "        aaaaaaaaaaaaaaaaaaaaa,\n"
4392                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
4393                Style);
4394 }
4395
4396 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
4397   FormatStyle Style = getLLVMStyleWithColumns(40);
4398   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4399                "          bbbbbbbbbbbbbbbbbbbbbb);",
4400                Style);
4401   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
4402   Style.AlignOperands = false;
4403   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4404                "          bbbbbbbbbbbbbbbbbbbbbb);",
4405                Style);
4406   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4407   Style.AlignOperands = true;
4408   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4409                "          bbbbbbbbbbbbbbbbbbbbbb);",
4410                Style);
4411   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4412   Style.AlignOperands = false;
4413   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
4414                "    bbbbbbbbbbbbbbbbbbbbbb);",
4415                Style);
4416 }
4417
4418 TEST_F(FormatTest, BreaksConditionalExpressions) {
4419   verifyFormat(
4420       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4421       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4422       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4423   verifyFormat(
4424       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4425       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4426   verifyFormat(
4427       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
4428       "                                                    : aaaaaaaaaaaaa);");
4429   verifyFormat(
4430       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4431       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4432       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4433       "                   aaaaaaaaaaaaa);");
4434   verifyFormat(
4435       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4436       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4437       "                   aaaaaaaaaaaaa);");
4438   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4439                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4440                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4441                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4442                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4443   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4444                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4445                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4446                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4447                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4448                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4449                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4450   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4451                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4452                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4453                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4454                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4455   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4456                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4457                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4458   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
4459                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4460                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4461                "        : aaaaaaaaaaaaaaaa;");
4462   verifyFormat(
4463       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4464       "    ? aaaaaaaaaaaaaaa\n"
4465       "    : aaaaaaaaaaaaaaa;");
4466   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
4467                "          aaaaaaaaa\n"
4468                "      ? b\n"
4469                "      : c);");
4470   verifyFormat("return aaaa == bbbb\n"
4471                "           // comment\n"
4472                "           ? aaaa\n"
4473                "           : bbbb;");
4474   verifyFormat("unsigned Indent =\n"
4475                "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0\n"
4476                "                              ? IndentForLevel[TheLine.Level]\n"
4477                "                              : TheLine * 2,\n"
4478                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
4479                getLLVMStyleWithColumns(70));
4480   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
4481                "                  ? aaaaaaaaaaaaaaa\n"
4482                "                  : bbbbbbbbbbbbbbb //\n"
4483                "                        ? ccccccccccccccc\n"
4484                "                        : ddddddddddddddd;");
4485   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
4486                "                  ? aaaaaaaaaaaaaaa\n"
4487                "                  : (bbbbbbbbbbbbbbb //\n"
4488                "                         ? ccccccccccccccc\n"
4489                "                         : ddddddddddddddd);");
4490   verifyFormat(
4491       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4492       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4493       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
4494       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
4495       "                                      : aaaaaaaaaa;");
4496   verifyFormat(
4497       "aaaaaa = aaaaaaaaaaaa\n"
4498       "             ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4499       "                          : aaaaaaaaaaaaaaaaaaaaaa\n"
4500       "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4501
4502   FormatStyle NoBinPacking = getLLVMStyle();
4503   NoBinPacking.BinPackArguments = false;
4504   verifyFormat(
4505       "void f() {\n"
4506       "  g(aaa,\n"
4507       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
4508       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4509       "        ? aaaaaaaaaaaaaaa\n"
4510       "        : aaaaaaaaaaaaaaa);\n"
4511       "}",
4512       NoBinPacking);
4513   verifyFormat(
4514       "void f() {\n"
4515       "  g(aaa,\n"
4516       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
4517       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4518       "        ?: aaaaaaaaaaaaaaa);\n"
4519       "}",
4520       NoBinPacking);
4521
4522   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
4523                "             // comment.\n"
4524                "             ccccccccccccccccccccccccccccccccccccccc\n"
4525                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4526                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
4527
4528   // Assignments in conditional expressions. Apparently not uncommon :-(.
4529   verifyFormat("return a != b\n"
4530                "           // comment\n"
4531                "           ? a = b\n"
4532                "           : a = b;");
4533   verifyFormat("return a != b\n"
4534                "           // comment\n"
4535                "           ? a = a != b\n"
4536                "                     // comment\n"
4537                "                     ? a = b\n"
4538                "                     : a\n"
4539                "           : a;\n");
4540   verifyFormat("return a != b\n"
4541                "           // comment\n"
4542                "           ? a\n"
4543                "           : a = a != b\n"
4544                "                     // comment\n"
4545                "                     ? a = b\n"
4546                "                     : a;");
4547 }
4548
4549 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
4550   FormatStyle Style = getLLVMStyle();
4551   Style.BreakBeforeTernaryOperators = false;
4552   Style.ColumnLimit = 70;
4553   verifyFormat(
4554       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4555       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4556       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4557       Style);
4558   verifyFormat(
4559       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4560       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4561       Style);
4562   verifyFormat(
4563       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
4564       "                                                      aaaaaaaaaaaaa);",
4565       Style);
4566   verifyFormat(
4567       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4568       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4569       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4570       "                   aaaaaaaaaaaaa);",
4571       Style);
4572   verifyFormat(
4573       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4574       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4575       "                   aaaaaaaaaaaaa);",
4576       Style);
4577   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4578                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4579                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
4580                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4581                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4582                Style);
4583   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4584                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4585                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4586                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
4587                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4588                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4589                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4590                Style);
4591   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4592                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
4593                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4594                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4595                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4596                Style);
4597   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4598                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4599                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4600                Style);
4601   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
4602                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4603                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
4604                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4605                Style);
4606   verifyFormat(
4607       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
4608       "    aaaaaaaaaaaaaaa :\n"
4609       "    aaaaaaaaaaaaaaa;",
4610       Style);
4611   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
4612                "          aaaaaaaaa ?\n"
4613                "      b :\n"
4614                "      c);",
4615                Style);
4616   verifyFormat(
4617       "unsigned Indent =\n"
4618       "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0 ?\n"
4619       "                              IndentForLevel[TheLine.Level] :\n"
4620       "                              TheLine * 2,\n"
4621       "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
4622       Style);
4623   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
4624                "                  aaaaaaaaaaaaaaa :\n"
4625                "                  bbbbbbbbbbbbbbb ? //\n"
4626                "                      ccccccccccccccc :\n"
4627                "                      ddddddddddddddd;",
4628                Style);
4629   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
4630                "                  aaaaaaaaaaaaaaa :\n"
4631                "                  (bbbbbbbbbbbbbbb ? //\n"
4632                "                       ccccccccccccccc :\n"
4633                "                       ddddddddddddddd);",
4634                Style);
4635 }
4636
4637 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
4638   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
4639                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
4640   verifyFormat("bool a = true, b = false;");
4641
4642   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4643                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
4644                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
4645                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
4646   verifyFormat(
4647       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
4648       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
4649       "     d = e && f;");
4650   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
4651                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
4652   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
4653                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
4654   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
4655                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
4656
4657   FormatStyle Style = getGoogleStyle();
4658   Style.PointerAlignment = FormatStyle::PAS_Left;
4659   Style.DerivePointerAlignment = false;
4660   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4661                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
4662                "    *b = bbbbbbbbbbbbbbbbbbb;",
4663                Style);
4664   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
4665                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
4666                Style);
4667 }
4668
4669 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
4670   verifyFormat("arr[foo ? bar : baz];");
4671   verifyFormat("f()[foo ? bar : baz];");
4672   verifyFormat("(a + b)[foo ? bar : baz];");
4673   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
4674 }
4675
4676 TEST_F(FormatTest, AlignsStringLiterals) {
4677   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
4678                "                                      \"short literal\");");
4679   verifyFormat(
4680       "looooooooooooooooooooooooongFunction(\n"
4681       "    \"short literal\"\n"
4682       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
4683   verifyFormat("someFunction(\"Always break between multi-line\"\n"
4684                "             \" string literals\",\n"
4685                "             and, other, parameters);");
4686   EXPECT_EQ("fun + \"1243\" /* comment */\n"
4687             "      \"5678\";",
4688             format("fun + \"1243\" /* comment */\n"
4689                    "      \"5678\";",
4690                    getLLVMStyleWithColumns(28)));
4691   EXPECT_EQ(
4692       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
4693       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
4694       "         \"aaaaaaaaaaaaaaaa\";",
4695       format("aaaaaa ="
4696              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
4697              "aaaaaaaaaaaaaaaaaaaaa\" "
4698              "\"aaaaaaaaaaaaaaaa\";"));
4699   verifyFormat("a = a + \"a\"\n"
4700                "        \"a\"\n"
4701                "        \"a\";");
4702   verifyFormat("f(\"a\", \"b\"\n"
4703                "       \"c\");");
4704
4705   verifyFormat(
4706       "#define LL_FORMAT \"ll\"\n"
4707       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
4708       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
4709
4710   verifyFormat("#define A(X)          \\\n"
4711                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
4712                "  \"ccccc\"",
4713                getLLVMStyleWithColumns(23));
4714   verifyFormat("#define A \"def\"\n"
4715                "f(\"abc\" A \"ghi\"\n"
4716                "  \"jkl\");");
4717
4718   verifyFormat("f(L\"a\"\n"
4719                "  L\"b\");");
4720   verifyFormat("#define A(X)            \\\n"
4721                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
4722                "  L\"ccccc\"",
4723                getLLVMStyleWithColumns(25));
4724
4725   verifyFormat("f(@\"a\"\n"
4726                "  @\"b\");");
4727   verifyFormat("NSString s = @\"a\"\n"
4728                "             @\"b\"\n"
4729                "             @\"c\";");
4730   verifyFormat("NSString s = @\"a\"\n"
4731                "              \"b\"\n"
4732                "              \"c\";");
4733 }
4734
4735 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
4736   FormatStyle Style = getLLVMStyle();
4737   // No declarations or definitions should be moved to own line.
4738   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
4739   verifyFormat("class A {\n"
4740                "  int f() { return 1; }\n"
4741                "  int g();\n"
4742                "};\n"
4743                "int f() { return 1; }\n"
4744                "int g();\n",
4745                Style);
4746
4747   // All declarations and definitions should have the return type moved to its
4748   // own
4749   // line.
4750   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
4751   verifyFormat("class E {\n"
4752                "  int\n"
4753                "  f() {\n"
4754                "    return 1;\n"
4755                "  }\n"
4756                "  int\n"
4757                "  g();\n"
4758                "};\n"
4759                "int\n"
4760                "f() {\n"
4761                "  return 1;\n"
4762                "}\n"
4763                "int\n"
4764                "g();\n",
4765                Style);
4766
4767   // Top-level definitions, and no kinds of declarations should have the
4768   // return type moved to its own line.
4769   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
4770   verifyFormat("class B {\n"
4771                "  int f() { return 1; }\n"
4772                "  int g();\n"
4773                "};\n"
4774                "int\n"
4775                "f() {\n"
4776                "  return 1;\n"
4777                "}\n"
4778                "int g();\n",
4779                Style);
4780
4781   // Top-level definitions and declarations should have the return type moved
4782   // to its own line.
4783   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
4784   verifyFormat("class C {\n"
4785                "  int f() { return 1; }\n"
4786                "  int g();\n"
4787                "};\n"
4788                "int\n"
4789                "f() {\n"
4790                "  return 1;\n"
4791                "}\n"
4792                "int\n"
4793                "g();\n",
4794                Style);
4795
4796   // All definitions should have the return type moved to its own line, but no
4797   // kinds of declarations.
4798   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
4799   verifyFormat("class D {\n"
4800                "  int\n"
4801                "  f() {\n"
4802                "    return 1;\n"
4803                "  }\n"
4804                "  int g();\n"
4805                "};\n"
4806                "int\n"
4807                "f() {\n"
4808                "  return 1;\n"
4809                "}\n"
4810                "int g();\n",
4811                Style);
4812   verifyFormat("const char *\n"
4813                "f(void) {\n" // Break here.
4814                "  return \"\";\n"
4815                "}\n"
4816                "const char *bar(void);\n", // No break here.
4817                Style);
4818   verifyFormat("template <class T>\n"
4819                "T *\n"
4820                "f(T &c) {\n" // Break here.
4821                "  return NULL;\n"
4822                "}\n"
4823                "template <class T> T *f(T &c);\n", // No break here.
4824                Style);
4825   verifyFormat("class C {\n"
4826                "  int\n"
4827                "  operator+() {\n"
4828                "    return 1;\n"
4829                "  }\n"
4830                "  int\n"
4831                "  operator()() {\n"
4832                "    return 1;\n"
4833                "  }\n"
4834                "};\n",
4835                Style);
4836   verifyFormat("void\n"
4837                "A::operator()() {}\n"
4838                "void\n"
4839                "A::operator>>() {}\n"
4840                "void\n"
4841                "A::operator+() {}\n",
4842                Style);
4843   verifyFormat("void *operator new(std::size_t s);", // No break here.
4844                Style);
4845   verifyFormat("void *\n"
4846                "operator new(std::size_t s) {}",
4847                Style);
4848   verifyFormat("void *\n"
4849                "operator delete[](void *ptr) {}",
4850                Style);
4851   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4852   verifyFormat("const char *\n"
4853                "f(void)\n" // Break here.
4854                "{\n"
4855                "  return \"\";\n"
4856                "}\n"
4857                "const char *bar(void);\n", // No break here.
4858                Style);
4859   verifyFormat("template <class T>\n"
4860                "T *\n"     // Problem here: no line break
4861                "f(T &c)\n" // Break here.
4862                "{\n"
4863                "  return NULL;\n"
4864                "}\n"
4865                "template <class T> T *f(T &c);\n", // No break here.
4866                Style);
4867 }
4868
4869 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
4870   FormatStyle NoBreak = getLLVMStyle();
4871   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
4872   FormatStyle Break = getLLVMStyle();
4873   Break.AlwaysBreakBeforeMultilineStrings = true;
4874   verifyFormat("aaaa = \"bbbb\"\n"
4875                "       \"cccc\";",
4876                NoBreak);
4877   verifyFormat("aaaa =\n"
4878                "    \"bbbb\"\n"
4879                "    \"cccc\";",
4880                Break);
4881   verifyFormat("aaaa(\"bbbb\"\n"
4882                "     \"cccc\");",
4883                NoBreak);
4884   verifyFormat("aaaa(\n"
4885                "    \"bbbb\"\n"
4886                "    \"cccc\");",
4887                Break);
4888   verifyFormat("aaaa(qqq, \"bbbb\"\n"
4889                "          \"cccc\");",
4890                NoBreak);
4891   verifyFormat("aaaa(qqq,\n"
4892                "     \"bbbb\"\n"
4893                "     \"cccc\");",
4894                Break);
4895   verifyFormat("aaaa(qqq,\n"
4896                "     L\"bbbb\"\n"
4897                "     L\"cccc\");",
4898                Break);
4899   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
4900                "                      \"bbbb\"));",
4901                Break);
4902   verifyFormat("string s = someFunction(\n"
4903                "    \"abc\"\n"
4904                "    \"abc\");",
4905                Break);
4906
4907   // As we break before unary operators, breaking right after them is bad.
4908   verifyFormat("string foo = abc ? \"x\"\n"
4909                "                   \"blah blah blah blah blah blah\"\n"
4910                "                 : \"y\";",
4911                Break);
4912
4913   // Don't break if there is no column gain.
4914   verifyFormat("f(\"aaaa\"\n"
4915                "  \"bbbb\");",
4916                Break);
4917
4918   // Treat literals with escaped newlines like multi-line string literals.
4919   EXPECT_EQ("x = \"a\\\n"
4920             "b\\\n"
4921             "c\";",
4922             format("x = \"a\\\n"
4923                    "b\\\n"
4924                    "c\";",
4925                    NoBreak));
4926   EXPECT_EQ("xxxx =\n"
4927             "    \"a\\\n"
4928             "b\\\n"
4929             "c\";",
4930             format("xxxx = \"a\\\n"
4931                    "b\\\n"
4932                    "c\";",
4933                    Break));
4934
4935   // Exempt ObjC strings for now.
4936   EXPECT_EQ("NSString *const kString = @\"aaaa\"\n"
4937             "                          @\"bbbb\";",
4938             format("NSString *const kString = @\"aaaa\"\n"
4939                    "@\"bbbb\";",
4940                    Break));
4941
4942   Break.ColumnLimit = 0;
4943   verifyFormat("const char *hello = \"hello llvm\";", Break);
4944 }
4945
4946 TEST_F(FormatTest, AlignsPipes) {
4947   verifyFormat(
4948       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4949       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4950       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4951   verifyFormat(
4952       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
4953       "                     << aaaaaaaaaaaaaaaaaaaa;");
4954   verifyFormat(
4955       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4956       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4957   verifyFormat(
4958       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
4959       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
4960       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
4961   verifyFormat(
4962       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4963       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4964       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4965   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4966                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4967                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4968                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
4969   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
4970                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
4971   verifyFormat(
4972       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4973       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
4974
4975   verifyFormat("return out << \"somepacket = {\\n\"\n"
4976                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
4977                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
4978                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
4979                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
4980                "           << \"}\";");
4981
4982   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
4983                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
4984                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
4985   verifyFormat(
4986       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
4987       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
4988       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
4989       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
4990       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
4991   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
4992                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
4993   verifyFormat(
4994       "void f() {\n"
4995       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
4996       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
4997       "}");
4998   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
4999                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
5000   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5001                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5002                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
5003                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
5004   verifyFormat("LOG_IF(aaa == //\n"
5005                "       bbb)\n"
5006                "    << a << b;");
5007
5008   // Breaking before the first "<<" is generally not desirable.
5009   verifyFormat(
5010       "llvm::errs()\n"
5011       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5012       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5013       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5014       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5015       getLLVMStyleWithColumns(70));
5016   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
5017                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5018                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
5019                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5020                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
5021                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5022                getLLVMStyleWithColumns(70));
5023
5024   // But sometimes, breaking before the first "<<" is desirable.
5025   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
5026                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
5027   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
5028                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5029                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5030   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
5031                "    << BEF << IsTemplate << Description << E->getType();");
5032
5033   verifyFormat(
5034       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5035       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5036
5037   // Incomplete string literal.
5038   EXPECT_EQ("llvm::errs() << \"\n"
5039             "             << a;",
5040             format("llvm::errs() << \"\n<<a;"));
5041
5042   verifyFormat("void f() {\n"
5043                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
5044                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
5045                "}");
5046
5047   // Handle 'endl'.
5048   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
5049                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
5050   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
5051 }
5052
5053 TEST_F(FormatTest, UnderstandsEquals) {
5054   verifyFormat(
5055       "aaaaaaaaaaaaaaaaa =\n"
5056       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5057   verifyFormat(
5058       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5059       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
5060   verifyFormat(
5061       "if (a) {\n"
5062       "  f();\n"
5063       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5064       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
5065       "}");
5066
5067   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5068                "        100000000 + 10000000) {\n}");
5069 }
5070
5071 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
5072   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
5073                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
5074
5075   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
5076                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
5077
5078   verifyFormat(
5079       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
5080       "                                                          Parameter2);");
5081
5082   verifyFormat(
5083       "ShortObject->shortFunction(\n"
5084       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
5085       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
5086
5087   verifyFormat("loooooooooooooongFunction(\n"
5088                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
5089
5090   verifyFormat(
5091       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
5092       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
5093
5094   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
5095                "    .WillRepeatedly(Return(SomeValue));");
5096   verifyFormat("void f() {\n"
5097                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
5098                "      .Times(2)\n"
5099                "      .WillRepeatedly(Return(SomeValue));\n"
5100                "}");
5101   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
5102                "    ccccccccccccccccccccccc);");
5103   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5104                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5105                "          .aaaaa(aaaaa),\n"
5106                "      aaaaaaaaaaaaaaaaaaaaa);");
5107   verifyFormat("void f() {\n"
5108                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5109                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
5110                "}");
5111   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5112                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5113                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5114                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5115                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5116   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5117                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5118                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5119                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
5120                "}");
5121
5122   // Here, it is not necessary to wrap at "." or "->".
5123   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
5124                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
5125   verifyFormat(
5126       "aaaaaaaaaaa->aaaaaaaaa(\n"
5127       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5128       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
5129
5130   verifyFormat(
5131       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5132       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
5133   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
5134                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
5135   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
5136                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
5137
5138   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5139                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5140                "    .a();");
5141
5142   FormatStyle NoBinPacking = getLLVMStyle();
5143   NoBinPacking.BinPackParameters = false;
5144   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
5145                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
5146                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
5147                "                         aaaaaaaaaaaaaaaaaaa,\n"
5148                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5149                NoBinPacking);
5150
5151   // If there is a subsequent call, change to hanging indentation.
5152   verifyFormat(
5153       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5154       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
5155       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5156   verifyFormat(
5157       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5158       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
5159   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5160                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5161                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5162   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5163                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5164                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
5165 }
5166
5167 TEST_F(FormatTest, WrapsTemplateDeclarations) {
5168   verifyFormat("template <typename T>\n"
5169                "virtual void loooooooooooongFunction(int Param1, int Param2);");
5170   verifyFormat("template <typename T>\n"
5171                "// T should be one of {A, B}.\n"
5172                "virtual void loooooooooooongFunction(int Param1, int Param2);");
5173   verifyFormat(
5174       "template <typename T>\n"
5175       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
5176   verifyFormat("template <typename T>\n"
5177                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
5178                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
5179   verifyFormat(
5180       "template <typename T>\n"
5181       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
5182       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
5183   verifyFormat(
5184       "template <typename T>\n"
5185       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
5186       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
5187       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5188   verifyFormat("template <typename T>\n"
5189                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5190                "    int aaaaaaaaaaaaaaaaaaaaaa);");
5191   verifyFormat(
5192       "template <typename T1, typename T2 = char, typename T3 = char,\n"
5193       "          typename T4 = char>\n"
5194       "void f();");
5195   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
5196                "          template <typename> class cccccccccccccccccccccc,\n"
5197                "          typename ddddddddddddd>\n"
5198                "class C {};");
5199   verifyFormat(
5200       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
5201       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5202
5203   verifyFormat("void f() {\n"
5204                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
5205                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
5206                "}");
5207
5208   verifyFormat("template <typename T> class C {};");
5209   verifyFormat("template <typename T> void f();");
5210   verifyFormat("template <typename T> void f() {}");
5211   verifyFormat(
5212       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
5213       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5214       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
5215       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
5216       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5217       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
5218       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
5219       getLLVMStyleWithColumns(72));
5220   EXPECT_EQ("static_cast<A< //\n"
5221             "    B> *>(\n"
5222             "\n"
5223             "    );",
5224             format("static_cast<A<//\n"
5225                    "    B>*>(\n"
5226                    "\n"
5227                    "    );"));
5228   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5229                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
5230
5231   FormatStyle AlwaysBreak = getLLVMStyle();
5232   AlwaysBreak.AlwaysBreakTemplateDeclarations = true;
5233   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
5234   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
5235   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
5236   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5237                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
5238                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
5239   verifyFormat("template <template <typename> class Fooooooo,\n"
5240                "          template <typename> class Baaaaaaar>\n"
5241                "struct C {};",
5242                AlwaysBreak);
5243   verifyFormat("template <typename T> // T can be A, B or C.\n"
5244                "struct C {};",
5245                AlwaysBreak);
5246 }
5247
5248 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
5249   verifyFormat(
5250       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5251       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5252   verifyFormat(
5253       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5254       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5255       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
5256
5257   // FIXME: Should we have the extra indent after the second break?
5258   verifyFormat(
5259       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5260       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5261       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5262
5263   verifyFormat(
5264       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
5265       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
5266
5267   // Breaking at nested name specifiers is generally not desirable.
5268   verifyFormat(
5269       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5270       "    aaaaaaaaaaaaaaaaaaaaaaa);");
5271
5272   verifyFormat(
5273       "aaaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5274       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5275       "                   aaaaaaaaaaaaaaaaaaaaa);",
5276       getLLVMStyleWithColumns(74));
5277
5278   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
5279                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5280                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5281 }
5282
5283 TEST_F(FormatTest, UnderstandsTemplateParameters) {
5284   verifyFormat("A<int> a;");
5285   verifyFormat("A<A<A<int>>> a;");
5286   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
5287   verifyFormat("bool x = a < 1 || 2 > a;");
5288   verifyFormat("bool x = 5 < f<int>();");
5289   verifyFormat("bool x = f<int>() > 5;");
5290   verifyFormat("bool x = 5 < a<int>::x;");
5291   verifyFormat("bool x = a < 4 ? a > 2 : false;");
5292   verifyFormat("bool x = f() ? a < 2 : a > 2;");
5293
5294   verifyGoogleFormat("A<A<int>> a;");
5295   verifyGoogleFormat("A<A<A<int>>> a;");
5296   verifyGoogleFormat("A<A<A<A<int>>>> a;");
5297   verifyGoogleFormat("A<A<int> > a;");
5298   verifyGoogleFormat("A<A<A<int> > > a;");
5299   verifyGoogleFormat("A<A<A<A<int> > > > a;");
5300   verifyGoogleFormat("A<::A<int>> a;");
5301   verifyGoogleFormat("A<::A> a;");
5302   verifyGoogleFormat("A< ::A> a;");
5303   verifyGoogleFormat("A< ::A<int> > a;");
5304   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
5305   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
5306   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
5307   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
5308   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
5309             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
5310
5311   verifyFormat("A<A>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
5312
5313   verifyFormat("test >> a >> b;");
5314   verifyFormat("test << a >> b;");
5315
5316   verifyFormat("f<int>();");
5317   verifyFormat("template <typename T> void f() {}");
5318   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
5319   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
5320                "sizeof(char)>::type>;");
5321   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
5322
5323   // Not template parameters.
5324   verifyFormat("return a < b && c > d;");
5325   verifyFormat("void f() {\n"
5326                "  while (a < b && c > d) {\n"
5327                "  }\n"
5328                "}");
5329   verifyFormat("template <typename... Types>\n"
5330                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
5331
5332   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5333                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
5334                getLLVMStyleWithColumns(60));
5335   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
5336   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
5337   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
5338 }
5339
5340 TEST_F(FormatTest, UnderstandsBinaryOperators) {
5341   verifyFormat("COMPARE(a, ==, b);");
5342 }
5343
5344 TEST_F(FormatTest, UnderstandsPointersToMembers) {
5345   verifyFormat("int A::*x;");
5346   verifyFormat("int (S::*func)(void *);");
5347   verifyFormat("void f() { int (S::*func)(void *); }");
5348   verifyFormat("typedef bool *(Class::*Member)() const;");
5349   verifyFormat("void f() {\n"
5350                "  (a->*f)();\n"
5351                "  a->*x;\n"
5352                "  (a.*f)();\n"
5353                "  ((*a).*f)();\n"
5354                "  a.*x;\n"
5355                "}");
5356   verifyFormat("void f() {\n"
5357                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
5358                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
5359                "}");
5360   verifyFormat(
5361       "(aaaaaaaaaa->*bbbbbbb)(\n"
5362       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5363   FormatStyle Style = getLLVMStyle();
5364   Style.PointerAlignment = FormatStyle::PAS_Left;
5365   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
5366 }
5367
5368 TEST_F(FormatTest, UnderstandsUnaryOperators) {
5369   verifyFormat("int a = -2;");
5370   verifyFormat("f(-1, -2, -3);");
5371   verifyFormat("a[-1] = 5;");
5372   verifyFormat("int a = 5 + -2;");
5373   verifyFormat("if (i == -1) {\n}");
5374   verifyFormat("if (i != -1) {\n}");
5375   verifyFormat("if (i > -1) {\n}");
5376   verifyFormat("if (i < -1) {\n}");
5377   verifyFormat("++(a->f());");
5378   verifyFormat("--(a->f());");
5379   verifyFormat("(a->f())++;");
5380   verifyFormat("a[42]++;");
5381   verifyFormat("if (!(a->f())) {\n}");
5382
5383   verifyFormat("a-- > b;");
5384   verifyFormat("b ? -a : c;");
5385   verifyFormat("n * sizeof char16;");
5386   verifyFormat("n * alignof char16;", getGoogleStyle());
5387   verifyFormat("sizeof(char);");
5388   verifyFormat("alignof(char);", getGoogleStyle());
5389
5390   verifyFormat("return -1;");
5391   verifyFormat("switch (a) {\n"
5392                "case -1:\n"
5393                "  break;\n"
5394                "}");
5395   verifyFormat("#define X -1");
5396   verifyFormat("#define X -kConstant");
5397
5398   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
5399   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
5400
5401   verifyFormat("int a = /* confusing comment */ -1;");
5402   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
5403   verifyFormat("int a = i /* confusing comment */++;");
5404 }
5405
5406 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
5407   verifyFormat("if (!aaaaaaaaaa( // break\n"
5408                "        aaaaa)) {\n"
5409                "}");
5410   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
5411                "    aaaaa));");
5412   verifyFormat("*aaa = aaaaaaa( // break\n"
5413                "    bbbbbb);");
5414 }
5415
5416 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
5417   verifyFormat("bool operator<();");
5418   verifyFormat("bool operator>();");
5419   verifyFormat("bool operator=();");
5420   verifyFormat("bool operator==();");
5421   verifyFormat("bool operator!=();");
5422   verifyFormat("int operator+();");
5423   verifyFormat("int operator++();");
5424   verifyFormat("bool operator();");
5425   verifyFormat("bool operator()();");
5426   verifyFormat("bool operator[]();");
5427   verifyFormat("operator bool();");
5428   verifyFormat("operator int();");
5429   verifyFormat("operator void *();");
5430   verifyFormat("operator SomeType<int>();");
5431   verifyFormat("operator SomeType<int, int>();");
5432   verifyFormat("operator SomeType<SomeType<int>>();");
5433   verifyFormat("void *operator new(std::size_t size);");
5434   verifyFormat("void *operator new[](std::size_t size);");
5435   verifyFormat("void operator delete(void *ptr);");
5436   verifyFormat("void operator delete[](void *ptr);");
5437   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
5438                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
5439
5440   verifyFormat(
5441       "ostream &operator<<(ostream &OutputStream,\n"
5442       "                    SomeReallyLongType WithSomeReallyLongValue);");
5443   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
5444                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
5445                "  return left.group < right.group;\n"
5446                "}");
5447   verifyFormat("SomeType &operator=(const SomeType &S);");
5448   verifyFormat("f.template operator()<int>();");
5449
5450   verifyGoogleFormat("operator void*();");
5451   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
5452   verifyGoogleFormat("operator ::A();");
5453
5454   verifyFormat("using A::operator+;");
5455   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
5456                "int i;");
5457 }
5458
5459 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
5460   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
5461   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
5462   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
5463   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
5464   verifyFormat("Deleted &operator=(const Deleted &) &;");
5465   verifyFormat("Deleted &operator=(const Deleted &) &&;");
5466   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
5467   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
5468   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
5469   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
5470   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
5471
5472   FormatStyle AlignLeft = getLLVMStyle();
5473   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
5474   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
5475   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
5476                AlignLeft);
5477   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
5478   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
5479
5480   FormatStyle Spaces = getLLVMStyle();
5481   Spaces.SpacesInCStyleCastParentheses = true;
5482   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
5483   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
5484   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
5485   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
5486
5487   Spaces.SpacesInCStyleCastParentheses = false;
5488   Spaces.SpacesInParentheses = true;
5489   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
5490   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;", Spaces);
5491   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
5492   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
5493 }
5494
5495 TEST_F(FormatTest, UnderstandsNewAndDelete) {
5496   verifyFormat("void f() {\n"
5497                "  A *a = new A;\n"
5498                "  A *a = new (placement) A;\n"
5499                "  delete a;\n"
5500                "  delete (A *)a;\n"
5501                "}");
5502   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
5503                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
5504   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5505                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
5506                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
5507   verifyFormat("delete[] h->p;");
5508 }
5509
5510 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
5511   verifyFormat("int *f(int *a) {}");
5512   verifyFormat("int main(int argc, char **argv) {}");
5513   verifyFormat("Test::Test(int b) : a(b * b) {}");
5514   verifyIndependentOfContext("f(a, *a);");
5515   verifyFormat("void g() { f(*a); }");
5516   verifyIndependentOfContext("int a = b * 10;");
5517   verifyIndependentOfContext("int a = 10 * b;");
5518   verifyIndependentOfContext("int a = b * c;");
5519   verifyIndependentOfContext("int a += b * c;");
5520   verifyIndependentOfContext("int a -= b * c;");
5521   verifyIndependentOfContext("int a *= b * c;");
5522   verifyIndependentOfContext("int a /= b * c;");
5523   verifyIndependentOfContext("int a = *b;");
5524   verifyIndependentOfContext("int a = *b * c;");
5525   verifyIndependentOfContext("int a = b * *c;");
5526   verifyIndependentOfContext("int a = b * (10);");
5527   verifyIndependentOfContext("S << b * (10);");
5528   verifyIndependentOfContext("return 10 * b;");
5529   verifyIndependentOfContext("return *b * *c;");
5530   verifyIndependentOfContext("return a & ~b;");
5531   verifyIndependentOfContext("f(b ? *c : *d);");
5532   verifyIndependentOfContext("int a = b ? *c : *d;");
5533   verifyIndependentOfContext("*b = a;");
5534   verifyIndependentOfContext("a * ~b;");
5535   verifyIndependentOfContext("a * !b;");
5536   verifyIndependentOfContext("a * +b;");
5537   verifyIndependentOfContext("a * -b;");
5538   verifyIndependentOfContext("a * ++b;");
5539   verifyIndependentOfContext("a * --b;");
5540   verifyIndependentOfContext("a[4] * b;");
5541   verifyIndependentOfContext("a[a * a] = 1;");
5542   verifyIndependentOfContext("f() * b;");
5543   verifyIndependentOfContext("a * [self dostuff];");
5544   verifyIndependentOfContext("int x = a * (a + b);");
5545   verifyIndependentOfContext("(a *)(a + b);");
5546   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
5547   verifyIndependentOfContext("int *pa = (int *)&a;");
5548   verifyIndependentOfContext("return sizeof(int **);");
5549   verifyIndependentOfContext("return sizeof(int ******);");
5550   verifyIndependentOfContext("return (int **&)a;");
5551   verifyIndependentOfContext("f((*PointerToArray)[10]);");
5552   verifyFormat("void f(Type (*parameter)[10]) {}");
5553   verifyFormat("void f(Type (&parameter)[10]) {}");
5554   verifyGoogleFormat("return sizeof(int**);");
5555   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
5556   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
5557   verifyFormat("auto a = [](int **&, int ***) {};");
5558   verifyFormat("auto PointerBinding = [](const char *S) {};");
5559   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
5560   verifyFormat("[](const decltype(*a) &value) {}");
5561   verifyFormat("decltype(a * b) F();");
5562   verifyFormat("#define MACRO() [](A *a) { return 1; }");
5563   verifyIndependentOfContext("typedef void (*f)(int *a);");
5564   verifyIndependentOfContext("int i{a * b};");
5565   verifyIndependentOfContext("aaa && aaa->f();");
5566   verifyIndependentOfContext("int x = ~*p;");
5567   verifyFormat("Constructor() : a(a), area(width * height) {}");
5568   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
5569   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
5570   verifyFormat("void f() { f(a, c * d); }");
5571   verifyFormat("void f() { f(new a(), c * d); }");
5572
5573   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
5574
5575   verifyIndependentOfContext("A<int *> a;");
5576   verifyIndependentOfContext("A<int **> a;");
5577   verifyIndependentOfContext("A<int *, int *> a;");
5578   verifyIndependentOfContext("A<int *[]> a;");
5579   verifyIndependentOfContext(
5580       "const char *const p = reinterpret_cast<const char *const>(q);");
5581   verifyIndependentOfContext("A<int **, int **> a;");
5582   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
5583   verifyFormat("for (char **a = b; *a; ++a) {\n}");
5584   verifyFormat("for (; a && b;) {\n}");
5585   verifyFormat("bool foo = true && [] { return false; }();");
5586
5587   verifyFormat(
5588       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5589       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5590
5591   verifyGoogleFormat("**outparam = 1;");
5592   verifyGoogleFormat("*outparam = a * b;");
5593   verifyGoogleFormat("int main(int argc, char** argv) {}");
5594   verifyGoogleFormat("A<int*> a;");
5595   verifyGoogleFormat("A<int**> a;");
5596   verifyGoogleFormat("A<int*, int*> a;");
5597   verifyGoogleFormat("A<int**, int**> a;");
5598   verifyGoogleFormat("f(b ? *c : *d);");
5599   verifyGoogleFormat("int a = b ? *c : *d;");
5600   verifyGoogleFormat("Type* t = **x;");
5601   verifyGoogleFormat("Type* t = *++*x;");
5602   verifyGoogleFormat("*++*x;");
5603   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
5604   verifyGoogleFormat("Type* t = x++ * y;");
5605   verifyGoogleFormat(
5606       "const char* const p = reinterpret_cast<const char* const>(q);");
5607   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
5608   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
5609   verifyGoogleFormat("template <typename T>\n"
5610                      "void f(int i = 0, SomeType** temps = NULL);");
5611
5612   FormatStyle Left = getLLVMStyle();
5613   Left.PointerAlignment = FormatStyle::PAS_Left;
5614   verifyFormat("x = *a(x) = *a(y);", Left);
5615   verifyFormat("for (;; * = b) {\n}", Left);
5616   verifyFormat("return *this += 1;", Left);
5617
5618   verifyIndependentOfContext("a = *(x + y);");
5619   verifyIndependentOfContext("a = &(x + y);");
5620   verifyIndependentOfContext("*(x + y).call();");
5621   verifyIndependentOfContext("&(x + y)->call();");
5622   verifyFormat("void f() { &(*I).first; }");
5623
5624   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
5625   verifyFormat(
5626       "int *MyValues = {\n"
5627       "    *A, // Operator detection might be confused by the '{'\n"
5628       "    *BB // Operator detection might be confused by previous comment\n"
5629       "};");
5630
5631   verifyIndependentOfContext("if (int *a = &b)");
5632   verifyIndependentOfContext("if (int &a = *b)");
5633   verifyIndependentOfContext("if (a & b[i])");
5634   verifyIndependentOfContext("if (a::b::c::d & b[i])");
5635   verifyIndependentOfContext("if (*b[i])");
5636   verifyIndependentOfContext("if (int *a = (&b))");
5637   verifyIndependentOfContext("while (int *a = &b)");
5638   verifyIndependentOfContext("size = sizeof *a;");
5639   verifyIndependentOfContext("if (a && (b = c))");
5640   verifyFormat("void f() {\n"
5641                "  for (const int &v : Values) {\n"
5642                "  }\n"
5643                "}");
5644   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
5645   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
5646   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
5647
5648   verifyFormat("#define A (!a * b)");
5649   verifyFormat("#define MACRO     \\\n"
5650                "  int *i = a * b; \\\n"
5651                "  void f(a *b);",
5652                getLLVMStyleWithColumns(19));
5653
5654   verifyIndependentOfContext("A = new SomeType *[Length];");
5655   verifyIndependentOfContext("A = new SomeType *[Length]();");
5656   verifyIndependentOfContext("T **t = new T *;");
5657   verifyIndependentOfContext("T **t = new T *();");
5658   verifyGoogleFormat("A = new SomeType*[Length]();");
5659   verifyGoogleFormat("A = new SomeType*[Length];");
5660   verifyGoogleFormat("T** t = new T*;");
5661   verifyGoogleFormat("T** t = new T*();");
5662
5663   FormatStyle PointerLeft = getLLVMStyle();
5664   PointerLeft.PointerAlignment = FormatStyle::PAS_Left;
5665   verifyFormat("delete *x;", PointerLeft);
5666   verifyFormat("STATIC_ASSERT((a & b) == 0);");
5667   verifyFormat("STATIC_ASSERT(0 == (a & b));");
5668   verifyFormat("template <bool a, bool b> "
5669                "typename t::if<x && y>::type f() {}");
5670   verifyFormat("template <int *y> f() {}");
5671   verifyFormat("vector<int *> v;");
5672   verifyFormat("vector<int *const> v;");
5673   verifyFormat("vector<int *const **const *> v;");
5674   verifyFormat("vector<int *volatile> v;");
5675   verifyFormat("vector<a * b> v;");
5676   verifyFormat("foo<b && false>();");
5677   verifyFormat("foo<b & 1>();");
5678   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
5679   verifyFormat(
5680       "template <class T, class = typename std::enable_if<\n"
5681       "                       std::is_integral<T>::value &&\n"
5682       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
5683       "void F();",
5684       getLLVMStyleWithColumns(76));
5685   verifyFormat(
5686       "template <class T,\n"
5687       "          class = typename ::std::enable_if<\n"
5688       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
5689       "void F();",
5690       getGoogleStyleWithColumns(68));
5691
5692   verifyIndependentOfContext("MACRO(int *i);");
5693   verifyIndependentOfContext("MACRO(auto *a);");
5694   verifyIndependentOfContext("MACRO(const A *a);");
5695   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
5696   // FIXME: Is there a way to make this work?
5697   // verifyIndependentOfContext("MACRO(A *a);");
5698
5699   verifyFormat("DatumHandle const *operator->() const { return input_; }");
5700   verifyFormat("return options != nullptr && operator==(*options);");
5701
5702   EXPECT_EQ("#define OP(x)                                    \\\n"
5703             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
5704             "    return s << a.DebugString();                 \\\n"
5705             "  }",
5706             format("#define OP(x) \\\n"
5707                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
5708                    "    return s << a.DebugString(); \\\n"
5709                    "  }",
5710                    getLLVMStyleWithColumns(50)));
5711
5712   // FIXME: We cannot handle this case yet; we might be able to figure out that
5713   // foo<x> d > v; doesn't make sense.
5714   verifyFormat("foo<a<b && c> d> v;");
5715
5716   FormatStyle PointerMiddle = getLLVMStyle();
5717   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
5718   verifyFormat("delete *x;", PointerMiddle);
5719   verifyFormat("int * x;", PointerMiddle);
5720   verifyFormat("template <int * y> f() {}", PointerMiddle);
5721   verifyFormat("int * f(int * a) {}", PointerMiddle);
5722   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
5723   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
5724   verifyFormat("A<int *> a;", PointerMiddle);
5725   verifyFormat("A<int **> a;", PointerMiddle);
5726   verifyFormat("A<int *, int *> a;", PointerMiddle);
5727   verifyFormat("A<int * []> a;", PointerMiddle);
5728   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
5729   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
5730   verifyFormat("T ** t = new T *;", PointerMiddle);
5731
5732   // Member function reference qualifiers aren't binary operators.
5733   verifyFormat("string // break\n"
5734                "operator()() & {}");
5735   verifyFormat("string // break\n"
5736                "operator()() && {}");
5737   verifyGoogleFormat("template <typename T>\n"
5738                      "auto x() & -> int {}");
5739 }
5740
5741 TEST_F(FormatTest, UnderstandsAttributes) {
5742   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
5743   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
5744                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
5745   FormatStyle AfterType = getLLVMStyle();
5746   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
5747   verifyFormat("__attribute__((nodebug)) void\n"
5748                "foo() {}\n",
5749                AfterType);
5750 }
5751
5752 TEST_F(FormatTest, UnderstandsEllipsis) {
5753   verifyFormat("int printf(const char *fmt, ...);");
5754   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
5755   verifyFormat("template <class... Ts> void Foo(Ts *... ts) {}");
5756
5757   FormatStyle PointersLeft = getLLVMStyle();
5758   PointersLeft.PointerAlignment = FormatStyle::PAS_Left;
5759   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", PointersLeft);
5760 }
5761
5762 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
5763   EXPECT_EQ("int *a;\n"
5764             "int *a;\n"
5765             "int *a;",
5766             format("int *a;\n"
5767                    "int* a;\n"
5768                    "int *a;",
5769                    getGoogleStyle()));
5770   EXPECT_EQ("int* a;\n"
5771             "int* a;\n"
5772             "int* a;",
5773             format("int* a;\n"
5774                    "int* a;\n"
5775                    "int *a;",
5776                    getGoogleStyle()));
5777   EXPECT_EQ("int *a;\n"
5778             "int *a;\n"
5779             "int *a;",
5780             format("int *a;\n"
5781                    "int * a;\n"
5782                    "int *  a;",
5783                    getGoogleStyle()));
5784   EXPECT_EQ("auto x = [] {\n"
5785             "  int *a;\n"
5786             "  int *a;\n"
5787             "  int *a;\n"
5788             "};",
5789             format("auto x=[]{int *a;\n"
5790                    "int * a;\n"
5791                    "int *  a;};",
5792                    getGoogleStyle()));
5793 }
5794
5795 TEST_F(FormatTest, UnderstandsRvalueReferences) {
5796   verifyFormat("int f(int &&a) {}");
5797   verifyFormat("int f(int a, char &&b) {}");
5798   verifyFormat("void f() { int &&a = b; }");
5799   verifyGoogleFormat("int f(int a, char&& b) {}");
5800   verifyGoogleFormat("void f() { int&& a = b; }");
5801
5802   verifyIndependentOfContext("A<int &&> a;");
5803   verifyIndependentOfContext("A<int &&, int &&> a;");
5804   verifyGoogleFormat("A<int&&> a;");
5805   verifyGoogleFormat("A<int&&, int&&> a;");
5806
5807   // Not rvalue references:
5808   verifyFormat("template <bool B, bool C> class A {\n"
5809                "  static_assert(B && C, \"Something is wrong\");\n"
5810                "};");
5811   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
5812   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
5813   verifyFormat("#define A(a, b) (a && b)");
5814 }
5815
5816 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
5817   verifyFormat("void f() {\n"
5818                "  x[aaaaaaaaa -\n"
5819                "    b] = 23;\n"
5820                "}",
5821                getLLVMStyleWithColumns(15));
5822 }
5823
5824 TEST_F(FormatTest, FormatsCasts) {
5825   verifyFormat("Type *A = static_cast<Type *>(P);");
5826   verifyFormat("Type *A = (Type *)P;");
5827   verifyFormat("Type *A = (vector<Type *, int *>)P;");
5828   verifyFormat("int a = (int)(2.0f);");
5829   verifyFormat("int a = (int)2.0f;");
5830   verifyFormat("x[(int32)y];");
5831   verifyFormat("x = (int32)y;");
5832   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
5833   verifyFormat("int a = (int)*b;");
5834   verifyFormat("int a = (int)2.0f;");
5835   verifyFormat("int a = (int)~0;");
5836   verifyFormat("int a = (int)++a;");
5837   verifyFormat("int a = (int)sizeof(int);");
5838   verifyFormat("int a = (int)+2;");
5839   verifyFormat("my_int a = (my_int)2.0f;");
5840   verifyFormat("my_int a = (my_int)sizeof(int);");
5841   verifyFormat("return (my_int)aaa;");
5842   verifyFormat("#define x ((int)-1)");
5843   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
5844   verifyFormat("#define p(q) ((int *)&q)");
5845   verifyFormat("fn(a)(b) + 1;");
5846
5847   verifyFormat("void f() { my_int a = (my_int)*b; }");
5848   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
5849   verifyFormat("my_int a = (my_int)~0;");
5850   verifyFormat("my_int a = (my_int)++a;");
5851   verifyFormat("my_int a = (my_int)-2;");
5852   verifyFormat("my_int a = (my_int)1;");
5853   verifyFormat("my_int a = (my_int *)1;");
5854   verifyFormat("my_int a = (const my_int)-1;");
5855   verifyFormat("my_int a = (const my_int *)-1;");
5856   verifyFormat("my_int a = (my_int)(my_int)-1;");
5857   verifyFormat("my_int a = (ns::my_int)-2;");
5858   verifyFormat("case (my_int)ONE:");
5859
5860   // FIXME: single value wrapped with paren will be treated as cast.
5861   verifyFormat("void f(int i = (kValue)*kMask) {}");
5862
5863   verifyFormat("{ (void)F; }");
5864
5865   // Don't break after a cast's
5866   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5867                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
5868                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
5869
5870   // These are not casts.
5871   verifyFormat("void f(int *) {}");
5872   verifyFormat("f(foo)->b;");
5873   verifyFormat("f(foo).b;");
5874   verifyFormat("f(foo)(b);");
5875   verifyFormat("f(foo)[b];");
5876   verifyFormat("[](foo) { return 4; }(bar);");
5877   verifyFormat("(*funptr)(foo)[4];");
5878   verifyFormat("funptrs[4](foo)[4];");
5879   verifyFormat("void f(int *);");
5880   verifyFormat("void f(int *) = 0;");
5881   verifyFormat("void f(SmallVector<int>) {}");
5882   verifyFormat("void f(SmallVector<int>);");
5883   verifyFormat("void f(SmallVector<int>) = 0;");
5884   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
5885   verifyFormat("int a = sizeof(int) * b;");
5886   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
5887   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
5888   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
5889   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
5890
5891   // These are not casts, but at some point were confused with casts.
5892   verifyFormat("virtual void foo(int *) override;");
5893   verifyFormat("virtual void foo(char &) const;");
5894   verifyFormat("virtual void foo(int *a, char *) const;");
5895   verifyFormat("int a = sizeof(int *) + b;");
5896   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
5897   verifyFormat("bool b = f(g<int>) && c;");
5898   verifyFormat("typedef void (*f)(int i) func;");
5899
5900   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
5901                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
5902   // FIXME: The indentation here is not ideal.
5903   verifyFormat(
5904       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5905       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
5906       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
5907 }
5908
5909 TEST_F(FormatTest, FormatsFunctionTypes) {
5910   verifyFormat("A<bool()> a;");
5911   verifyFormat("A<SomeType()> a;");
5912   verifyFormat("A<void (*)(int, std::string)> a;");
5913   verifyFormat("A<void *(int)>;");
5914   verifyFormat("void *(*a)(int *, SomeType *);");
5915   verifyFormat("int (*func)(void *);");
5916   verifyFormat("void f() { int (*func)(void *); }");
5917   verifyFormat("template <class CallbackClass>\n"
5918                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
5919
5920   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
5921   verifyGoogleFormat("void* (*a)(int);");
5922   verifyGoogleFormat(
5923       "template <class CallbackClass>\n"
5924       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
5925
5926   // Other constructs can look somewhat like function types:
5927   verifyFormat("A<sizeof(*x)> a;");
5928   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
5929   verifyFormat("some_var = function(*some_pointer_var)[0];");
5930   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
5931   verifyFormat("int x = f(&h)();");
5932 }
5933
5934 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
5935   verifyFormat("A (*foo_)[6];");
5936   verifyFormat("vector<int> (*foo_)[6];");
5937 }
5938
5939 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
5940   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
5941                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
5942   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
5943                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
5944   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
5945                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
5946
5947   // Different ways of ()-initializiation.
5948   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
5949                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
5950   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
5951                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
5952   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
5953                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
5954   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
5955                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
5956 }
5957
5958 TEST_F(FormatTest, BreaksLongDeclarations) {
5959   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
5960                "    AnotherNameForTheLongType;");
5961   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
5962                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5963   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
5964                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
5965   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
5966                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
5967   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
5968                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
5969   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
5970                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
5971   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
5972                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
5973   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
5974                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
5975   FormatStyle Indented = getLLVMStyle();
5976   Indented.IndentWrappedFunctionNames = true;
5977   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
5978                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
5979                Indented);
5980   verifyFormat(
5981       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
5982       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
5983       Indented);
5984   verifyFormat(
5985       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
5986       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
5987       Indented);
5988   verifyFormat(
5989       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
5990       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
5991       Indented);
5992
5993   // FIXME: Without the comment, this breaks after "(".
5994   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
5995                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
5996                getGoogleStyle());
5997
5998   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
5999                "                  int LoooooooooooooooooooongParam2) {}");
6000   verifyFormat(
6001       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
6002       "                                   SourceLocation L, IdentifierIn *II,\n"
6003       "                                   Type *T) {}");
6004   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
6005                "ReallyReaaallyLongFunctionName(\n"
6006                "    const std::string &SomeParameter,\n"
6007                "    const SomeType<string, SomeOtherTemplateParameter>\n"
6008                "        &ReallyReallyLongParameterName,\n"
6009                "    const SomeType<string, SomeOtherTemplateParameter>\n"
6010                "        &AnotherLongParameterName) {}");
6011   verifyFormat("template <typename A>\n"
6012                "SomeLoooooooooooooooooooooongType<\n"
6013                "    typename some_namespace::SomeOtherType<A>::Type>\n"
6014                "Function() {}");
6015
6016   verifyGoogleFormat(
6017       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
6018       "    aaaaaaaaaaaaaaaaaaaaaaa;");
6019   verifyGoogleFormat(
6020       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
6021       "                                   SourceLocation L) {}");
6022   verifyGoogleFormat(
6023       "some_namespace::LongReturnType\n"
6024       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
6025       "    int first_long_parameter, int second_parameter) {}");
6026
6027   verifyGoogleFormat("template <typename T>\n"
6028                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
6029                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
6030   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6031                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
6032
6033   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
6034                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6035                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6036   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6037                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
6038                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
6039   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6040                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
6041                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
6042                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6043 }
6044
6045 TEST_F(FormatTest, FormatsArrays) {
6046   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6047                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
6048   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
6049                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
6050   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
6051                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
6052   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6053                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
6054   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6055                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
6056   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6057                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6058                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
6059   verifyFormat(
6060       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
6061       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
6062       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
6063
6064   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
6065                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
6066   verifyFormat(
6067       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
6068       "                                  .aaaaaaa[0]\n"
6069       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
6070
6071   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
6072 }
6073
6074 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
6075   verifyFormat("(a)->b();");
6076   verifyFormat("--a;");
6077 }
6078
6079 TEST_F(FormatTest, HandlesIncludeDirectives) {
6080   verifyFormat("#include <string>\n"
6081                "#include <a/b/c.h>\n"
6082                "#include \"a/b/string\"\n"
6083                "#include \"string.h\"\n"
6084                "#include \"string.h\"\n"
6085                "#include <a-a>\n"
6086                "#include < path with space >\n"
6087                "#include_next <test.h>"
6088                "#include \"abc.h\" // this is included for ABC\n"
6089                "#include \"some long include\" // with a comment\n"
6090                "#include \"some very long include paaaaaaaaaaaaaaaaaaaaaaath\"",
6091                getLLVMStyleWithColumns(35));
6092   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
6093   EXPECT_EQ("#include <a>", format("#include<a>"));
6094
6095   verifyFormat("#import <string>");
6096   verifyFormat("#import <a/b/c.h>");
6097   verifyFormat("#import \"a/b/string\"");
6098   verifyFormat("#import \"string.h\"");
6099   verifyFormat("#import \"string.h\"");
6100   verifyFormat("#if __has_include(<strstream>)\n"
6101                "#include <strstream>\n"
6102                "#endif");
6103
6104   verifyFormat("#define MY_IMPORT <a/b>");
6105
6106   // Protocol buffer definition or missing "#".
6107   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
6108                getLLVMStyleWithColumns(30));
6109
6110   FormatStyle Style = getLLVMStyle();
6111   Style.AlwaysBreakBeforeMultilineStrings = true;
6112   Style.ColumnLimit = 0;
6113   verifyFormat("#import \"abc.h\"", Style);
6114
6115   // But 'import' might also be a regular C++ namespace.
6116   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6117                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6118 }
6119
6120 //===----------------------------------------------------------------------===//
6121 // Error recovery tests.
6122 //===----------------------------------------------------------------------===//
6123
6124 TEST_F(FormatTest, IncompleteParameterLists) {
6125   FormatStyle NoBinPacking = getLLVMStyle();
6126   NoBinPacking.BinPackParameters = false;
6127   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
6128                "                        double *min_x,\n"
6129                "                        double *max_x,\n"
6130                "                        double *min_y,\n"
6131                "                        double *max_y,\n"
6132                "                        double *min_z,\n"
6133                "                        double *max_z, ) {}",
6134                NoBinPacking);
6135 }
6136
6137 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
6138   verifyFormat("void f() { return; }\n42");
6139   verifyFormat("void f() {\n"
6140                "  if (0)\n"
6141                "    return;\n"
6142                "}\n"
6143                "42");
6144   verifyFormat("void f() { return }\n42");
6145   verifyFormat("void f() {\n"
6146                "  if (0)\n"
6147                "    return\n"
6148                "}\n"
6149                "42");
6150 }
6151
6152 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
6153   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
6154   EXPECT_EQ("void f() {\n"
6155             "  if (a)\n"
6156             "    return\n"
6157             "}",
6158             format("void  f  (  )  {  if  ( a )  return  }"));
6159   EXPECT_EQ("namespace N {\n"
6160             "void f()\n"
6161             "}",
6162             format("namespace  N  {  void f()  }"));
6163   EXPECT_EQ("namespace N {\n"
6164             "void f() {}\n"
6165             "void g()\n"
6166             "}",
6167             format("namespace N  { void f( ) { } void g( ) }"));
6168 }
6169
6170 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
6171   verifyFormat("int aaaaaaaa =\n"
6172                "    // Overlylongcomment\n"
6173                "    b;",
6174                getLLVMStyleWithColumns(20));
6175   verifyFormat("function(\n"
6176                "    ShortArgument,\n"
6177                "    LoooooooooooongArgument);\n",
6178                getLLVMStyleWithColumns(20));
6179 }
6180
6181 TEST_F(FormatTest, IncorrectAccessSpecifier) {
6182   verifyFormat("public:");
6183   verifyFormat("class A {\n"
6184                "public\n"
6185                "  void f() {}\n"
6186                "};");
6187   verifyFormat("public\n"
6188                "int qwerty;");
6189   verifyFormat("public\n"
6190                "B {}");
6191   verifyFormat("public\n"
6192                "{}");
6193   verifyFormat("public\n"
6194                "B { int x; }");
6195 }
6196
6197 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
6198   verifyFormat("{");
6199   verifyFormat("#})");
6200   verifyNoCrash("(/**/[:!] ?[).");
6201 }
6202
6203 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
6204   verifyFormat("do {\n}");
6205   verifyFormat("do {\n}\n"
6206                "f();");
6207   verifyFormat("do {\n}\n"
6208                "wheeee(fun);");
6209   verifyFormat("do {\n"
6210                "  f();\n"
6211                "}");
6212 }
6213
6214 TEST_F(FormatTest, IncorrectCodeMissingParens) {
6215   verifyFormat("if {\n  foo;\n  foo();\n}");
6216   verifyFormat("switch {\n  foo;\n  foo();\n}");
6217   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
6218   verifyFormat("while {\n  foo;\n  foo();\n}");
6219   verifyFormat("do {\n  foo;\n  foo();\n} while;");
6220 }
6221
6222 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
6223   verifyIncompleteFormat("namespace {\n"
6224                          "class Foo { Foo (\n"
6225                          "};\n"
6226                          "} // comment");
6227 }
6228
6229 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
6230   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
6231   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
6232   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
6233   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
6234
6235   EXPECT_EQ("{\n"
6236             "  {\n"
6237             "    breakme(\n"
6238             "        qwe);\n"
6239             "  }\n",
6240             format("{\n"
6241                    "    {\n"
6242                    " breakme(qwe);\n"
6243                    "}\n",
6244                    getLLVMStyleWithColumns(10)));
6245 }
6246
6247 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
6248   verifyFormat("int x = {\n"
6249                "    avariable,\n"
6250                "    b(alongervariable)};",
6251                getLLVMStyleWithColumns(25));
6252 }
6253
6254 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
6255   verifyFormat("return (a)(b){1, 2, 3};");
6256 }
6257
6258 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
6259   verifyFormat("vector<int> x{1, 2, 3, 4};");
6260   verifyFormat("vector<int> x{\n"
6261                "    1, 2, 3, 4,\n"
6262                "};");
6263   verifyFormat("vector<T> x{{}, {}, {}, {}};");
6264   verifyFormat("f({1, 2});");
6265   verifyFormat("auto v = Foo{-1};");
6266   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
6267   verifyFormat("Class::Class : member{1, 2, 3} {}");
6268   verifyFormat("new vector<int>{1, 2, 3};");
6269   verifyFormat("new int[3]{1, 2, 3};");
6270   verifyFormat("new int{1};");
6271   verifyFormat("return {arg1, arg2};");
6272   verifyFormat("return {arg1, SomeType{parameter}};");
6273   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
6274   verifyFormat("new T{arg1, arg2};");
6275   verifyFormat("f(MyMap[{composite, key}]);");
6276   verifyFormat("class Class {\n"
6277                "  T member = {arg1, arg2};\n"
6278                "};");
6279   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
6280   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
6281   verifyFormat("int a = std::is_integral<int>{} + 0;");
6282
6283   verifyFormat("int foo(int i) { return fo1{}(i); }");
6284   verifyFormat("int foo(int i) { return fo1{}(i); }");
6285   verifyFormat("auto i = decltype(x){};");
6286   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
6287   verifyFormat("Node n{1, Node{1000}, //\n"
6288                "       2};");
6289   verifyFormat("Aaaa aaaaaaa{\n"
6290                "    {\n"
6291                "        aaaa,\n"
6292                "    },\n"
6293                "};");
6294   verifyFormat("class C : public D {\n"
6295                "  SomeClass SC{2};\n"
6296                "};");
6297   verifyFormat("class C : public A {\n"
6298                "  class D : public B {\n"
6299                "    void f() { int i{2}; }\n"
6300                "  };\n"
6301                "};");
6302   verifyFormat("#define A {a, a},");
6303
6304   // In combination with BinPackArguments = false.
6305   FormatStyle NoBinPacking = getLLVMStyle();
6306   NoBinPacking.BinPackArguments = false;
6307   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
6308                "                      bbbbb,\n"
6309                "                      ccccc,\n"
6310                "                      ddddd,\n"
6311                "                      eeeee,\n"
6312                "                      ffffff,\n"
6313                "                      ggggg,\n"
6314                "                      hhhhhh,\n"
6315                "                      iiiiii,\n"
6316                "                      jjjjjj,\n"
6317                "                      kkkkkk};",
6318                NoBinPacking);
6319   verifyFormat("const Aaaaaa aaaaa = {\n"
6320                "    aaaaa,\n"
6321                "    bbbbb,\n"
6322                "    ccccc,\n"
6323                "    ddddd,\n"
6324                "    eeeee,\n"
6325                "    ffffff,\n"
6326                "    ggggg,\n"
6327                "    hhhhhh,\n"
6328                "    iiiiii,\n"
6329                "    jjjjjj,\n"
6330                "    kkkkkk,\n"
6331                "};",
6332                NoBinPacking);
6333   verifyFormat(
6334       "const Aaaaaa aaaaa = {\n"
6335       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
6336       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
6337       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
6338       "};",
6339       NoBinPacking);
6340
6341   // FIXME: The alignment of these trailing comments might be bad. Then again,
6342   // this might be utterly useless in real code.
6343   verifyFormat("Constructor::Constructor()\n"
6344                "    : some_value{         //\n"
6345                "                 aaaaaaa, //\n"
6346                "                 bbbbbbb} {}");
6347
6348   // In braced lists, the first comment is always assumed to belong to the
6349   // first element. Thus, it can be moved to the next or previous line as
6350   // appropriate.
6351   EXPECT_EQ("function({// First element:\n"
6352             "          1,\n"
6353             "          // Second element:\n"
6354             "          2});",
6355             format("function({\n"
6356                    "    // First element:\n"
6357                    "    1,\n"
6358                    "    // Second element:\n"
6359                    "    2});"));
6360   EXPECT_EQ("std::vector<int> MyNumbers{\n"
6361             "    // First element:\n"
6362             "    1,\n"
6363             "    // Second element:\n"
6364             "    2};",
6365             format("std::vector<int> MyNumbers{// First element:\n"
6366                    "                           1,\n"
6367                    "                           // Second element:\n"
6368                    "                           2};",
6369                    getLLVMStyleWithColumns(30)));
6370   // A trailing comma should still lead to an enforced line break.
6371   EXPECT_EQ("vector<int> SomeVector = {\n"
6372             "    // aaa\n"
6373             "    1, 2,\n"
6374             "};",
6375             format("vector<int> SomeVector = { // aaa\n"
6376                    "    1, 2, };"));
6377
6378   FormatStyle ExtraSpaces = getLLVMStyle();
6379   ExtraSpaces.Cpp11BracedListStyle = false;
6380   ExtraSpaces.ColumnLimit = 75;
6381   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
6382   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
6383   verifyFormat("f({ 1, 2 });", ExtraSpaces);
6384   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
6385   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
6386   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
6387   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
6388   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
6389   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
6390   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
6391   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
6392   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
6393   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
6394   verifyFormat("class Class {\n"
6395                "  T member = { arg1, arg2 };\n"
6396                "};",
6397                ExtraSpaces);
6398   verifyFormat(
6399       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6400       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
6401       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
6402       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
6403       ExtraSpaces);
6404   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
6405   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
6406                ExtraSpaces);
6407   verifyFormat(
6408       "someFunction(OtherParam,\n"
6409       "             BracedList{ // comment 1 (Forcing interesting break)\n"
6410       "                         param1, param2,\n"
6411       "                         // comment 2\n"
6412       "                         param3, param4 });",
6413       ExtraSpaces);
6414   verifyFormat(
6415       "std::this_thread::sleep_for(\n"
6416       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
6417       ExtraSpaces);
6418   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaa{\n"
6419                "    aaaaaaa,\n"
6420                "    aaaaaaaaaa,\n"
6421                "    aaaaa,\n"
6422                "    aaaaaaaaaaaaaaa,\n"
6423                "    aaa,\n"
6424                "    aaaaaaaaaa,\n"
6425                "    a,\n"
6426                "    aaaaaaaaaaaaaaaaaaaaa,\n"
6427                "    aaaaaaaaaaaa,\n"
6428                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
6429                "    aaaaaaa,\n"
6430                "    a};");
6431   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
6432 }
6433
6434 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
6435   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6436                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6437                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6438                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6439                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6440                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
6441   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
6442                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6443                "                 1, 22, 333, 4444, 55555, //\n"
6444                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
6445                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
6446   verifyFormat(
6447       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
6448       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
6449       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
6450       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
6451       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
6452       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
6453       "                 7777777};");
6454   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
6455                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
6456                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
6457   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
6458                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
6459                "    // Separating comment.\n"
6460                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
6461   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
6462                "    // Leading comment\n"
6463                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
6464                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
6465   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
6466                "                 1, 1, 1, 1};",
6467                getLLVMStyleWithColumns(39));
6468   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
6469                "                 1, 1, 1, 1};",
6470                getLLVMStyleWithColumns(38));
6471   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
6472                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
6473                getLLVMStyleWithColumns(43));
6474   verifyFormat(
6475       "static unsigned SomeValues[10][3] = {\n"
6476       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
6477       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
6478   verifyFormat("static auto fields = new vector<string>{\n"
6479                "    \"aaaaaaaaaaaaa\",\n"
6480                "    \"aaaaaaaaaaaaa\",\n"
6481                "    \"aaaaaaaaaaaa\",\n"
6482                "    \"aaaaaaaaaaaaaa\",\n"
6483                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
6484                "    \"aaaaaaaaaaaa\",\n"
6485                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
6486                "};");
6487   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
6488   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
6489                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
6490                "                 3, cccccccccccccccccccccc};",
6491                getLLVMStyleWithColumns(60));
6492
6493   // Trailing commas.
6494   verifyFormat("vector<int> x = {\n"
6495                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
6496                "};",
6497                getLLVMStyleWithColumns(39));
6498   verifyFormat("vector<int> x = {\n"
6499                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
6500                "};",
6501                getLLVMStyleWithColumns(39));
6502   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
6503                "                 1, 1, 1, 1,\n"
6504                "                 /**/ /**/};",
6505                getLLVMStyleWithColumns(39));
6506
6507   // Trailing comment in the first line.
6508   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
6509                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
6510                "    111111111,  222222222,  3333333333,  444444444,  //\n"
6511                "    11111111,   22222222,   333333333,   44444444};");
6512   // Trailing comment in the last line.
6513   verifyFormat("int aaaaa[] = {\n"
6514                "    1, 2, 3, // comment\n"
6515                "    4, 5, 6  // comment\n"
6516                "};");
6517
6518   // With nested lists, we should either format one item per line or all nested
6519   // lists one on line.
6520   // FIXME: For some nested lists, we can do better.
6521   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
6522                "        {aaaaaaaaaaaaaaaaaaa},\n"
6523                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
6524                "        {aaaaaaaaaaaaaaaaa}};",
6525                getLLVMStyleWithColumns(60));
6526   verifyFormat(
6527       "SomeStruct my_struct_array = {\n"
6528       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
6529       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
6530       "    {aaa, aaa},\n"
6531       "    {aaa, aaa},\n"
6532       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
6533       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6534       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
6535
6536   // No column layout should be used here.
6537   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
6538                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
6539
6540   verifyNoCrash("a<,");
6541   
6542   // No braced initializer here.
6543   verifyFormat("void f() {\n"
6544                "  struct Dummy {};\n"
6545                "  f(v);\n"
6546                "}");
6547 }
6548
6549 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
6550   FormatStyle DoNotMerge = getLLVMStyle();
6551   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6552
6553   verifyFormat("void f() { return 42; }");
6554   verifyFormat("void f() {\n"
6555                "  return 42;\n"
6556                "}",
6557                DoNotMerge);
6558   verifyFormat("void f() {\n"
6559                "  // Comment\n"
6560                "}");
6561   verifyFormat("{\n"
6562                "#error {\n"
6563                "  int a;\n"
6564                "}");
6565   verifyFormat("{\n"
6566                "  int a;\n"
6567                "#error {\n"
6568                "}");
6569   verifyFormat("void f() {} // comment");
6570   verifyFormat("void f() { int a; } // comment");
6571   verifyFormat("void f() {\n"
6572                "} // comment",
6573                DoNotMerge);
6574   verifyFormat("void f() {\n"
6575                "  int a;\n"
6576                "} // comment",
6577                DoNotMerge);
6578   verifyFormat("void f() {\n"
6579                "} // comment",
6580                getLLVMStyleWithColumns(15));
6581
6582   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
6583   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
6584
6585   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
6586   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
6587   verifyFormat("class C {\n"
6588                "  C()\n"
6589                "      : iiiiiiii(nullptr),\n"
6590                "        kkkkkkk(nullptr),\n"
6591                "        mmmmmmm(nullptr),\n"
6592                "        nnnnnnn(nullptr) {}\n"
6593                "};",
6594                getGoogleStyle());
6595
6596   FormatStyle NoColumnLimit = getLLVMStyle();
6597   NoColumnLimit.ColumnLimit = 0;
6598   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
6599   EXPECT_EQ("class C {\n"
6600             "  A() : b(0) {}\n"
6601             "};",
6602             format("class C{A():b(0){}};", NoColumnLimit));
6603   EXPECT_EQ("A()\n"
6604             "    : b(0) {\n"
6605             "}",
6606             format("A()\n:b(0)\n{\n}", NoColumnLimit));
6607
6608   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
6609   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
6610       FormatStyle::SFS_None;
6611   EXPECT_EQ("A()\n"
6612             "    : b(0) {\n"
6613             "}",
6614             format("A():b(0){}", DoNotMergeNoColumnLimit));
6615   EXPECT_EQ("A()\n"
6616             "    : b(0) {\n"
6617             "}",
6618             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
6619
6620   verifyFormat("#define A          \\\n"
6621                "  void f() {       \\\n"
6622                "    int i;         \\\n"
6623                "  }",
6624                getLLVMStyleWithColumns(20));
6625   verifyFormat("#define A           \\\n"
6626                "  void f() { int i; }",
6627                getLLVMStyleWithColumns(21));
6628   verifyFormat("#define A            \\\n"
6629                "  void f() {         \\\n"
6630                "    int i;           \\\n"
6631                "  }                  \\\n"
6632                "  int j;",
6633                getLLVMStyleWithColumns(22));
6634   verifyFormat("#define A             \\\n"
6635                "  void f() { int i; } \\\n"
6636                "  int j;",
6637                getLLVMStyleWithColumns(23));
6638 }
6639
6640 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
6641   FormatStyle MergeInlineOnly = getLLVMStyle();
6642   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
6643   verifyFormat("class C {\n"
6644                "  int f() { return 42; }\n"
6645                "};",
6646                MergeInlineOnly);
6647   verifyFormat("int f() {\n"
6648                "  return 42;\n"
6649                "}",
6650                MergeInlineOnly);
6651 }
6652
6653 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
6654   // Elaborate type variable declarations.
6655   verifyFormat("struct foo a = {bar};\nint n;");
6656   verifyFormat("class foo a = {bar};\nint n;");
6657   verifyFormat("union foo a = {bar};\nint n;");
6658
6659   // Elaborate types inside function definitions.
6660   verifyFormat("struct foo f() {}\nint n;");
6661   verifyFormat("class foo f() {}\nint n;");
6662   verifyFormat("union foo f() {}\nint n;");
6663
6664   // Templates.
6665   verifyFormat("template <class X> void f() {}\nint n;");
6666   verifyFormat("template <struct X> void f() {}\nint n;");
6667   verifyFormat("template <union X> void f() {}\nint n;");
6668
6669   // Actual definitions...
6670   verifyFormat("struct {\n} n;");
6671   verifyFormat(
6672       "template <template <class T, class Y>, class Z> class X {\n} n;");
6673   verifyFormat("union Z {\n  int n;\n} x;");
6674   verifyFormat("class MACRO Z {\n} n;");
6675   verifyFormat("class MACRO(X) Z {\n} n;");
6676   verifyFormat("class __attribute__(X) Z {\n} n;");
6677   verifyFormat("class __declspec(X) Z {\n} n;");
6678   verifyFormat("class A##B##C {\n} n;");
6679   verifyFormat("class alignas(16) Z {\n} n;");
6680   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
6681   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
6682
6683   // Redefinition from nested context:
6684   verifyFormat("class A::B::C {\n} n;");
6685
6686   // Template definitions.
6687   verifyFormat(
6688       "template <typename F>\n"
6689       "Matcher(const Matcher<F> &Other,\n"
6690       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
6691       "                             !is_same<F, T>::value>::type * = 0)\n"
6692       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
6693
6694   // FIXME: This is still incorrectly handled at the formatter side.
6695   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
6696   verifyFormat("int i = SomeFunction(a<b, a> b);");
6697
6698   // FIXME:
6699   // This now gets parsed incorrectly as class definition.
6700   // verifyFormat("class A<int> f() {\n}\nint n;");
6701
6702   // Elaborate types where incorrectly parsing the structural element would
6703   // break the indent.
6704   verifyFormat("if (true)\n"
6705                "  class X x;\n"
6706                "else\n"
6707                "  f();\n");
6708
6709   // This is simply incomplete. Formatting is not important, but must not crash.
6710   verifyFormat("class A:");
6711 }
6712
6713 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
6714   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
6715             format("#error Leave     all         white!!!!! space* alone!\n"));
6716   EXPECT_EQ(
6717       "#warning Leave     all         white!!!!! space* alone!\n",
6718       format("#warning Leave     all         white!!!!! space* alone!\n"));
6719   EXPECT_EQ("#error 1", format("  #  error   1"));
6720   EXPECT_EQ("#warning 1", format("  #  warning 1"));
6721 }
6722
6723 TEST_F(FormatTest, FormatHashIfExpressions) {
6724   verifyFormat("#if AAAA && BBBB");
6725   verifyFormat("#if (AAAA && BBBB)");
6726   verifyFormat("#elif (AAAA && BBBB)");
6727   // FIXME: Come up with a better indentation for #elif.
6728   verifyFormat(
6729       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
6730       "    defined(BBBBBBBB)\n"
6731       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
6732       "    defined(BBBBBBBB)\n"
6733       "#endif",
6734       getLLVMStyleWithColumns(65));
6735 }
6736
6737 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
6738   FormatStyle AllowsMergedIf = getGoogleStyle();
6739   AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
6740   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
6741   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
6742   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
6743   EXPECT_EQ("if (true) return 42;",
6744             format("if (true)\nreturn 42;", AllowsMergedIf));
6745   FormatStyle ShortMergedIf = AllowsMergedIf;
6746   ShortMergedIf.ColumnLimit = 25;
6747   verifyFormat("#define A \\\n"
6748                "  if (true) return 42;",
6749                ShortMergedIf);
6750   verifyFormat("#define A \\\n"
6751                "  f();    \\\n"
6752                "  if (true)\n"
6753                "#define B",
6754                ShortMergedIf);
6755   verifyFormat("#define A \\\n"
6756                "  f();    \\\n"
6757                "  if (true)\n"
6758                "g();",
6759                ShortMergedIf);
6760   verifyFormat("{\n"
6761                "#ifdef A\n"
6762                "  // Comment\n"
6763                "  if (true) continue;\n"
6764                "#endif\n"
6765                "  // Comment\n"
6766                "  if (true) continue;\n"
6767                "}",
6768                ShortMergedIf);
6769   ShortMergedIf.ColumnLimit = 29;
6770   verifyFormat("#define A                   \\\n"
6771                "  if (aaaaaaaaaa) return 1; \\\n"
6772                "  return 2;",
6773                ShortMergedIf);
6774   ShortMergedIf.ColumnLimit = 28;
6775   verifyFormat("#define A         \\\n"
6776                "  if (aaaaaaaaaa) \\\n"
6777                "    return 1;     \\\n"
6778                "  return 2;",
6779                ShortMergedIf);
6780 }
6781
6782 TEST_F(FormatTest, BlockCommentsInControlLoops) {
6783   verifyFormat("if (0) /* a comment in a strange place */ {\n"
6784                "  f();\n"
6785                "}");
6786   verifyFormat("if (0) /* a comment in a strange place */ {\n"
6787                "  f();\n"
6788                "} /* another comment */ else /* comment #3 */ {\n"
6789                "  g();\n"
6790                "}");
6791   verifyFormat("while (0) /* a comment in a strange place */ {\n"
6792                "  f();\n"
6793                "}");
6794   verifyFormat("for (;;) /* a comment in a strange place */ {\n"
6795                "  f();\n"
6796                "}");
6797   verifyFormat("do /* a comment in a strange place */ {\n"
6798                "  f();\n"
6799                "} /* another comment */ while (0);");
6800 }
6801
6802 TEST_F(FormatTest, BlockComments) {
6803   EXPECT_EQ("/* */ /* */ /* */\n/* */ /* */ /* */",
6804             format("/* *//* */  /* */\n/* *//* */  /* */"));
6805   EXPECT_EQ("/* */ a /* */ b;", format("  /* */  a/* */  b;"));
6806   EXPECT_EQ("#define A /*123*/ \\\n"
6807             "  b\n"
6808             "/* */\n"
6809             "someCall(\n"
6810             "    parameter);",
6811             format("#define A /*123*/ b\n"
6812                    "/* */\n"
6813                    "someCall(parameter);",
6814                    getLLVMStyleWithColumns(15)));
6815
6816   EXPECT_EQ("#define A\n"
6817             "/* */ someCall(\n"
6818             "    parameter);",
6819             format("#define A\n"
6820                    "/* */someCall(parameter);",
6821                    getLLVMStyleWithColumns(15)));
6822   EXPECT_EQ("/*\n**\n*/", format("/*\n**\n*/"));
6823   EXPECT_EQ("/*\n"
6824             "*\n"
6825             " * aaaaaa\n"
6826             " * aaaaaa\n"
6827             "*/",
6828             format("/*\n"
6829                    "*\n"
6830                    " * aaaaaa aaaaaa\n"
6831                    "*/",
6832                    getLLVMStyleWithColumns(10)));
6833   EXPECT_EQ("/*\n"
6834             "**\n"
6835             "* aaaaaa\n"
6836             "*aaaaaa\n"
6837             "*/",
6838             format("/*\n"
6839                    "**\n"
6840                    "* aaaaaa aaaaaa\n"
6841                    "*/",
6842                    getLLVMStyleWithColumns(10)));
6843
6844   FormatStyle NoBinPacking = getLLVMStyle();
6845   NoBinPacking.BinPackParameters = false;
6846   EXPECT_EQ("someFunction(1, /* comment 1 */\n"
6847             "             2, /* comment 2 */\n"
6848             "             3, /* comment 3 */\n"
6849             "             aaaa,\n"
6850             "             bbbb);",
6851             format("someFunction (1,   /* comment 1 */\n"
6852                    "                2, /* comment 2 */  \n"
6853                    "               3,   /* comment 3 */\n"
6854                    "aaaa, bbbb );",
6855                    NoBinPacking));
6856   verifyFormat(
6857       "bool aaaaaaaaaaaaa = /* comment: */ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6858       "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6859   EXPECT_EQ(
6860       "bool aaaaaaaaaaaaa = /* trailing comment */\n"
6861       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6862       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;",
6863       format(
6864           "bool       aaaaaaaaaaaaa =       /* trailing comment */\n"
6865           "    aaaaaaaaaaaaaaaaaaaaaaaaaaa||aaaaaaaaaaaaaaaaaaaaaaaaa    ||\n"
6866           "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa   || aaaaaaaaaaaaaaaaaaaaaaaaaa;"));
6867   EXPECT_EQ(
6868       "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
6869       "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   /* comment */\n"
6870       "int cccccccccccccccccccccccccccccc;       /* comment */\n",
6871       format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
6872              "int      bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n"
6873              "int    cccccccccccccccccccccccccccccc;  /* comment */\n"));
6874
6875   verifyFormat("void f(int * /* unused */) {}");
6876
6877   EXPECT_EQ("/*\n"
6878             " **\n"
6879             " */",
6880             format("/*\n"
6881                    " **\n"
6882                    " */"));
6883   EXPECT_EQ("/*\n"
6884             " *q\n"
6885             " */",
6886             format("/*\n"
6887                    " *q\n"
6888                    " */"));
6889   EXPECT_EQ("/*\n"
6890             " * q\n"
6891             " */",
6892             format("/*\n"
6893                    " * q\n"
6894                    " */"));
6895   EXPECT_EQ("/*\n"
6896             " **/",
6897             format("/*\n"
6898                    " **/"));
6899   EXPECT_EQ("/*\n"
6900             " ***/",
6901             format("/*\n"
6902                    " ***/"));
6903 }
6904
6905 TEST_F(FormatTest, BlockCommentsInMacros) {
6906   EXPECT_EQ("#define A          \\\n"
6907             "  {                \\\n"
6908             "    /* one line */ \\\n"
6909             "    someCall();",
6910             format("#define A {        \\\n"
6911                    "  /* one line */   \\\n"
6912                    "  someCall();",
6913                    getLLVMStyleWithColumns(20)));
6914   EXPECT_EQ("#define A          \\\n"
6915             "  {                \\\n"
6916             "    /* previous */ \\\n"
6917             "    /* one line */ \\\n"
6918             "    someCall();",
6919             format("#define A {        \\\n"
6920                    "  /* previous */   \\\n"
6921                    "  /* one line */   \\\n"
6922                    "  someCall();",
6923                    getLLVMStyleWithColumns(20)));
6924 }
6925
6926 TEST_F(FormatTest, BlockCommentsAtEndOfLine) {
6927   EXPECT_EQ("a = {\n"
6928             "    1111 /*    */\n"
6929             "};",
6930             format("a = {1111 /*    */\n"
6931                    "};",
6932                    getLLVMStyleWithColumns(15)));
6933   EXPECT_EQ("a = {\n"
6934             "    1111 /*      */\n"
6935             "};",
6936             format("a = {1111 /*      */\n"
6937                    "};",
6938                    getLLVMStyleWithColumns(15)));
6939
6940   // FIXME: The formatting is still wrong here.
6941   EXPECT_EQ("a = {\n"
6942             "    1111 /*      a\n"
6943             "            */\n"
6944             "};",
6945             format("a = {1111 /*      a */\n"
6946                    "};",
6947                    getLLVMStyleWithColumns(15)));
6948 }
6949
6950 TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
6951   // FIXME: This is not what we want...
6952   verifyFormat("{\n"
6953                "// a"
6954                "// b");
6955 }
6956
6957 TEST_F(FormatTest, FormatStarDependingOnContext) {
6958   verifyFormat("void f(int *a);");
6959   verifyFormat("void f() { f(fint * b); }");
6960   verifyFormat("class A {\n  void f(int *a);\n};");
6961   verifyFormat("class A {\n  int *a;\n};");
6962   verifyFormat("namespace a {\n"
6963                "namespace b {\n"
6964                "class A {\n"
6965                "  void f() {}\n"
6966                "  int *a;\n"
6967                "};\n"
6968                "}\n"
6969                "}");
6970 }
6971
6972 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
6973   verifyFormat("while");
6974   verifyFormat("operator");
6975 }
6976
6977 //===----------------------------------------------------------------------===//
6978 // Objective-C tests.
6979 //===----------------------------------------------------------------------===//
6980
6981 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
6982   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
6983   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
6984             format("-(NSUInteger)indexOfObject:(id)anObject;"));
6985   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
6986   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
6987   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
6988             format("-(NSInteger)Method3:(id)anObject;"));
6989   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
6990             format("-(NSInteger)Method4:(id)anObject;"));
6991   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
6992             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
6993   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
6994             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
6995   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
6996             "forAllCells:(BOOL)flag;",
6997             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
6998                    "forAllCells:(BOOL)flag;"));
6999
7000   // Very long objectiveC method declaration.
7001   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
7002                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
7003   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
7004                "                    inRange:(NSRange)range\n"
7005                "                   outRange:(NSRange)out_range\n"
7006                "                  outRange1:(NSRange)out_range1\n"
7007                "                  outRange2:(NSRange)out_range2\n"
7008                "                  outRange3:(NSRange)out_range3\n"
7009                "                  outRange4:(NSRange)out_range4\n"
7010                "                  outRange5:(NSRange)out_range5\n"
7011                "                  outRange6:(NSRange)out_range6\n"
7012                "                  outRange7:(NSRange)out_range7\n"
7013                "                  outRange8:(NSRange)out_range8\n"
7014                "                  outRange9:(NSRange)out_range9;");
7015
7016   // When the function name has to be wrapped.
7017   FormatStyle Style = getLLVMStyle();
7018   Style.IndentWrappedFunctionNames = false;
7019   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
7020                "veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
7021                "           anotherName:(NSString)bbbbbbbbbbbbbb {\n"
7022                "}",
7023                Style);
7024   Style.IndentWrappedFunctionNames = true;
7025   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
7026                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
7027                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
7028                "}",
7029                Style);
7030
7031   verifyFormat("- (int)sum:(vector<int>)numbers;");
7032   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
7033   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
7034   // protocol lists (but not for template classes):
7035   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
7036
7037   verifyFormat("- (int (*)())foo:(int (*)())f;");
7038   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
7039
7040   // If there's no return type (very rare in practice!), LLVM and Google style
7041   // agree.
7042   verifyFormat("- foo;");
7043   verifyFormat("- foo:(int)f;");
7044   verifyGoogleFormat("- foo:(int)foo;");
7045 }
7046
7047 TEST_F(FormatTest, FormatObjCInterface) {
7048   verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
7049                "@public\n"
7050                "  int field1;\n"
7051                "@protected\n"
7052                "  int field2;\n"
7053                "@private\n"
7054                "  int field3;\n"
7055                "@package\n"
7056                "  int field4;\n"
7057                "}\n"
7058                "+ (id)init;\n"
7059                "@end");
7060
7061   verifyGoogleFormat("@interface Foo : NSObject<NSSomeDelegate> {\n"
7062                      " @public\n"
7063                      "  int field1;\n"
7064                      " @protected\n"
7065                      "  int field2;\n"
7066                      " @private\n"
7067                      "  int field3;\n"
7068                      " @package\n"
7069                      "  int field4;\n"
7070                      "}\n"
7071                      "+ (id)init;\n"
7072                      "@end");
7073
7074   verifyFormat("@interface /* wait for it */ Foo\n"
7075                "+ (id)init;\n"
7076                "// Look, a comment!\n"
7077                "- (int)answerWith:(int)i;\n"
7078                "@end");
7079
7080   verifyFormat("@interface Foo\n"
7081                "@end\n"
7082                "@interface Bar\n"
7083                "@end");
7084
7085   verifyFormat("@interface Foo : Bar\n"
7086                "+ (id)init;\n"
7087                "@end");
7088
7089   verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
7090                "+ (id)init;\n"
7091                "@end");
7092
7093   verifyGoogleFormat("@interface Foo : Bar<Baz, Quux>\n"
7094                      "+ (id)init;\n"
7095                      "@end");
7096
7097   verifyFormat("@interface Foo (HackStuff)\n"
7098                "+ (id)init;\n"
7099                "@end");
7100
7101   verifyFormat("@interface Foo ()\n"
7102                "+ (id)init;\n"
7103                "@end");
7104
7105   verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
7106                "+ (id)init;\n"
7107                "@end");
7108
7109   verifyGoogleFormat("@interface Foo (HackStuff)<MyProtocol>\n"
7110                      "+ (id)init;\n"
7111                      "@end");
7112
7113   verifyFormat("@interface Foo {\n"
7114                "  int _i;\n"
7115                "}\n"
7116                "+ (id)init;\n"
7117                "@end");
7118
7119   verifyFormat("@interface Foo : Bar {\n"
7120                "  int _i;\n"
7121                "}\n"
7122                "+ (id)init;\n"
7123                "@end");
7124
7125   verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
7126                "  int _i;\n"
7127                "}\n"
7128                "+ (id)init;\n"
7129                "@end");
7130
7131   verifyFormat("@interface Foo (HackStuff) {\n"
7132                "  int _i;\n"
7133                "}\n"
7134                "+ (id)init;\n"
7135                "@end");
7136
7137   verifyFormat("@interface Foo () {\n"
7138                "  int _i;\n"
7139                "}\n"
7140                "+ (id)init;\n"
7141                "@end");
7142
7143   verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
7144                "  int _i;\n"
7145                "}\n"
7146                "+ (id)init;\n"
7147                "@end");
7148
7149   FormatStyle OnePerLine = getGoogleStyle();
7150   OnePerLine.BinPackParameters = false;
7151   verifyFormat("@interface aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ()<\n"
7152                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7153                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7154                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7155                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
7156                "}",
7157                OnePerLine);
7158 }
7159
7160 TEST_F(FormatTest, FormatObjCImplementation) {
7161   verifyFormat("@implementation Foo : NSObject {\n"
7162                "@public\n"
7163                "  int field1;\n"
7164                "@protected\n"
7165                "  int field2;\n"
7166                "@private\n"
7167                "  int field3;\n"
7168                "@package\n"
7169                "  int field4;\n"
7170                "}\n"
7171                "+ (id)init {\n}\n"
7172                "@end");
7173
7174   verifyGoogleFormat("@implementation Foo : NSObject {\n"
7175                      " @public\n"
7176                      "  int field1;\n"
7177                      " @protected\n"
7178                      "  int field2;\n"
7179                      " @private\n"
7180                      "  int field3;\n"
7181                      " @package\n"
7182                      "  int field4;\n"
7183                      "}\n"
7184                      "+ (id)init {\n}\n"
7185                      "@end");
7186
7187   verifyFormat("@implementation Foo\n"
7188                "+ (id)init {\n"
7189                "  if (true)\n"
7190                "    return nil;\n"
7191                "}\n"
7192                "// Look, a comment!\n"
7193                "- (int)answerWith:(int)i {\n"
7194                "  return i;\n"
7195                "}\n"
7196                "+ (int)answerWith:(int)i {\n"
7197                "  return i;\n"
7198                "}\n"
7199                "@end");
7200
7201   verifyFormat("@implementation Foo\n"
7202                "@end\n"
7203                "@implementation Bar\n"
7204                "@end");
7205
7206   EXPECT_EQ("@implementation Foo : Bar\n"
7207             "+ (id)init {\n}\n"
7208             "- (void)foo {\n}\n"
7209             "@end",
7210             format("@implementation Foo : Bar\n"
7211                    "+(id)init{}\n"
7212                    "-(void)foo{}\n"
7213                    "@end"));
7214
7215   verifyFormat("@implementation Foo {\n"
7216                "  int _i;\n"
7217                "}\n"
7218                "+ (id)init {\n}\n"
7219                "@end");
7220
7221   verifyFormat("@implementation Foo : Bar {\n"
7222                "  int _i;\n"
7223                "}\n"
7224                "+ (id)init {\n}\n"
7225                "@end");
7226
7227   verifyFormat("@implementation Foo (HackStuff)\n"
7228                "+ (id)init {\n}\n"
7229                "@end");
7230   verifyFormat("@implementation ObjcClass\n"
7231                "- (void)method;\n"
7232                "{}\n"
7233                "@end");
7234 }
7235
7236 TEST_F(FormatTest, FormatObjCProtocol) {
7237   verifyFormat("@protocol Foo\n"
7238                "@property(weak) id delegate;\n"
7239                "- (NSUInteger)numberOfThings;\n"
7240                "@end");
7241
7242   verifyFormat("@protocol MyProtocol <NSObject>\n"
7243                "- (NSUInteger)numberOfThings;\n"
7244                "@end");
7245
7246   verifyGoogleFormat("@protocol MyProtocol<NSObject>\n"
7247                      "- (NSUInteger)numberOfThings;\n"
7248                      "@end");
7249
7250   verifyFormat("@protocol Foo;\n"
7251                "@protocol Bar;\n");
7252
7253   verifyFormat("@protocol Foo\n"
7254                "@end\n"
7255                "@protocol Bar\n"
7256                "@end");
7257
7258   verifyFormat("@protocol myProtocol\n"
7259                "- (void)mandatoryWithInt:(int)i;\n"
7260                "@optional\n"
7261                "- (void)optional;\n"
7262                "@required\n"
7263                "- (void)required;\n"
7264                "@optional\n"
7265                "@property(assign) int madProp;\n"
7266                "@end\n");
7267
7268   verifyFormat("@property(nonatomic, assign, readonly)\n"
7269                "    int *looooooooooooooooooooooooooooongNumber;\n"
7270                "@property(nonatomic, assign, readonly)\n"
7271                "    NSString *looooooooooooooooooooooooooooongName;");
7272
7273   verifyFormat("@implementation PR18406\n"
7274                "}\n"
7275                "@end");
7276 }
7277
7278 TEST_F(FormatTest, FormatObjCMethodDeclarations) {
7279   verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
7280                "                   rect:(NSRect)theRect\n"
7281                "               interval:(float)theInterval {\n"
7282                "}");
7283   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
7284                "      longKeyword:(NSRect)theRect\n"
7285                "    longerKeyword:(float)theInterval\n"
7286                "            error:(NSError **)theError {\n"
7287                "}");
7288   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
7289                "          longKeyword:(NSRect)theRect\n"
7290                "    evenLongerKeyword:(float)theInterval\n"
7291                "                error:(NSError **)theError {\n"
7292                "}");
7293   verifyFormat("- (instancetype)initXxxxxx:(id<x>)x\n"
7294                "                         y:(id<yyyyyyyyyyyyyyyyyyyy>)y\n"
7295                "    NS_DESIGNATED_INITIALIZER;",
7296                getLLVMStyleWithColumns(60));
7297
7298   // Continuation indent width should win over aligning colons if the function
7299   // name is long.
7300   FormatStyle continuationStyle = getGoogleStyle();
7301   continuationStyle.ColumnLimit = 40;
7302   continuationStyle.IndentWrappedFunctionNames = true;
7303   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
7304                "    dontAlignNamef:(NSRect)theRect {\n"
7305                "}",
7306                continuationStyle);
7307
7308   // Make sure we don't break aligning for short parameter names.
7309   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
7310                "       aShortf:(NSRect)theRect {\n"
7311                "}",
7312                continuationStyle);
7313 }
7314
7315 TEST_F(FormatTest, FormatObjCMethodExpr) {
7316   verifyFormat("[foo bar:baz];");
7317   verifyFormat("return [foo bar:baz];");
7318   verifyFormat("return (a)[foo bar:baz];");
7319   verifyFormat("f([foo bar:baz]);");
7320   verifyFormat("f(2, [foo bar:baz]);");
7321   verifyFormat("f(2, a ? b : c);");
7322   verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
7323
7324   // Unary operators.
7325   verifyFormat("int a = +[foo bar:baz];");
7326   verifyFormat("int a = -[foo bar:baz];");
7327   verifyFormat("int a = ![foo bar:baz];");
7328   verifyFormat("int a = ~[foo bar:baz];");
7329   verifyFormat("int a = ++[foo bar:baz];");
7330   verifyFormat("int a = --[foo bar:baz];");
7331   verifyFormat("int a = sizeof [foo bar:baz];");
7332   verifyFormat("int a = alignof [foo bar:baz];", getGoogleStyle());
7333   verifyFormat("int a = &[foo bar:baz];");
7334   verifyFormat("int a = *[foo bar:baz];");
7335   // FIXME: Make casts work, without breaking f()[4].
7336   // verifyFormat("int a = (int)[foo bar:baz];");
7337   // verifyFormat("return (int)[foo bar:baz];");
7338   // verifyFormat("(void)[foo bar:baz];");
7339   verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
7340
7341   // Binary operators.
7342   verifyFormat("[foo bar:baz], [foo bar:baz];");
7343   verifyFormat("[foo bar:baz] = [foo bar:baz];");
7344   verifyFormat("[foo bar:baz] *= [foo bar:baz];");
7345   verifyFormat("[foo bar:baz] /= [foo bar:baz];");
7346   verifyFormat("[foo bar:baz] %= [foo bar:baz];");
7347   verifyFormat("[foo bar:baz] += [foo bar:baz];");
7348   verifyFormat("[foo bar:baz] -= [foo bar:baz];");
7349   verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
7350   verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
7351   verifyFormat("[foo bar:baz] &= [foo bar:baz];");
7352   verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
7353   verifyFormat("[foo bar:baz] |= [foo bar:baz];");
7354   verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
7355   verifyFormat("[foo bar:baz] || [foo bar:baz];");
7356   verifyFormat("[foo bar:baz] && [foo bar:baz];");
7357   verifyFormat("[foo bar:baz] | [foo bar:baz];");
7358   verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
7359   verifyFormat("[foo bar:baz] & [foo bar:baz];");
7360   verifyFormat("[foo bar:baz] == [foo bar:baz];");
7361   verifyFormat("[foo bar:baz] != [foo bar:baz];");
7362   verifyFormat("[foo bar:baz] >= [foo bar:baz];");
7363   verifyFormat("[foo bar:baz] <= [foo bar:baz];");
7364   verifyFormat("[foo bar:baz] > [foo bar:baz];");
7365   verifyFormat("[foo bar:baz] < [foo bar:baz];");
7366   verifyFormat("[foo bar:baz] >> [foo bar:baz];");
7367   verifyFormat("[foo bar:baz] << [foo bar:baz];");
7368   verifyFormat("[foo bar:baz] - [foo bar:baz];");
7369   verifyFormat("[foo bar:baz] + [foo bar:baz];");
7370   verifyFormat("[foo bar:baz] * [foo bar:baz];");
7371   verifyFormat("[foo bar:baz] / [foo bar:baz];");
7372   verifyFormat("[foo bar:baz] % [foo bar:baz];");
7373   // Whew!
7374
7375   verifyFormat("return in[42];");
7376   verifyFormat("for (auto v : in[1]) {\n}");
7377   verifyFormat("for (int i = 0; i < in[a]; ++i) {\n}");
7378   verifyFormat("for (int i = 0; in[a] < i; ++i) {\n}");
7379   verifyFormat("for (int i = 0; i < n; ++i, ++in[a]) {\n}");
7380   verifyFormat("for (int i = 0; i < n; ++i, in[a]++) {\n}");
7381   verifyFormat("for (int i = 0; i < f(in[a]); ++i, in[a]++) {\n}");
7382   verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
7383                "}");
7384   verifyFormat("[self aaaaa:MACRO(a, b:, c:)];");
7385   verifyFormat("[self aaaaa:(1 + 2) bbbbb:3];");
7386   verifyFormat("[self aaaaa:(Type)a bbbbb:3];");
7387
7388   verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
7389   verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
7390   verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
7391   verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
7392   verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
7393   verifyFormat("[button setAction:@selector(zoomOut:)];");
7394   verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
7395
7396   verifyFormat("arr[[self indexForFoo:a]];");
7397   verifyFormat("throw [self errorFor:a];");
7398   verifyFormat("@throw [self errorFor:a];");
7399
7400   verifyFormat("[(id)foo bar:(id)baz quux:(id)snorf];");
7401   verifyFormat("[(id)foo bar:(id) ? baz : quux];");
7402   verifyFormat("4 > 4 ? (id)a : (id)baz;");
7403
7404   // This tests that the formatter doesn't break after "backing" but before ":",
7405   // which would be at 80 columns.
7406   verifyFormat(
7407       "void f() {\n"
7408       "  if ((self = [super initWithContentRect:contentRect\n"
7409       "                               styleMask:styleMask ?: otherMask\n"
7410       "                                 backing:NSBackingStoreBuffered\n"
7411       "                                   defer:YES]))");
7412
7413   verifyFormat(
7414       "[foo checkThatBreakingAfterColonWorksOk:\n"
7415       "         [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
7416
7417   verifyFormat("[myObj short:arg1 // Force line break\n"
7418                "          longKeyword:arg2 != nil ? arg2 : @\"longKeyword\"\n"
7419                "    evenLongerKeyword:arg3 ?: @\"evenLongerKeyword\"\n"
7420                "                error:arg4];");
7421   verifyFormat(
7422       "void f() {\n"
7423       "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
7424       "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
7425       "                                     pos.width(), pos.height())\n"
7426       "                styleMask:NSBorderlessWindowMask\n"
7427       "                  backing:NSBackingStoreBuffered\n"
7428       "                    defer:NO]);\n"
7429       "}");
7430   verifyFormat(
7431       "void f() {\n"
7432       "  popup_wdow_.reset([[RenderWidgetPopupWindow alloc]\n"
7433       "      iniithContentRect:NSMakRet(origin_global.x, origin_global.y,\n"
7434       "                                 pos.width(), pos.height())\n"
7435       "                syeMask:NSBorderlessWindowMask\n"
7436       "                  bking:NSBackingStoreBuffered\n"
7437       "                    der:NO]);\n"
7438       "}",
7439       getLLVMStyleWithColumns(70));
7440   verifyFormat(
7441       "void f() {\n"
7442       "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
7443       "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
7444       "                                     pos.width(), pos.height())\n"
7445       "                styleMask:NSBorderlessWindowMask\n"
7446       "                  backing:NSBackingStoreBuffered\n"
7447       "                    defer:NO]);\n"
7448       "}",
7449       getChromiumStyle(FormatStyle::LK_Cpp));
7450   verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
7451                "                             with:contentsNativeView];");
7452
7453   verifyFormat(
7454       "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
7455       "           owner:nillllll];");
7456
7457   verifyFormat(
7458       "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
7459       "        forType:kBookmarkButtonDragType];");
7460
7461   verifyFormat("[defaultCenter addObserver:self\n"
7462                "                  selector:@selector(willEnterFullscreen)\n"
7463                "                      name:kWillEnterFullscreenNotification\n"
7464                "                    object:nil];");
7465   verifyFormat("[image_rep drawInRect:drawRect\n"
7466                "             fromRect:NSZeroRect\n"
7467                "            operation:NSCompositeCopy\n"
7468                "             fraction:1.0\n"
7469                "       respectFlipped:NO\n"
7470                "                hints:nil];");
7471   verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7472                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
7473   verifyFormat("[aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7474                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
7475   verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaa[aaaaaaaaaaaaaaaaaaaaa]\n"
7476                "    aaaaaaaaaaaaaaaaaaaaaa];");
7477   verifyFormat("[call aaaaaaaa.aaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa\n"
7478                "        .aaaaaaaa.aaaaaaaa];", // FIXME: Indentation seems off.
7479                getLLVMStyleWithColumns(60));
7480
7481   verifyFormat(
7482       "scoped_nsobject<NSTextField> message(\n"
7483       "    // The frame will be fixed up when |-setMessageText:| is called.\n"
7484       "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
7485   verifyFormat("[self aaaaaa:bbbbbbbbbbbbb\n"
7486                "    aaaaaaaaaa:bbbbbbbbbbbbbbbbb\n"
7487                "         aaaaa:bbbbbbbbbbb + bbbbbbbbbbbb\n"
7488                "          aaaa:bbb];");
7489   verifyFormat("[self param:function( //\n"
7490                "                parameter)]");
7491   verifyFormat(
7492       "[self aaaaaaaaaa:aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
7493       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
7494       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa];");
7495
7496   // FIXME: This violates the column limit.
7497   verifyFormat(
7498       "[aaaaaaaaaaaaaaaaaaaaaaaaa\n"
7499       "    aaaaaaaaaaaaaaaaa:aaaaaaaa\n"
7500       "                  aaa:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];",
7501       getLLVMStyleWithColumns(60));
7502
7503   // Variadic parameters.
7504   verifyFormat(
7505       "NSArray *myStrings = [NSArray stringarray:@\"a\", @\"b\", nil];");
7506   verifyFormat(
7507       "[self aaaaaaaaaaaaa:aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
7508       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
7509       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa];");
7510   verifyFormat("[self // break\n"
7511                "      a:a\n"
7512                "    aaa:aaa];");
7513   verifyFormat("bool a = ([aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaa ||\n"
7514                "          [aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaaaaa);");
7515 }
7516
7517 TEST_F(FormatTest, ObjCAt) {
7518   verifyFormat("@autoreleasepool");
7519   verifyFormat("@catch");
7520   verifyFormat("@class");
7521   verifyFormat("@compatibility_alias");
7522   verifyFormat("@defs");
7523   verifyFormat("@dynamic");
7524   verifyFormat("@encode");
7525   verifyFormat("@end");
7526   verifyFormat("@finally");
7527   verifyFormat("@implementation");
7528   verifyFormat("@import");
7529   verifyFormat("@interface");
7530   verifyFormat("@optional");
7531   verifyFormat("@package");
7532   verifyFormat("@private");
7533   verifyFormat("@property");
7534   verifyFormat("@protected");
7535   verifyFormat("@protocol");
7536   verifyFormat("@public");
7537   verifyFormat("@required");
7538   verifyFormat("@selector");
7539   verifyFormat("@synchronized");
7540   verifyFormat("@synthesize");
7541   verifyFormat("@throw");
7542   verifyFormat("@try");
7543
7544   EXPECT_EQ("@interface", format("@ interface"));
7545
7546   // The precise formatting of this doesn't matter, nobody writes code like
7547   // this.
7548   verifyFormat("@ /*foo*/ interface");
7549 }
7550
7551 TEST_F(FormatTest, ObjCSnippets) {
7552   verifyFormat("@autoreleasepool {\n"
7553                "  foo();\n"
7554                "}");
7555   verifyFormat("@class Foo, Bar;");
7556   verifyFormat("@compatibility_alias AliasName ExistingClass;");
7557   verifyFormat("@dynamic textColor;");
7558   verifyFormat("char *buf1 = @encode(int *);");
7559   verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
7560   verifyFormat("char *buf1 = @encode(int **);");
7561   verifyFormat("Protocol *proto = @protocol(p1);");
7562   verifyFormat("SEL s = @selector(foo:);");
7563   verifyFormat("@synchronized(self) {\n"
7564                "  f();\n"
7565                "}");
7566
7567   verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
7568   verifyGoogleFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
7569
7570   verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
7571   verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
7572   verifyGoogleFormat("@property(assign, getter=isEditable) BOOL editable;");
7573   verifyFormat("@property (assign, getter=isEditable) BOOL editable;",
7574                getMozillaStyle());
7575   verifyFormat("@property BOOL editable;", getMozillaStyle());
7576   verifyFormat("@property (assign, getter=isEditable) BOOL editable;",
7577                getWebKitStyle());
7578   verifyFormat("@property BOOL editable;", getWebKitStyle());
7579
7580   verifyFormat("@import foo.bar;\n"
7581                "@import baz;");
7582 }
7583
7584 TEST_F(FormatTest, ObjCForIn) {
7585   verifyFormat("- (void)test {\n"
7586                "  for (NSString *n in arrayOfStrings) {\n"
7587                "    foo(n);\n"
7588                "  }\n"
7589                "}");
7590   verifyFormat("- (void)test {\n"
7591                "  for (NSString *n in (__bridge NSArray *)arrayOfStrings) {\n"
7592                "    foo(n);\n"
7593                "  }\n"
7594                "}");
7595 }
7596
7597 TEST_F(FormatTest, ObjCLiterals) {
7598   verifyFormat("@\"String\"");
7599   verifyFormat("@1");
7600   verifyFormat("@+4.8");
7601   verifyFormat("@-4");
7602   verifyFormat("@1LL");
7603   verifyFormat("@.5");
7604   verifyFormat("@'c'");
7605   verifyFormat("@true");
7606
7607   verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
7608   verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
7609   verifyFormat("NSNumber *favoriteColor = @(Green);");
7610   verifyFormat("NSString *path = @(getenv(\"PATH\"));");
7611
7612   verifyFormat("[dictionary setObject:@(1) forKey:@\"number\"];");
7613 }
7614
7615 TEST_F(FormatTest, ObjCDictLiterals) {
7616   verifyFormat("@{");
7617   verifyFormat("@{}");
7618   verifyFormat("@{@\"one\" : @1}");
7619   verifyFormat("return @{@\"one\" : @1;");
7620   verifyFormat("@{@\"one\" : @1}");
7621
7622   verifyFormat("@{@\"one\" : @{@2 : @1}}");
7623   verifyFormat("@{\n"
7624                "  @\"one\" : @{@2 : @1},\n"
7625                "}");
7626
7627   verifyFormat("@{1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2}");
7628   verifyIncompleteFormat("[self setDict:@{}");
7629   verifyIncompleteFormat("[self setDict:@{@1 : @2}");
7630   verifyFormat("NSLog(@\"%@\", @{@1 : @2, @2 : @3}[@1]);");
7631   verifyFormat(
7632       "NSDictionary *masses = @{@\"H\" : @1.0078, @\"He\" : @4.0026};");
7633   verifyFormat(
7634       "NSDictionary *settings = @{AVEncoderKey : @(AVAudioQualityMax)};");
7635
7636   verifyFormat("NSDictionary *d = @{\n"
7637                "  @\"nam\" : NSUserNam(),\n"
7638                "  @\"dte\" : [NSDate date],\n"
7639                "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
7640                "};");
7641   verifyFormat(
7642       "@{\n"
7643       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
7644       "regularFont,\n"
7645       "};");
7646   verifyGoogleFormat(
7647       "@{\n"
7648       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
7649       "regularFont,\n"
7650       "};");
7651   verifyFormat(
7652       "@{\n"
7653       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :\n"
7654       "      reeeeeeeeeeeeeeeeeeeeeeeegularFont,\n"
7655       "};");
7656
7657   // We should try to be robust in case someone forgets the "@".
7658   verifyFormat("NSDictionary *d = {\n"
7659                "  @\"nam\" : NSUserNam(),\n"
7660                "  @\"dte\" : [NSDate date],\n"
7661                "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
7662                "};");
7663   verifyFormat("NSMutableDictionary *dictionary =\n"
7664                "    [NSMutableDictionary dictionaryWithDictionary:@{\n"
7665                "      aaaaaaaaaaaaaaaaaaaaa : aaaaaaaaaaaaa,\n"
7666                "      bbbbbbbbbbbbbbbbbb : bbbbb,\n"
7667                "      cccccccccccccccc : ccccccccccccccc\n"
7668                "    }];");
7669
7670   // Ensure that casts before the key are kept on the same line as the key.
7671   verifyFormat(
7672       "NSDictionary *d = @{\n"
7673       "  (aaaaaaaa id)aaaaaaaaa : (aaaaaaaa id)aaaaaaaaaaaaaaaaaaaaaaaa,\n"
7674       "  (aaaaaaaa id)aaaaaaaaaaaaaa : (aaaaaaaa id)aaaaaaaaaaaaaa,\n"
7675       "};");
7676 }
7677
7678 TEST_F(FormatTest, ObjCArrayLiterals) {
7679   verifyIncompleteFormat("@[");
7680   verifyFormat("@[]");
7681   verifyFormat(
7682       "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
7683   verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
7684   verifyFormat("NSArray *array = @[ [foo description] ];");
7685
7686   verifyFormat(
7687       "NSArray *some_variable = @[\n"
7688       "  aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
7689       "  @\"aaaaaaaaaaaaaaaaa\",\n"
7690       "  @\"aaaaaaaaaaaaaaaaa\",\n"
7691       "  @\"aaaaaaaaaaaaaaaaa\"\n"
7692       "];");
7693   verifyFormat("NSArray *some_variable = @[\n"
7694                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7695                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7696                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7697                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7698                "];");
7699   verifyGoogleFormat("NSArray *some_variable = @[\n"
7700                      "  @\"aaaaaaaaaaaaaaaaa\",\n"
7701                      "  @\"aaaaaaaaaaaaaaaaa\",\n"
7702                      "  @\"aaaaaaaaaaaaaaaaa\",\n"
7703                      "  @\"aaaaaaaaaaaaaaaaa\"\n"
7704                      "];");
7705   verifyFormat("NSArray *array = @[\n"
7706                "  @\"a\",\n"
7707                "  @\"a\",\n" // Trailing comma -> one per line.
7708                "];");
7709
7710   // We should try to be robust in case someone forgets the "@".
7711   verifyFormat("NSArray *some_variable = [\n"
7712                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7713                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7714                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7715                "  @\"aaaaaaaaaaaaaaaaa\",\n"
7716                "];");
7717   verifyFormat(
7718       "- (NSAttributedString *)attributedStringForSegment:(NSUInteger)segment\n"
7719       "                                             index:(NSUInteger)index\n"
7720       "                                nonDigitAttributes:\n"
7721       "                                    (NSDictionary *)noDigitAttributes;");
7722   verifyFormat("[someFunction someLooooooooooooongParameter:@[\n"
7723                "  NSBundle.mainBundle.infoDictionary[@\"a\"]\n"
7724                "]];");
7725 }
7726
7727 TEST_F(FormatTest, BreaksStringLiterals) {
7728   EXPECT_EQ("\"some text \"\n"
7729             "\"other\";",
7730             format("\"some text other\";", getLLVMStyleWithColumns(12)));
7731   EXPECT_EQ("\"some text \"\n"
7732             "\"other\";",
7733             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
7734   EXPECT_EQ(
7735       "#define A  \\\n"
7736       "  \"some \"  \\\n"
7737       "  \"text \"  \\\n"
7738       "  \"other\";",
7739       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
7740   EXPECT_EQ(
7741       "#define A  \\\n"
7742       "  \"so \"    \\\n"
7743       "  \"text \"  \\\n"
7744       "  \"other\";",
7745       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
7746
7747   EXPECT_EQ("\"some text\"",
7748             format("\"some text\"", getLLVMStyleWithColumns(1)));
7749   EXPECT_EQ("\"some text\"",
7750             format("\"some text\"", getLLVMStyleWithColumns(11)));
7751   EXPECT_EQ("\"some \"\n"
7752             "\"text\"",
7753             format("\"some text\"", getLLVMStyleWithColumns(10)));
7754   EXPECT_EQ("\"some \"\n"
7755             "\"text\"",
7756             format("\"some text\"", getLLVMStyleWithColumns(7)));
7757   EXPECT_EQ("\"some\"\n"
7758             "\" tex\"\n"
7759             "\"t\"",
7760             format("\"some text\"", getLLVMStyleWithColumns(6)));
7761   EXPECT_EQ("\"some\"\n"
7762             "\" tex\"\n"
7763             "\" and\"",
7764             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
7765   EXPECT_EQ("\"some\"\n"
7766             "\"/tex\"\n"
7767             "\"/and\"",
7768             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
7769
7770   EXPECT_EQ("variable =\n"
7771             "    \"long string \"\n"
7772             "    \"literal\";",
7773             format("variable = \"long string literal\";",
7774                    getLLVMStyleWithColumns(20)));
7775
7776   EXPECT_EQ("variable = f(\n"
7777             "    \"long string \"\n"
7778             "    \"literal\",\n"
7779             "    short,\n"
7780             "    loooooooooooooooooooong);",
7781             format("variable = f(\"long string literal\", short, "
7782                    "loooooooooooooooooooong);",
7783                    getLLVMStyleWithColumns(20)));
7784
7785   EXPECT_EQ(
7786       "f(g(\"long string \"\n"
7787       "    \"literal\"),\n"
7788       "  b);",
7789       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
7790   EXPECT_EQ("f(g(\"long string \"\n"
7791             "    \"literal\",\n"
7792             "    a),\n"
7793             "  b);",
7794             format("f(g(\"long string literal\", a), b);",
7795                    getLLVMStyleWithColumns(20)));
7796   EXPECT_EQ(
7797       "f(\"one two\".split(\n"
7798       "    variable));",
7799       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
7800   EXPECT_EQ("f(\"one two three four five six \"\n"
7801             "  \"seven\".split(\n"
7802             "      really_looooong_variable));",
7803             format("f(\"one two three four five six seven\"."
7804                    "split(really_looooong_variable));",
7805                    getLLVMStyleWithColumns(33)));
7806
7807   EXPECT_EQ("f(\"some \"\n"
7808             "  \"text\",\n"
7809             "  other);",
7810             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
7811
7812   // Only break as a last resort.
7813   verifyFormat(
7814       "aaaaaaaaaaaaaaaaaaaa(\n"
7815       "    aaaaaaaaaaaaaaaaaaaa,\n"
7816       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
7817
7818   EXPECT_EQ("\"splitmea\"\n"
7819             "\"trandomp\"\n"
7820             "\"oint\"",
7821             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
7822
7823   EXPECT_EQ("\"split/\"\n"
7824             "\"pathat/\"\n"
7825             "\"slashes\"",
7826             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
7827
7828   EXPECT_EQ("\"split/\"\n"
7829             "\"pathat/\"\n"
7830             "\"slashes\"",
7831             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
7832   EXPECT_EQ("\"split at \"\n"
7833             "\"spaces/at/\"\n"
7834             "\"slashes.at.any$\"\n"
7835             "\"non-alphanumeric%\"\n"
7836             "\"1111111111characte\"\n"
7837             "\"rs\"",
7838             format("\"split at "
7839                    "spaces/at/"
7840                    "slashes.at."
7841                    "any$non-"
7842                    "alphanumeric%"
7843                    "1111111111characte"
7844                    "rs\"",
7845                    getLLVMStyleWithColumns(20)));
7846
7847   // Verify that splitting the strings understands
7848   // Style::AlwaysBreakBeforeMultilineStrings.
7849   EXPECT_EQ(
7850       "aaaaaaaaaaaa(\n"
7851       "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
7852       "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
7853       format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
7854              "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
7855              "aaaaaaaaaaaaaaaaaaaaaa\");",
7856              getGoogleStyle()));
7857   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
7858             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
7859             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
7860                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
7861                    "aaaaaaaaaaaaaaaaaaaaaa\";",
7862                    getGoogleStyle()));
7863   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
7864             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
7865             format("llvm::outs() << "
7866                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
7867                    "aaaaaaaaaaaaaaaaaaa\";"));
7868   EXPECT_EQ("ffff(\n"
7869             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
7870             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
7871             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
7872                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
7873                    getGoogleStyle()));
7874
7875   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
7876   AlignLeft.AlignEscapedNewlinesLeft = true;
7877   EXPECT_EQ("#define A \\\n"
7878             "  \"some \" \\\n"
7879             "  \"text \" \\\n"
7880             "  \"other\";",
7881             format("#define A \"some text other\";", AlignLeft));
7882 }
7883
7884 TEST_F(FormatTest, FullyRemoveEmptyLines) {
7885   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
7886   NoEmptyLines.MaxEmptyLinesToKeep = 0;
7887   EXPECT_EQ("int i = a(b());",
7888             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
7889 }
7890
7891 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
7892   EXPECT_EQ(
7893       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
7894       "(\n"
7895       "    \"x\t\");",
7896       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
7897              "aaaaaaa("
7898              "\"x\t\");"));
7899 }
7900
7901 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
7902   EXPECT_EQ(
7903       "u8\"utf8 string \"\n"
7904       "u8\"literal\";",
7905       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
7906   EXPECT_EQ(
7907       "u\"utf16 string \"\n"
7908       "u\"literal\";",
7909       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
7910   EXPECT_EQ(
7911       "U\"utf32 string \"\n"
7912       "U\"literal\";",
7913       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
7914   EXPECT_EQ("L\"wide string \"\n"
7915             "L\"literal\";",
7916             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
7917   EXPECT_EQ("@\"NSString \"\n"
7918             "@\"literal\";",
7919             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
7920
7921   // This input makes clang-format try to split the incomplete unicode escape
7922   // sequence, which used to lead to a crasher.
7923   verifyNoCrash(
7924       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
7925       getLLVMStyleWithColumns(60));
7926 }
7927
7928 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
7929   FormatStyle Style = getGoogleStyleWithColumns(15);
7930   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
7931   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
7932   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
7933   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
7934   EXPECT_EQ("u8R\"x(raw literal)x\";",
7935             format("u8R\"x(raw literal)x\";", Style));
7936 }
7937
7938 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
7939   FormatStyle Style = getLLVMStyleWithColumns(20);
7940   EXPECT_EQ(
7941       "_T(\"aaaaaaaaaaaaaa\")\n"
7942       "_T(\"aaaaaaaaaaaaaa\")\n"
7943       "_T(\"aaaaaaaaaaaa\")",
7944       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
7945   EXPECT_EQ("f(x, _T(\"aaaaaaaaa\")\n"
7946             "     _T(\"aaaaaa\"),\n"
7947             "  z);",
7948             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
7949
7950   // FIXME: Handle embedded spaces in one iteration.
7951   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
7952   //            "_T(\"aaaaaaaaaaaaa\")\n"
7953   //            "_T(\"aaaaaaaaaaaaa\")\n"
7954   //            "_T(\"a\")",
7955   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
7956   //                   getLLVMStyleWithColumns(20)));
7957   EXPECT_EQ(
7958       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
7959       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
7960   EXPECT_EQ("f(\n"
7961             "#if !TEST\n"
7962             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
7963             "#endif\n"
7964             "    );",
7965             format("f(\n"
7966                    "#if !TEST\n"
7967                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
7968                    "#endif\n"
7969                    ");"));
7970   EXPECT_EQ("f(\n"
7971             "\n"
7972             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
7973             format("f(\n"
7974                    "\n"
7975                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
7976 }
7977
7978 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
7979   EXPECT_EQ(
7980       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
7981       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
7982       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
7983       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
7984              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
7985              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
7986 }
7987
7988 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
7989   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
7990             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
7991   EXPECT_EQ("fffffffffff(g(R\"x(\n"
7992             "multiline raw string literal xxxxxxxxxxxxxx\n"
7993             ")x\",\n"
7994             "              a),\n"
7995             "            b);",
7996             format("fffffffffff(g(R\"x(\n"
7997                    "multiline raw string literal xxxxxxxxxxxxxx\n"
7998                    ")x\", a), b);",
7999                    getGoogleStyleWithColumns(20)));
8000   EXPECT_EQ("fffffffffff(\n"
8001             "    g(R\"x(qqq\n"
8002             "multiline raw string literal xxxxxxxxxxxxxx\n"
8003             ")x\",\n"
8004             "      a),\n"
8005             "    b);",
8006             format("fffffffffff(g(R\"x(qqq\n"
8007                    "multiline raw string literal xxxxxxxxxxxxxx\n"
8008                    ")x\", a), b);",
8009                    getGoogleStyleWithColumns(20)));
8010
8011   EXPECT_EQ("fffffffffff(R\"x(\n"
8012             "multiline raw string literal xxxxxxxxxxxxxx\n"
8013             ")x\");",
8014             format("fffffffffff(R\"x(\n"
8015                    "multiline raw string literal xxxxxxxxxxxxxx\n"
8016                    ")x\");",
8017                    getGoogleStyleWithColumns(20)));
8018   EXPECT_EQ("fffffffffff(R\"x(\n"
8019             "multiline raw string literal xxxxxxxxxxxxxx\n"
8020             ")x\" + bbbbbb);",
8021             format("fffffffffff(R\"x(\n"
8022                    "multiline raw string literal xxxxxxxxxxxxxx\n"
8023                    ")x\" +   bbbbbb);",
8024                    getGoogleStyleWithColumns(20)));
8025   EXPECT_EQ("fffffffffff(\n"
8026             "    R\"x(\n"
8027             "multiline raw string literal xxxxxxxxxxxxxx\n"
8028             ")x\" +\n"
8029             "    bbbbbb);",
8030             format("fffffffffff(\n"
8031                    " R\"x(\n"
8032                    "multiline raw string literal xxxxxxxxxxxxxx\n"
8033                    ")x\" + bbbbbb);",
8034                    getGoogleStyleWithColumns(20)));
8035 }
8036
8037 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
8038   verifyFormat("string a = \"unterminated;");
8039   EXPECT_EQ("function(\"unterminated,\n"
8040             "         OtherParameter);",
8041             format("function(  \"unterminated,\n"
8042                    "    OtherParameter);"));
8043 }
8044
8045 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
8046   FormatStyle Style = getLLVMStyle();
8047   Style.Standard = FormatStyle::LS_Cpp03;
8048   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
8049             format("#define x(_a) printf(\"foo\"_a);", Style));
8050 }
8051
8052 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
8053
8054 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
8055   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
8056             "             \"ddeeefff\");",
8057             format("someFunction(\"aaabbbcccdddeeefff\");",
8058                    getLLVMStyleWithColumns(25)));
8059   EXPECT_EQ("someFunction1234567890(\n"
8060             "    \"aaabbbcccdddeeefff\");",
8061             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
8062                    getLLVMStyleWithColumns(26)));
8063   EXPECT_EQ("someFunction1234567890(\n"
8064             "    \"aaabbbcccdddeeeff\"\n"
8065             "    \"f\");",
8066             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
8067                    getLLVMStyleWithColumns(25)));
8068   EXPECT_EQ("someFunction1234567890(\n"
8069             "    \"aaabbbcccdddeeeff\"\n"
8070             "    \"f\");",
8071             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
8072                    getLLVMStyleWithColumns(24)));
8073   EXPECT_EQ("someFunction(\"aaabbbcc \"\n"
8074             "             \"ddde \"\n"
8075             "             \"efff\");",
8076             format("someFunction(\"aaabbbcc ddde efff\");",
8077                    getLLVMStyleWithColumns(25)));
8078   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
8079             "             \"ddeeefff\");",
8080             format("someFunction(\"aaabbbccc ddeeefff\");",
8081                    getLLVMStyleWithColumns(25)));
8082   EXPECT_EQ("someFunction1234567890(\n"
8083             "    \"aaabb \"\n"
8084             "    \"cccdddeeefff\");",
8085             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
8086                    getLLVMStyleWithColumns(25)));
8087   EXPECT_EQ("#define A          \\\n"
8088             "  string s =       \\\n"
8089             "      \"123456789\"  \\\n"
8090             "      \"0\";         \\\n"
8091             "  int i;",
8092             format("#define A string s = \"1234567890\"; int i;",
8093                    getLLVMStyleWithColumns(20)));
8094   // FIXME: Put additional penalties on breaking at non-whitespace locations.
8095   EXPECT_EQ("someFunction(\"aaabbbcc \"\n"
8096             "             \"dddeeeff\"\n"
8097             "             \"f\");",
8098             format("someFunction(\"aaabbbcc dddeeefff\");",
8099                    getLLVMStyleWithColumns(25)));
8100 }
8101
8102 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
8103   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
8104   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
8105   EXPECT_EQ("\"test\"\n"
8106             "\"\\n\"",
8107             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
8108   EXPECT_EQ("\"tes\\\\\"\n"
8109             "\"n\"",
8110             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
8111   EXPECT_EQ("\"\\\\\\\\\"\n"
8112             "\"\\n\"",
8113             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
8114   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
8115   EXPECT_EQ("\"\\uff01\"\n"
8116             "\"test\"",
8117             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
8118   EXPECT_EQ("\"\\Uff01ff02\"",
8119             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
8120   EXPECT_EQ("\"\\x000000000001\"\n"
8121             "\"next\"",
8122             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
8123   EXPECT_EQ("\"\\x000000000001next\"",
8124             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
8125   EXPECT_EQ("\"\\x000000000001\"",
8126             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
8127   EXPECT_EQ("\"test\"\n"
8128             "\"\\000000\"\n"
8129             "\"000001\"",
8130             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
8131   EXPECT_EQ("\"test\\000\"\n"
8132             "\"00000000\"\n"
8133             "\"1\"",
8134             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
8135 }
8136
8137 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
8138   verifyFormat("void f() {\n"
8139                "  return g() {}\n"
8140                "  void h() {}");
8141   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
8142                "g();\n"
8143                "}");
8144 }
8145
8146 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
8147   verifyFormat(
8148       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
8149 }
8150
8151 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
8152   verifyFormat("class X {\n"
8153                "  void f() {\n"
8154                "  }\n"
8155                "};",
8156                getLLVMStyleWithColumns(12));
8157 }
8158
8159 TEST_F(FormatTest, ConfigurableIndentWidth) {
8160   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
8161   EightIndent.IndentWidth = 8;
8162   EightIndent.ContinuationIndentWidth = 8;
8163   verifyFormat("void f() {\n"
8164                "        someFunction();\n"
8165                "        if (true) {\n"
8166                "                f();\n"
8167                "        }\n"
8168                "}",
8169                EightIndent);
8170   verifyFormat("class X {\n"
8171                "        void f() {\n"
8172                "        }\n"
8173                "};",
8174                EightIndent);
8175   verifyFormat("int x[] = {\n"
8176                "        call(),\n"
8177                "        call()};",
8178                EightIndent);
8179 }
8180
8181 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
8182   verifyFormat("double\n"
8183                "f();",
8184                getLLVMStyleWithColumns(8));
8185 }
8186
8187 TEST_F(FormatTest, ConfigurableUseOfTab) {
8188   FormatStyle Tab = getLLVMStyleWithColumns(42);
8189   Tab.IndentWidth = 8;
8190   Tab.UseTab = FormatStyle::UT_Always;
8191   Tab.AlignEscapedNewlinesLeft = true;
8192
8193   EXPECT_EQ("if (aaaaaaaa && // q\n"
8194             "    bb)\t\t// w\n"
8195             "\t;",
8196             format("if (aaaaaaaa &&// q\n"
8197                    "bb)// w\n"
8198                    ";",
8199                    Tab));
8200   EXPECT_EQ("if (aaa && bbb) // w\n"
8201             "\t;",
8202             format("if(aaa&&bbb)// w\n"
8203                    ";",
8204                    Tab));
8205
8206   verifyFormat("class X {\n"
8207                "\tvoid f() {\n"
8208                "\t\tsomeFunction(parameter1,\n"
8209                "\t\t\t     parameter2);\n"
8210                "\t}\n"
8211                "};",
8212                Tab);
8213   verifyFormat("#define A                        \\\n"
8214                "\tvoid f() {               \\\n"
8215                "\t\tsomeFunction(    \\\n"
8216                "\t\t    parameter1,  \\\n"
8217                "\t\t    parameter2); \\\n"
8218                "\t}",
8219                Tab);
8220
8221   Tab.TabWidth = 4;
8222   Tab.IndentWidth = 8;
8223   verifyFormat("class TabWidth4Indent8 {\n"
8224                "\t\tvoid f() {\n"
8225                "\t\t\t\tsomeFunction(parameter1,\n"
8226                "\t\t\t\t\t\t\t parameter2);\n"
8227                "\t\t}\n"
8228                "};",
8229                Tab);
8230
8231   Tab.TabWidth = 4;
8232   Tab.IndentWidth = 4;
8233   verifyFormat("class TabWidth4Indent4 {\n"
8234                "\tvoid f() {\n"
8235                "\t\tsomeFunction(parameter1,\n"
8236                "\t\t\t\t\t parameter2);\n"
8237                "\t}\n"
8238                "};",
8239                Tab);
8240
8241   Tab.TabWidth = 8;
8242   Tab.IndentWidth = 4;
8243   verifyFormat("class TabWidth8Indent4 {\n"
8244                "    void f() {\n"
8245                "\tsomeFunction(parameter1,\n"
8246                "\t\t     parameter2);\n"
8247                "    }\n"
8248                "};",
8249                Tab);
8250
8251   Tab.TabWidth = 8;
8252   Tab.IndentWidth = 8;
8253   EXPECT_EQ("/*\n"
8254             "\t      a\t\tcomment\n"
8255             "\t      in multiple lines\n"
8256             "       */",
8257             format("   /*\t \t \n"
8258                    " \t \t a\t\tcomment\t \t\n"
8259                    " \t \t in multiple lines\t\n"
8260                    " \t  */",
8261                    Tab));
8262
8263   Tab.UseTab = FormatStyle::UT_ForIndentation;
8264   verifyFormat("{\n"
8265                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8266                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8267                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8268                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8269                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8270                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
8271                "};",
8272                Tab);
8273   verifyFormat("enum A {\n"
8274                "\ta1, // Force multiple lines\n"
8275                "\ta2,\n"
8276                "\ta3\n"
8277                "};",
8278                Tab);
8279   EXPECT_EQ("if (aaaaaaaa && // q\n"
8280             "    bb)         // w\n"
8281             "\t;",
8282             format("if (aaaaaaaa &&// q\n"
8283                    "bb)// w\n"
8284                    ";",
8285                    Tab));
8286   verifyFormat("class X {\n"
8287                "\tvoid f() {\n"
8288                "\t\tsomeFunction(parameter1,\n"
8289                "\t\t             parameter2);\n"
8290                "\t}\n"
8291                "};",
8292                Tab);
8293   verifyFormat("{\n"
8294                "\tQ(\n"
8295                "\t    {\n"
8296                "\t\t    int a;\n"
8297                "\t\t    someFunction(aaaaaaaa,\n"
8298                "\t\t                 bbbbbbb);\n"
8299                "\t    },\n"
8300                "\t    p);\n"
8301                "}",
8302                Tab);
8303   EXPECT_EQ("{\n"
8304             "\t/* aaaa\n"
8305             "\t   bbbb */\n"
8306             "}",
8307             format("{\n"
8308                    "/* aaaa\n"
8309                    "   bbbb */\n"
8310                    "}",
8311                    Tab));
8312   EXPECT_EQ("{\n"
8313             "\t/*\n"
8314             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8315             "\t  bbbbbbbbbbbbb\n"
8316             "\t*/\n"
8317             "}",
8318             format("{\n"
8319                    "/*\n"
8320                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
8321                    "*/\n"
8322                    "}",
8323                    Tab));
8324   EXPECT_EQ("{\n"
8325             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8326             "\t// bbbbbbbbbbbbb\n"
8327             "}",
8328             format("{\n"
8329                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
8330                    "}",
8331                    Tab));
8332   EXPECT_EQ("{\n"
8333             "\t/*\n"
8334             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8335             "\t  bbbbbbbbbbbbb\n"
8336             "\t*/\n"
8337             "}",
8338             format("{\n"
8339                    "\t/*\n"
8340                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
8341                    "\t*/\n"
8342                    "}",
8343                    Tab));
8344   EXPECT_EQ("{\n"
8345             "\t/*\n"
8346             "\n"
8347             "\t*/\n"
8348             "}",
8349             format("{\n"
8350                    "\t/*\n"
8351                    "\n"
8352                    "\t*/\n"
8353                    "}",
8354                    Tab));
8355   EXPECT_EQ("{\n"
8356             "\t/*\n"
8357             " asdf\n"
8358             "\t*/\n"
8359             "}",
8360             format("{\n"
8361                    "\t/*\n"
8362                    " asdf\n"
8363                    "\t*/\n"
8364                    "}",
8365                    Tab));
8366
8367   Tab.UseTab = FormatStyle::UT_Never;
8368   EXPECT_EQ("/*\n"
8369             "              a\t\tcomment\n"
8370             "              in multiple lines\n"
8371             "       */",
8372             format("   /*\t \t \n"
8373                    " \t \t a\t\tcomment\t \t\n"
8374                    " \t \t in multiple lines\t\n"
8375                    " \t  */",
8376                    Tab));
8377   EXPECT_EQ("/* some\n"
8378             "   comment */",
8379             format(" \t \t /* some\n"
8380                    " \t \t    comment */",
8381                    Tab));
8382   EXPECT_EQ("int a; /* some\n"
8383             "   comment */",
8384             format(" \t \t int a; /* some\n"
8385                    " \t \t    comment */",
8386                    Tab));
8387
8388   EXPECT_EQ("int a; /* some\n"
8389             "comment */",
8390             format(" \t \t int\ta; /* some\n"
8391                    " \t \t    comment */",
8392                    Tab));
8393   EXPECT_EQ("f(\"\t\t\"); /* some\n"
8394             "    comment */",
8395             format(" \t \t f(\"\t\t\"); /* some\n"
8396                    " \t \t    comment */",
8397                    Tab));
8398   EXPECT_EQ("{\n"
8399             "  /*\n"
8400             "   * Comment\n"
8401             "   */\n"
8402             "  int i;\n"
8403             "}",
8404             format("{\n"
8405                    "\t/*\n"
8406                    "\t * Comment\n"
8407                    "\t */\n"
8408                    "\t int i;\n"
8409                    "}"));
8410 }
8411
8412 TEST_F(FormatTest, CalculatesOriginalColumn) {
8413   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8414             "q\"; /* some\n"
8415             "       comment */",
8416             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8417                    "q\"; /* some\n"
8418                    "       comment */",
8419                    getLLVMStyle()));
8420   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
8421             "/* some\n"
8422             "   comment */",
8423             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
8424                    " /* some\n"
8425                    "    comment */",
8426                    getLLVMStyle()));
8427   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8428             "qqq\n"
8429             "/* some\n"
8430             "   comment */",
8431             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8432                    "qqq\n"
8433                    " /* some\n"
8434                    "    comment */",
8435                    getLLVMStyle()));
8436   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8437             "wwww; /* some\n"
8438             "         comment */",
8439             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
8440                    "wwww; /* some\n"
8441                    "         comment */",
8442                    getLLVMStyle()));
8443 }
8444
8445 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
8446   FormatStyle NoSpace = getLLVMStyle();
8447   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
8448
8449   verifyFormat("while(true)\n"
8450                "  continue;",
8451                NoSpace);
8452   verifyFormat("for(;;)\n"
8453                "  continue;",
8454                NoSpace);
8455   verifyFormat("if(true)\n"
8456                "  f();\n"
8457                "else if(true)\n"
8458                "  f();",
8459                NoSpace);
8460   verifyFormat("do {\n"
8461                "  do_something();\n"
8462                "} while(something());",
8463                NoSpace);
8464   verifyFormat("switch(x) {\n"
8465                "default:\n"
8466                "  break;\n"
8467                "}",
8468                NoSpace);
8469   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
8470   verifyFormat("size_t x = sizeof(x);", NoSpace);
8471   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
8472   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
8473   verifyFormat("alignas(128) char a[128];", NoSpace);
8474   verifyFormat("size_t x = alignof(MyType);", NoSpace);
8475   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
8476   verifyFormat("int f() throw(Deprecated);", NoSpace);
8477   verifyFormat("typedef void (*cb)(int);", NoSpace);
8478   verifyFormat("T A::operator()();", NoSpace);
8479   verifyFormat("X A::operator++(T);", NoSpace);
8480
8481   FormatStyle Space = getLLVMStyle();
8482   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
8483
8484   verifyFormat("int f ();", Space);
8485   verifyFormat("void f (int a, T b) {\n"
8486                "  while (true)\n"
8487                "    continue;\n"
8488                "}",
8489                Space);
8490   verifyFormat("if (true)\n"
8491                "  f ();\n"
8492                "else if (true)\n"
8493                "  f ();",
8494                Space);
8495   verifyFormat("do {\n"
8496                "  do_something ();\n"
8497                "} while (something ());",
8498                Space);
8499   verifyFormat("switch (x) {\n"
8500                "default:\n"
8501                "  break;\n"
8502                "}",
8503                Space);
8504   verifyFormat("A::A () : a (1) {}", Space);
8505   verifyFormat("void f () __attribute__ ((asdf));", Space);
8506   verifyFormat("*(&a + 1);\n"
8507                "&((&a)[1]);\n"
8508                "a[(b + c) * d];\n"
8509                "(((a + 1) * 2) + 3) * 4;",
8510                Space);
8511   verifyFormat("#define A(x) x", Space);
8512   verifyFormat("#define A (x) x", Space);
8513   verifyFormat("#if defined(x)\n"
8514                "#endif",
8515                Space);
8516   verifyFormat("auto i = std::make_unique<int> (5);", Space);
8517   verifyFormat("size_t x = sizeof (x);", Space);
8518   verifyFormat("auto f (int x) -> decltype (x);", Space);
8519   verifyFormat("int f (T x) noexcept (x.create ());", Space);
8520   verifyFormat("alignas (128) char a[128];", Space);
8521   verifyFormat("size_t x = alignof (MyType);", Space);
8522   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
8523   verifyFormat("int f () throw (Deprecated);", Space);
8524   verifyFormat("typedef void (*cb) (int);", Space);
8525   verifyFormat("T A::operator() ();", Space);
8526   verifyFormat("X A::operator++ (T);", Space);
8527 }
8528
8529 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
8530   FormatStyle Spaces = getLLVMStyle();
8531
8532   Spaces.SpacesInParentheses = true;
8533   verifyFormat("call( x, y, z );", Spaces);
8534   verifyFormat("call();", Spaces);
8535   verifyFormat("std::function<void( int, int )> callback;", Spaces);
8536   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
8537                Spaces);
8538   verifyFormat("while ( (bool)1 )\n"
8539                "  continue;",
8540                Spaces);
8541   verifyFormat("for ( ;; )\n"
8542                "  continue;",
8543                Spaces);
8544   verifyFormat("if ( true )\n"
8545                "  f();\n"
8546                "else if ( true )\n"
8547                "  f();",
8548                Spaces);
8549   verifyFormat("do {\n"
8550                "  do_something( (int)i );\n"
8551                "} while ( something() );",
8552                Spaces);
8553   verifyFormat("switch ( x ) {\n"
8554                "default:\n"
8555                "  break;\n"
8556                "}",
8557                Spaces);
8558
8559   Spaces.SpacesInParentheses = false;
8560   Spaces.SpacesInCStyleCastParentheses = true;
8561   verifyFormat("Type *A = ( Type * )P;", Spaces);
8562   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
8563   verifyFormat("x = ( int32 )y;", Spaces);
8564   verifyFormat("int a = ( int )(2.0f);", Spaces);
8565   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
8566   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
8567   verifyFormat("#define x (( int )-1)", Spaces);
8568
8569   // Run the first set of tests again with:
8570   Spaces.SpacesInParentheses = false, Spaces.SpaceInEmptyParentheses = true;
8571   Spaces.SpacesInCStyleCastParentheses = true;
8572   verifyFormat("call(x, y, z);", Spaces);
8573   verifyFormat("call( );", Spaces);
8574   verifyFormat("std::function<void(int, int)> callback;", Spaces);
8575   verifyFormat("while (( bool )1)\n"
8576                "  continue;",
8577                Spaces);
8578   verifyFormat("for (;;)\n"
8579                "  continue;",
8580                Spaces);
8581   verifyFormat("if (true)\n"
8582                "  f( );\n"
8583                "else if (true)\n"
8584                "  f( );",
8585                Spaces);
8586   verifyFormat("do {\n"
8587                "  do_something(( int )i);\n"
8588                "} while (something( ));",
8589                Spaces);
8590   verifyFormat("switch (x) {\n"
8591                "default:\n"
8592                "  break;\n"
8593                "}",
8594                Spaces);
8595
8596   // Run the first set of tests again with:
8597   Spaces.SpaceAfterCStyleCast = true;
8598   verifyFormat("call(x, y, z);", Spaces);
8599   verifyFormat("call( );", Spaces);
8600   verifyFormat("std::function<void(int, int)> callback;", Spaces);
8601   verifyFormat("while (( bool ) 1)\n"
8602                "  continue;",
8603                Spaces);
8604   verifyFormat("for (;;)\n"
8605                "  continue;",
8606                Spaces);
8607   verifyFormat("if (true)\n"
8608                "  f( );\n"
8609                "else if (true)\n"
8610                "  f( );",
8611                Spaces);
8612   verifyFormat("do {\n"
8613                "  do_something(( int ) i);\n"
8614                "} while (something( ));",
8615                Spaces);
8616   verifyFormat("switch (x) {\n"
8617                "default:\n"
8618                "  break;\n"
8619                "}",
8620                Spaces);
8621
8622   // Run subset of tests again with:
8623   Spaces.SpacesInCStyleCastParentheses = false;
8624   Spaces.SpaceAfterCStyleCast = true;
8625   verifyFormat("while ((bool) 1)\n"
8626                "  continue;",
8627                Spaces);
8628   verifyFormat("do {\n"
8629                "  do_something((int) i);\n"
8630                "} while (something( ));",
8631                Spaces);
8632 }
8633
8634 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
8635   verifyFormat("int a[5];");
8636   verifyFormat("a[3] += 42;");
8637
8638   FormatStyle Spaces = getLLVMStyle();
8639   Spaces.SpacesInSquareBrackets = true;
8640   // Lambdas unchanged.
8641   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
8642   verifyFormat("return [i, args...] {};", Spaces);
8643
8644   // Not lambdas.
8645   verifyFormat("int a[ 5 ];", Spaces);
8646   verifyFormat("a[ 3 ] += 42;", Spaces);
8647   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
8648   verifyFormat("double &operator[](int i) { return 0; }\n"
8649                "int i;",
8650                Spaces);
8651   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
8652   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
8653   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
8654 }
8655
8656 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
8657   verifyFormat("int a = 5;");
8658   verifyFormat("a += 42;");
8659   verifyFormat("a or_eq 8;");
8660
8661   FormatStyle Spaces = getLLVMStyle();
8662   Spaces.SpaceBeforeAssignmentOperators = false;
8663   verifyFormat("int a= 5;", Spaces);
8664   verifyFormat("a+= 42;", Spaces);
8665   verifyFormat("a or_eq 8;", Spaces);
8666 }
8667
8668 TEST_F(FormatTest, AlignConsecutiveAssignments) {
8669   FormatStyle Alignment = getLLVMStyle();
8670   Alignment.AlignConsecutiveAssignments = false;
8671   verifyFormat("int a = 5;\n"
8672                "int oneTwoThree = 123;",
8673                Alignment);
8674   verifyFormat("int a = 5;\n"
8675                "int oneTwoThree = 123;",
8676                Alignment);
8677
8678   Alignment.AlignConsecutiveAssignments = true;
8679   verifyFormat("int a           = 5;\n"
8680                "int oneTwoThree = 123;",
8681                Alignment);
8682   verifyFormat("int a           = method();\n"
8683                "int oneTwoThree = 133;",
8684                Alignment);
8685   verifyFormat("a &= 5;\n"
8686                "bcd *= 5;\n"
8687                "ghtyf += 5;\n"
8688                "dvfvdb -= 5;\n"
8689                "a /= 5;\n"
8690                "vdsvsv %= 5;\n"
8691                "sfdbddfbdfbb ^= 5;\n"
8692                "dvsdsv |= 5;\n"
8693                "int dsvvdvsdvvv = 123;",
8694                Alignment);
8695   verifyFormat("int i = 1, j = 10;\n"
8696                "something = 2000;",
8697                Alignment);
8698   verifyFormat("something = 2000;\n"
8699                "int i = 1, j = 10;\n",
8700                Alignment);
8701   verifyFormat("something = 2000;\n"
8702                "another   = 911;\n"
8703                "int i = 1, j = 10;\n"
8704                "oneMore = 1;\n"
8705                "i       = 2;",
8706                Alignment);
8707   verifyFormat("int a   = 5;\n"
8708                "int one = 1;\n"
8709                "method();\n"
8710                "int oneTwoThree = 123;\n"
8711                "int oneTwo      = 12;",
8712                Alignment);
8713   verifyFormat("int oneTwoThree = 123;\n"
8714                "int oneTwo      = 12;\n"
8715                "method();\n",
8716                Alignment);
8717   verifyFormat("int oneTwoThree = 123; // comment\n"
8718                "int oneTwo      = 12;  // comment",
8719                Alignment);
8720   EXPECT_EQ("int a = 5;\n"
8721             "\n"
8722             "int oneTwoThree = 123;",
8723             format("int a       = 5;\n"
8724                    "\n"
8725                    "int oneTwoThree= 123;",
8726                    Alignment));
8727   EXPECT_EQ("int a   = 5;\n"
8728             "int one = 1;\n"
8729             "\n"
8730             "int oneTwoThree = 123;",
8731             format("int a = 5;\n"
8732                    "int one = 1;\n"
8733                    "\n"
8734                    "int oneTwoThree = 123;",
8735                    Alignment));
8736   EXPECT_EQ("int a   = 5;\n"
8737             "int one = 1;\n"
8738             "\n"
8739             "int oneTwoThree = 123;\n"
8740             "int oneTwo      = 12;",
8741             format("int a = 5;\n"
8742                    "int one = 1;\n"
8743                    "\n"
8744                    "int oneTwoThree = 123;\n"
8745                    "int oneTwo = 12;",
8746                    Alignment));
8747   Alignment.AlignEscapedNewlinesLeft = true;
8748   verifyFormat("#define A               \\\n"
8749                "  int aaaa       = 12;  \\\n"
8750                "  int b          = 23;  \\\n"
8751                "  int ccc        = 234; \\\n"
8752                "  int dddddddddd = 2345;",
8753                Alignment);
8754   Alignment.AlignEscapedNewlinesLeft = false;
8755   verifyFormat("#define A                                                      "
8756                "                \\\n"
8757                "  int aaaa       = 12;                                         "
8758                "                \\\n"
8759                "  int b          = 23;                                         "
8760                "                \\\n"
8761                "  int ccc        = 234;                                        "
8762                "                \\\n"
8763                "  int dddddddddd = 2345;",
8764                Alignment);
8765   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
8766                "k = 4, int l = 5,\n"
8767                "                  int m = 6) {\n"
8768                "  int j      = 10;\n"
8769                "  otherThing = 1;\n"
8770                "}",
8771                Alignment);
8772   verifyFormat("void SomeFunction(int parameter = 0) {\n"
8773                "  int i   = 1;\n"
8774                "  int j   = 2;\n"
8775                "  int big = 10000;\n"
8776                "}",
8777                Alignment);
8778   verifyFormat("class C {\n"
8779                "public:\n"
8780                "  int i            = 1;\n"
8781                "  virtual void f() = 0;\n"
8782                "};",
8783                Alignment);
8784   verifyFormat("int i = 1;\n"
8785                "if (SomeType t = getSomething()) {\n"
8786                "}\n"
8787                "int j   = 2;\n"
8788                "int big = 10000;",
8789                Alignment);
8790   verifyFormat("int j = 7;\n"
8791                "for (int k = 0; k < N; ++k) {\n"
8792                "}\n"
8793                "int j   = 2;\n"
8794                "int big = 10000;\n"
8795                "}",
8796                Alignment);
8797   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
8798   verifyFormat("int i = 1;\n"
8799                "LooooooooooongType loooooooooooooooooooooongVariable\n"
8800                "    = someLooooooooooooooooongFunction();\n"
8801                "int j = 2;",
8802                Alignment);
8803   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
8804   verifyFormat("int i = 1;\n"
8805                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
8806                "    someLooooooooooooooooongFunction();\n"
8807                "int j = 2;",
8808                Alignment);
8809
8810   verifyFormat("auto lambda = []() {\n"
8811                "  auto i = 0;\n"
8812                "  return 0;\n"
8813                "};\n"
8814                "int i  = 0;\n"
8815                "auto v = type{\n"
8816                "    i = 1,   //\n"
8817                "    (i = 2), //\n"
8818                "    i = 3    //\n"
8819                "};",
8820                Alignment);
8821
8822   // FIXME: Should align all three assignments
8823   verifyFormat(
8824       "int i      = 1;\n"
8825       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
8826       "                          loooooooooooooooooooooongParameterB);\n"
8827       "int j = 2;",
8828       Alignment);
8829
8830   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
8831                "          typename B   = very_long_type_name_1,\n"
8832                "          typename T_2 = very_long_type_name_2>\n"
8833                "auto foo() {}\n",
8834                Alignment);
8835   verifyFormat("int a, b = 1;\n"
8836                "int c  = 2;\n"
8837                "int dd = 3;\n",
8838                Alignment);
8839   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
8840                "float b[1][] = {{3.f}};\n",
8841                Alignment);
8842 }
8843
8844 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
8845   FormatStyle Alignment = getLLVMStyle();
8846   Alignment.AlignConsecutiveDeclarations = false;
8847   verifyFormat("float const a = 5;\n"
8848                "int oneTwoThree = 123;",
8849                Alignment);
8850   verifyFormat("int a = 5;\n"
8851                "float const oneTwoThree = 123;",
8852                Alignment);
8853
8854   Alignment.AlignConsecutiveDeclarations = true;
8855   verifyFormat("float const a = 5;\n"
8856                "int         oneTwoThree = 123;",
8857                Alignment);
8858   verifyFormat("int         a = method();\n"
8859                "float const oneTwoThree = 133;",
8860                Alignment);
8861   verifyFormat("int i = 1, j = 10;\n"
8862                "something = 2000;",
8863                Alignment);
8864   verifyFormat("something = 2000;\n"
8865                "int i = 1, j = 10;\n",
8866                Alignment);
8867   verifyFormat("float      something = 2000;\n"
8868                "double     another = 911;\n"
8869                "int        i = 1, j = 10;\n"
8870                "const int *oneMore = 1;\n"
8871                "unsigned   i = 2;",
8872                Alignment);
8873   verifyFormat("float a = 5;\n"
8874                "int   one = 1;\n"
8875                "method();\n"
8876                "const double       oneTwoThree = 123;\n"
8877                "const unsigned int oneTwo = 12;",
8878                Alignment);
8879   verifyFormat("int      oneTwoThree{0}; // comment\n"
8880                "unsigned oneTwo;         // comment",
8881                Alignment);
8882   EXPECT_EQ("float const a = 5;\n"
8883             "\n"
8884             "int oneTwoThree = 123;",
8885             format("float const   a = 5;\n"
8886                    "\n"
8887                    "int           oneTwoThree= 123;",
8888                    Alignment));
8889   EXPECT_EQ("float a = 5;\n"
8890             "int   one = 1;\n"
8891             "\n"
8892             "unsigned oneTwoThree = 123;",
8893             format("float    a = 5;\n"
8894                    "int      one = 1;\n"
8895                    "\n"
8896                    "unsigned oneTwoThree = 123;",
8897                    Alignment));
8898   EXPECT_EQ("float a = 5;\n"
8899             "int   one = 1;\n"
8900             "\n"
8901             "unsigned oneTwoThree = 123;\n"
8902             "int      oneTwo = 12;",
8903             format("float    a = 5;\n"
8904                    "int one = 1;\n"
8905                    "\n"
8906                    "unsigned oneTwoThree = 123;\n"
8907                    "int oneTwo = 12;",
8908                    Alignment));
8909   Alignment.AlignConsecutiveAssignments = true;
8910   verifyFormat("float      something = 2000;\n"
8911                "double     another   = 911;\n"
8912                "int        i = 1, j = 10;\n"
8913                "const int *oneMore = 1;\n"
8914                "unsigned   i       = 2;",
8915                Alignment);
8916   verifyFormat("int      oneTwoThree = {0}; // comment\n"
8917                "unsigned oneTwo      = 0;   // comment",
8918                Alignment);
8919   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
8920             "  int const i   = 1;\n"
8921             "  int *     j   = 2;\n"
8922             "  int       big = 10000;\n"
8923             "\n"
8924             "  unsigned oneTwoThree = 123;\n"
8925             "  int      oneTwo      = 12;\n"
8926             "  method();\n"
8927             "  float k  = 2;\n"
8928             "  int   ll = 10000;\n"
8929             "}",
8930             format("void SomeFunction(int parameter= 0) {\n"
8931                    " int const  i= 1;\n"
8932                    "  int *j=2;\n"
8933                    " int big  =  10000;\n"
8934                    "\n"
8935                    "unsigned oneTwoThree  =123;\n"
8936                    "int oneTwo = 12;\n"
8937                    "  method();\n"
8938                    "float k= 2;\n"
8939                    "int ll=10000;\n"
8940                    "}",
8941                    Alignment));
8942   Alignment.AlignConsecutiveAssignments = false;
8943   Alignment.AlignEscapedNewlinesLeft = true;
8944   verifyFormat("#define A              \\\n"
8945                "  int       aaaa = 12; \\\n"
8946                "  float     b = 23;    \\\n"
8947                "  const int ccc = 234; \\\n"
8948                "  unsigned  dddddddddd = 2345;",
8949                Alignment);
8950   Alignment.AlignEscapedNewlinesLeft = false;
8951   Alignment.ColumnLimit = 30;
8952   verifyFormat("#define A                    \\\n"
8953                "  int       aaaa = 12;       \\\n"
8954                "  float     b = 23;          \\\n"
8955                "  const int ccc = 234;       \\\n"
8956                "  int       dddddddddd = 2345;",
8957                Alignment);
8958   Alignment.ColumnLimit = 80;
8959   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
8960                "k = 4, int l = 5,\n"
8961                "                  int m = 6) {\n"
8962                "  const int j = 10;\n"
8963                "  otherThing = 1;\n"
8964                "}",
8965                Alignment);
8966   verifyFormat("void SomeFunction(int parameter = 0) {\n"
8967                "  int const i = 1;\n"
8968                "  int *     j = 2;\n"
8969                "  int       big = 10000;\n"
8970                "}",
8971                Alignment);
8972   verifyFormat("class C {\n"
8973                "public:\n"
8974                "  int          i = 1;\n"
8975                "  virtual void f() = 0;\n"
8976                "};",
8977                Alignment);
8978   verifyFormat("float i = 1;\n"
8979                "if (SomeType t = getSomething()) {\n"
8980                "}\n"
8981                "const unsigned j = 2;\n"
8982                "int            big = 10000;",
8983                Alignment);
8984   verifyFormat("float j = 7;\n"
8985                "for (int k = 0; k < N; ++k) {\n"
8986                "}\n"
8987                "unsigned j = 2;\n"
8988                "int      big = 10000;\n"
8989                "}",
8990                Alignment);
8991   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
8992   verifyFormat("float              i = 1;\n"
8993                "LooooooooooongType loooooooooooooooooooooongVariable\n"
8994                "    = someLooooooooooooooooongFunction();\n"
8995                "int j = 2;",
8996                Alignment);
8997   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
8998   verifyFormat("int                i = 1;\n"
8999                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
9000                "    someLooooooooooooooooongFunction();\n"
9001                "int j = 2;",
9002                Alignment);
9003
9004   Alignment.AlignConsecutiveAssignments = true;
9005   verifyFormat("auto lambda = []() {\n"
9006                "  auto  ii = 0;\n"
9007                "  float j  = 0;\n"
9008                "  return 0;\n"
9009                "};\n"
9010                "int   i  = 0;\n"
9011                "float i2 = 0;\n"
9012                "auto  v  = type{\n"
9013                "    i = 1,   //\n"
9014                "    (i = 2), //\n"
9015                "    i = 3    //\n"
9016                "};",
9017                Alignment);
9018   Alignment.AlignConsecutiveAssignments = false;
9019
9020   // FIXME: Should align all three declarations
9021   verifyFormat(
9022       "int      i = 1;\n"
9023       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
9024       "                          loooooooooooooooooooooongParameterB);\n"
9025       "int j = 2;",
9026       Alignment);
9027
9028   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
9029   // We expect declarations and assignments to align, as long as it doesn't
9030   // exceed the column limit, starting a new alignemnt sequence whenever it
9031   // happens.
9032   Alignment.AlignConsecutiveAssignments = true;
9033   Alignment.ColumnLimit = 30;
9034   verifyFormat("float    ii              = 1;\n"
9035                "unsigned j               = 2;\n"
9036                "int someVerylongVariable = 1;\n"
9037                "AnotherLongType  ll = 123456;\n"
9038                "VeryVeryLongType k  = 2;\n"
9039                "int              myvar = 1;",
9040                Alignment);
9041   Alignment.ColumnLimit = 80;
9042   Alignment.AlignConsecutiveAssignments = false;
9043
9044   verifyFormat(
9045       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
9046       "          typename LongType, typename B>\n"
9047       "auto foo() {}\n",
9048       Alignment);
9049   verifyFormat("float a, b = 1;\n"
9050                "int   c = 2;\n"
9051                "int   dd = 3;\n",
9052                Alignment);
9053   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
9054                "float b[1][] = {{3.f}};\n",
9055                Alignment);
9056   Alignment.AlignConsecutiveAssignments = true;
9057   verifyFormat("float a, b = 1;\n"
9058                "int   c  = 2;\n"
9059                "int   dd = 3;\n",
9060                Alignment);
9061   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
9062                "float b[1][] = {{3.f}};\n",
9063                Alignment);
9064   Alignment.AlignConsecutiveAssignments = false;
9065
9066   Alignment.ColumnLimit = 30;
9067   Alignment.BinPackParameters = false;
9068   verifyFormat("void foo(float     a,\n"
9069                "         float     b,\n"
9070                "         int       c,\n"
9071                "         uint32_t *d) {\n"
9072                "  int *  e = 0;\n"
9073                "  float  f = 0;\n"
9074                "  double g = 0;\n"
9075                "}\n"
9076                "void bar(ino_t     a,\n"
9077                "         int       b,\n"
9078                "         uint32_t *c,\n"
9079                "         bool      d) {}\n",
9080                Alignment);
9081   Alignment.BinPackParameters = true;
9082   Alignment.ColumnLimit = 80;
9083 }
9084
9085 TEST_F(FormatTest, LinuxBraceBreaking) {
9086   FormatStyle LinuxBraceStyle = getLLVMStyle();
9087   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
9088   verifyFormat("namespace a\n"
9089                "{\n"
9090                "class A\n"
9091                "{\n"
9092                "  void f()\n"
9093                "  {\n"
9094                "    if (true) {\n"
9095                "      a();\n"
9096                "      b();\n"
9097                "    } else {\n"
9098                "      a();\n"
9099                "    }\n"
9100                "  }\n"
9101                "  void g() { return; }\n"
9102                "};\n"
9103                "struct B {\n"
9104                "  int x;\n"
9105                "};\n"
9106                "}\n",
9107                LinuxBraceStyle);
9108   verifyFormat("enum X {\n"
9109                "  Y = 0,\n"
9110                "}\n",
9111                LinuxBraceStyle);
9112   verifyFormat("struct S {\n"
9113                "  int Type;\n"
9114                "  union {\n"
9115                "    int x;\n"
9116                "    double y;\n"
9117                "  } Value;\n"
9118                "  class C\n"
9119                "  {\n"
9120                "    MyFavoriteType Value;\n"
9121                "  } Class;\n"
9122                "}\n",
9123                LinuxBraceStyle);
9124 }
9125
9126 TEST_F(FormatTest, MozillaBraceBreaking) {
9127   FormatStyle MozillaBraceStyle = getLLVMStyle();
9128   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
9129   verifyFormat("namespace a {\n"
9130                "class A\n"
9131                "{\n"
9132                "  void f()\n"
9133                "  {\n"
9134                "    if (true) {\n"
9135                "      a();\n"
9136                "      b();\n"
9137                "    }\n"
9138                "  }\n"
9139                "  void g() { return; }\n"
9140                "};\n"
9141                "enum E\n"
9142                "{\n"
9143                "  A,\n"
9144                "  // foo\n"
9145                "  B,\n"
9146                "  C\n"
9147                "};\n"
9148                "struct B\n"
9149                "{\n"
9150                "  int x;\n"
9151                "};\n"
9152                "}\n",
9153                MozillaBraceStyle);
9154   verifyFormat("struct S\n"
9155                "{\n"
9156                "  int Type;\n"
9157                "  union\n"
9158                "  {\n"
9159                "    int x;\n"
9160                "    double y;\n"
9161                "  } Value;\n"
9162                "  class C\n"
9163                "  {\n"
9164                "    MyFavoriteType Value;\n"
9165                "  } Class;\n"
9166                "}\n",
9167                MozillaBraceStyle);
9168 }
9169
9170 TEST_F(FormatTest, StroustrupBraceBreaking) {
9171   FormatStyle StroustrupBraceStyle = getLLVMStyle();
9172   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
9173   verifyFormat("namespace a {\n"
9174                "class A {\n"
9175                "  void f()\n"
9176                "  {\n"
9177                "    if (true) {\n"
9178                "      a();\n"
9179                "      b();\n"
9180                "    }\n"
9181                "  }\n"
9182                "  void g() { return; }\n"
9183                "};\n"
9184                "struct B {\n"
9185                "  int x;\n"
9186                "};\n"
9187                "}\n",
9188                StroustrupBraceStyle);
9189
9190   verifyFormat("void foo()\n"
9191                "{\n"
9192                "  if (a) {\n"
9193                "    a();\n"
9194                "  }\n"
9195                "  else {\n"
9196                "    b();\n"
9197                "  }\n"
9198                "}\n",
9199                StroustrupBraceStyle);
9200
9201   verifyFormat("#ifdef _DEBUG\n"
9202                "int foo(int i = 0)\n"
9203                "#else\n"
9204                "int foo(int i = 5)\n"
9205                "#endif\n"
9206                "{\n"
9207                "  return i;\n"
9208                "}",
9209                StroustrupBraceStyle);
9210
9211   verifyFormat("void foo() {}\n"
9212                "void bar()\n"
9213                "#ifdef _DEBUG\n"
9214                "{\n"
9215                "  foo();\n"
9216                "}\n"
9217                "#else\n"
9218                "{\n"
9219                "}\n"
9220                "#endif",
9221                StroustrupBraceStyle);
9222
9223   verifyFormat("void foobar() { int i = 5; }\n"
9224                "#ifdef _DEBUG\n"
9225                "void bar() {}\n"
9226                "#else\n"
9227                "void bar() { foobar(); }\n"
9228                "#endif",
9229                StroustrupBraceStyle);
9230 }
9231
9232 TEST_F(FormatTest, AllmanBraceBreaking) {
9233   FormatStyle AllmanBraceStyle = getLLVMStyle();
9234   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
9235   verifyFormat("namespace a\n"
9236                "{\n"
9237                "class A\n"
9238                "{\n"
9239                "  void f()\n"
9240                "  {\n"
9241                "    if (true)\n"
9242                "    {\n"
9243                "      a();\n"
9244                "      b();\n"
9245                "    }\n"
9246                "  }\n"
9247                "  void g() { return; }\n"
9248                "};\n"
9249                "struct B\n"
9250                "{\n"
9251                "  int x;\n"
9252                "};\n"
9253                "}",
9254                AllmanBraceStyle);
9255
9256   verifyFormat("void f()\n"
9257                "{\n"
9258                "  if (true)\n"
9259                "  {\n"
9260                "    a();\n"
9261                "  }\n"
9262                "  else if (false)\n"
9263                "  {\n"
9264                "    b();\n"
9265                "  }\n"
9266                "  else\n"
9267                "  {\n"
9268                "    c();\n"
9269                "  }\n"
9270                "}\n",
9271                AllmanBraceStyle);
9272
9273   verifyFormat("void f()\n"
9274                "{\n"
9275                "  for (int i = 0; i < 10; ++i)\n"
9276                "  {\n"
9277                "    a();\n"
9278                "  }\n"
9279                "  while (false)\n"
9280                "  {\n"
9281                "    b();\n"
9282                "  }\n"
9283                "  do\n"
9284                "  {\n"
9285                "    c();\n"
9286                "  } while (false)\n"
9287                "}\n",
9288                AllmanBraceStyle);
9289
9290   verifyFormat("void f(int a)\n"
9291                "{\n"
9292                "  switch (a)\n"
9293                "  {\n"
9294                "  case 0:\n"
9295                "    break;\n"
9296                "  case 1:\n"
9297                "  {\n"
9298                "    break;\n"
9299                "  }\n"
9300                "  case 2:\n"
9301                "  {\n"
9302                "  }\n"
9303                "  break;\n"
9304                "  default:\n"
9305                "    break;\n"
9306                "  }\n"
9307                "}\n",
9308                AllmanBraceStyle);
9309
9310   verifyFormat("enum X\n"
9311                "{\n"
9312                "  Y = 0,\n"
9313                "}\n",
9314                AllmanBraceStyle);
9315   verifyFormat("enum X\n"
9316                "{\n"
9317                "  Y = 0\n"
9318                "}\n",
9319                AllmanBraceStyle);
9320
9321   verifyFormat("@interface BSApplicationController ()\n"
9322                "{\n"
9323                "@private\n"
9324                "  id _extraIvar;\n"
9325                "}\n"
9326                "@end\n",
9327                AllmanBraceStyle);
9328
9329   verifyFormat("#ifdef _DEBUG\n"
9330                "int foo(int i = 0)\n"
9331                "#else\n"
9332                "int foo(int i = 5)\n"
9333                "#endif\n"
9334                "{\n"
9335                "  return i;\n"
9336                "}",
9337                AllmanBraceStyle);
9338
9339   verifyFormat("void foo() {}\n"
9340                "void bar()\n"
9341                "#ifdef _DEBUG\n"
9342                "{\n"
9343                "  foo();\n"
9344                "}\n"
9345                "#else\n"
9346                "{\n"
9347                "}\n"
9348                "#endif",
9349                AllmanBraceStyle);
9350
9351   verifyFormat("void foobar() { int i = 5; }\n"
9352                "#ifdef _DEBUG\n"
9353                "void bar() {}\n"
9354                "#else\n"
9355                "void bar() { foobar(); }\n"
9356                "#endif",
9357                AllmanBraceStyle);
9358
9359   // This shouldn't affect ObjC blocks..
9360   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
9361                "  // ...\n"
9362                "  int i;\n"
9363                "}];",
9364                AllmanBraceStyle);
9365   verifyFormat("void (^block)(void) = ^{\n"
9366                "  // ...\n"
9367                "  int i;\n"
9368                "};",
9369                AllmanBraceStyle);
9370   // .. or dict literals.
9371   verifyFormat("void f()\n"
9372                "{\n"
9373                "  [object someMethod:@{ @\"a\" : @\"b\" }];\n"
9374                "}",
9375                AllmanBraceStyle);
9376   verifyFormat("int f()\n"
9377                "{ // comment\n"
9378                "  return 42;\n"
9379                "}",
9380                AllmanBraceStyle);
9381
9382   AllmanBraceStyle.ColumnLimit = 19;
9383   verifyFormat("void f() { int i; }", AllmanBraceStyle);
9384   AllmanBraceStyle.ColumnLimit = 18;
9385   verifyFormat("void f()\n"
9386                "{\n"
9387                "  int i;\n"
9388                "}",
9389                AllmanBraceStyle);
9390   AllmanBraceStyle.ColumnLimit = 80;
9391
9392   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
9393   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = true;
9394   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
9395   verifyFormat("void f(bool b)\n"
9396                "{\n"
9397                "  if (b)\n"
9398                "  {\n"
9399                "    return;\n"
9400                "  }\n"
9401                "}\n",
9402                BreakBeforeBraceShortIfs);
9403   verifyFormat("void f(bool b)\n"
9404                "{\n"
9405                "  if (b) return;\n"
9406                "}\n",
9407                BreakBeforeBraceShortIfs);
9408   verifyFormat("void f(bool b)\n"
9409                "{\n"
9410                "  while (b)\n"
9411                "  {\n"
9412                "    return;\n"
9413                "  }\n"
9414                "}\n",
9415                BreakBeforeBraceShortIfs);
9416 }
9417
9418 TEST_F(FormatTest, GNUBraceBreaking) {
9419   FormatStyle GNUBraceStyle = getLLVMStyle();
9420   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
9421   verifyFormat("namespace a\n"
9422                "{\n"
9423                "class A\n"
9424                "{\n"
9425                "  void f()\n"
9426                "  {\n"
9427                "    int a;\n"
9428                "    {\n"
9429                "      int b;\n"
9430                "    }\n"
9431                "    if (true)\n"
9432                "      {\n"
9433                "        a();\n"
9434                "        b();\n"
9435                "      }\n"
9436                "  }\n"
9437                "  void g() { return; }\n"
9438                "}\n"
9439                "}",
9440                GNUBraceStyle);
9441
9442   verifyFormat("void f()\n"
9443                "{\n"
9444                "  if (true)\n"
9445                "    {\n"
9446                "      a();\n"
9447                "    }\n"
9448                "  else if (false)\n"
9449                "    {\n"
9450                "      b();\n"
9451                "    }\n"
9452                "  else\n"
9453                "    {\n"
9454                "      c();\n"
9455                "    }\n"
9456                "}\n",
9457                GNUBraceStyle);
9458
9459   verifyFormat("void f()\n"
9460                "{\n"
9461                "  for (int i = 0; i < 10; ++i)\n"
9462                "    {\n"
9463                "      a();\n"
9464                "    }\n"
9465                "  while (false)\n"
9466                "    {\n"
9467                "      b();\n"
9468                "    }\n"
9469                "  do\n"
9470                "    {\n"
9471                "      c();\n"
9472                "    }\n"
9473                "  while (false);\n"
9474                "}\n",
9475                GNUBraceStyle);
9476
9477   verifyFormat("void f(int a)\n"
9478                "{\n"
9479                "  switch (a)\n"
9480                "    {\n"
9481                "    case 0:\n"
9482                "      break;\n"
9483                "    case 1:\n"
9484                "      {\n"
9485                "        break;\n"
9486                "      }\n"
9487                "    case 2:\n"
9488                "      {\n"
9489                "      }\n"
9490                "      break;\n"
9491                "    default:\n"
9492                "      break;\n"
9493                "    }\n"
9494                "}\n",
9495                GNUBraceStyle);
9496
9497   verifyFormat("enum X\n"
9498                "{\n"
9499                "  Y = 0,\n"
9500                "}\n",
9501                GNUBraceStyle);
9502
9503   verifyFormat("@interface BSApplicationController ()\n"
9504                "{\n"
9505                "@private\n"
9506                "  id _extraIvar;\n"
9507                "}\n"
9508                "@end\n",
9509                GNUBraceStyle);
9510
9511   verifyFormat("#ifdef _DEBUG\n"
9512                "int foo(int i = 0)\n"
9513                "#else\n"
9514                "int foo(int i = 5)\n"
9515                "#endif\n"
9516                "{\n"
9517                "  return i;\n"
9518                "}",
9519                GNUBraceStyle);
9520
9521   verifyFormat("void foo() {}\n"
9522                "void bar()\n"
9523                "#ifdef _DEBUG\n"
9524                "{\n"
9525                "  foo();\n"
9526                "}\n"
9527                "#else\n"
9528                "{\n"
9529                "}\n"
9530                "#endif",
9531                GNUBraceStyle);
9532
9533   verifyFormat("void foobar() { int i = 5; }\n"
9534                "#ifdef _DEBUG\n"
9535                "void bar() {}\n"
9536                "#else\n"
9537                "void bar() { foobar(); }\n"
9538                "#endif",
9539                GNUBraceStyle);
9540 }
9541
9542 TEST_F(FormatTest, WebKitBraceBreaking) {
9543   FormatStyle WebKitBraceStyle = getLLVMStyle();
9544   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
9545   verifyFormat("namespace a {\n"
9546                "class A {\n"
9547                "  void f()\n"
9548                "  {\n"
9549                "    if (true) {\n"
9550                "      a();\n"
9551                "      b();\n"
9552                "    }\n"
9553                "  }\n"
9554                "  void g() { return; }\n"
9555                "};\n"
9556                "enum E {\n"
9557                "  A,\n"
9558                "  // foo\n"
9559                "  B,\n"
9560                "  C\n"
9561                "};\n"
9562                "struct B {\n"
9563                "  int x;\n"
9564                "};\n"
9565                "}\n",
9566                WebKitBraceStyle);
9567   verifyFormat("struct S {\n"
9568                "  int Type;\n"
9569                "  union {\n"
9570                "    int x;\n"
9571                "    double y;\n"
9572                "  } Value;\n"
9573                "  class C {\n"
9574                "    MyFavoriteType Value;\n"
9575                "  } Class;\n"
9576                "};\n",
9577                WebKitBraceStyle);
9578 }
9579
9580 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
9581   verifyFormat("void f() {\n"
9582                "  try {\n"
9583                "  } catch (const Exception &e) {\n"
9584                "  }\n"
9585                "}\n",
9586                getLLVMStyle());
9587 }
9588
9589 TEST_F(FormatTest, UnderstandsPragmas) {
9590   verifyFormat("#pragma omp reduction(| : var)");
9591   verifyFormat("#pragma omp reduction(+ : var)");
9592
9593   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
9594             "(including parentheses).",
9595             format("#pragma    mark   Any non-hyphenated or hyphenated string "
9596                    "(including parentheses)."));
9597 }
9598
9599 TEST_F(FormatTest, UnderstandPragmaOption) {
9600   verifyFormat("#pragma option -C -A");
9601
9602   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
9603 }
9604
9605 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
9606   for (size_t i = 1; i < Styles.size(); ++i)                                   \
9607   EXPECT_EQ(Styles[0], Styles[i]) << "Style #" << i << " of " << Styles.size() \
9608                                   << " differs from Style #0"
9609
9610 TEST_F(FormatTest, GetsPredefinedStyleByName) {
9611   SmallVector<FormatStyle, 3> Styles;
9612   Styles.resize(3);
9613
9614   Styles[0] = getLLVMStyle();
9615   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
9616   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
9617   EXPECT_ALL_STYLES_EQUAL(Styles);
9618
9619   Styles[0] = getGoogleStyle();
9620   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
9621   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
9622   EXPECT_ALL_STYLES_EQUAL(Styles);
9623
9624   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
9625   EXPECT_TRUE(
9626       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
9627   EXPECT_TRUE(
9628       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
9629   EXPECT_ALL_STYLES_EQUAL(Styles);
9630
9631   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
9632   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
9633   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
9634   EXPECT_ALL_STYLES_EQUAL(Styles);
9635
9636   Styles[0] = getMozillaStyle();
9637   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
9638   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
9639   EXPECT_ALL_STYLES_EQUAL(Styles);
9640
9641   Styles[0] = getWebKitStyle();
9642   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
9643   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
9644   EXPECT_ALL_STYLES_EQUAL(Styles);
9645
9646   Styles[0] = getGNUStyle();
9647   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
9648   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
9649   EXPECT_ALL_STYLES_EQUAL(Styles);
9650
9651   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
9652 }
9653
9654 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
9655   SmallVector<FormatStyle, 8> Styles;
9656   Styles.resize(2);
9657
9658   Styles[0] = getGoogleStyle();
9659   Styles[1] = getLLVMStyle();
9660   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
9661   EXPECT_ALL_STYLES_EQUAL(Styles);
9662
9663   Styles.resize(5);
9664   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
9665   Styles[1] = getLLVMStyle();
9666   Styles[1].Language = FormatStyle::LK_JavaScript;
9667   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
9668
9669   Styles[2] = getLLVMStyle();
9670   Styles[2].Language = FormatStyle::LK_JavaScript;
9671   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
9672                                   "BasedOnStyle: Google",
9673                                   &Styles[2])
9674                    .value());
9675
9676   Styles[3] = getLLVMStyle();
9677   Styles[3].Language = FormatStyle::LK_JavaScript;
9678   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
9679                                   "Language: JavaScript",
9680                                   &Styles[3])
9681                    .value());
9682
9683   Styles[4] = getLLVMStyle();
9684   Styles[4].Language = FormatStyle::LK_JavaScript;
9685   EXPECT_EQ(0, parseConfiguration("---\n"
9686                                   "BasedOnStyle: LLVM\n"
9687                                   "IndentWidth: 123\n"
9688                                   "---\n"
9689                                   "BasedOnStyle: Google\n"
9690                                   "Language: JavaScript",
9691                                   &Styles[4])
9692                    .value());
9693   EXPECT_ALL_STYLES_EQUAL(Styles);
9694 }
9695
9696 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
9697   Style.FIELD = false;                                                         \
9698   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
9699   EXPECT_TRUE(Style.FIELD);                                                    \
9700   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
9701   EXPECT_FALSE(Style.FIELD);
9702
9703 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
9704
9705 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
9706   Style.STRUCT.FIELD = false;                                                  \
9707   EXPECT_EQ(0,                                                                 \
9708             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
9709                 .value());                                                     \
9710   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
9711   EXPECT_EQ(0,                                                                 \
9712             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
9713                 .value());                                                     \
9714   EXPECT_FALSE(Style.STRUCT.FIELD);
9715
9716 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
9717   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
9718
9719 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
9720   EXPECT_NE(VALUE, Style.FIELD);                                               \
9721   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
9722   EXPECT_EQ(VALUE, Style.FIELD)
9723
9724 TEST_F(FormatTest, ParsesConfigurationBools) {
9725   FormatStyle Style = {};
9726   Style.Language = FormatStyle::LK_Cpp;
9727   CHECK_PARSE_BOOL(AlignEscapedNewlinesLeft);
9728   CHECK_PARSE_BOOL(AlignOperands);
9729   CHECK_PARSE_BOOL(AlignTrailingComments);
9730   CHECK_PARSE_BOOL(AlignConsecutiveAssignments);
9731   CHECK_PARSE_BOOL(AlignConsecutiveDeclarations);
9732   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
9733   CHECK_PARSE_BOOL(AllowShortBlocksOnASingleLine);
9734   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
9735   CHECK_PARSE_BOOL(AllowShortIfStatementsOnASingleLine);
9736   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
9737   CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
9738   CHECK_PARSE_BOOL(BinPackArguments);
9739   CHECK_PARSE_BOOL(BinPackParameters);
9740   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
9741   CHECK_PARSE_BOOL(BreakConstructorInitializersBeforeComma);
9742   CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
9743   CHECK_PARSE_BOOL(DerivePointerAlignment);
9744   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
9745   CHECK_PARSE_BOOL(DisableFormat);
9746   CHECK_PARSE_BOOL(IndentCaseLabels);
9747   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
9748   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
9749   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
9750   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
9751   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
9752   CHECK_PARSE_BOOL(ReflowComments);
9753   CHECK_PARSE_BOOL(SortIncludes);
9754   CHECK_PARSE_BOOL(SpacesInParentheses);
9755   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
9756   CHECK_PARSE_BOOL(SpacesInAngles);
9757   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
9758   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
9759   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
9760   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
9761   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
9762
9763   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
9764   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterControlStatement);
9765   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
9766   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
9767   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
9768   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
9769   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
9770   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
9771   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
9772   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
9773   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
9774 }
9775
9776 #undef CHECK_PARSE_BOOL
9777
9778 TEST_F(FormatTest, ParsesConfiguration) {
9779   FormatStyle Style = {};
9780   Style.Language = FormatStyle::LK_Cpp;
9781   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
9782   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
9783               ConstructorInitializerIndentWidth, 1234u);
9784   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
9785   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
9786   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
9787   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
9788               PenaltyBreakBeforeFirstCallParameter, 1234u);
9789   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
9790   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
9791               PenaltyReturnTypeOnItsOwnLine, 1234u);
9792   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
9793               SpacesBeforeTrailingComments, 1234u);
9794   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
9795   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
9796
9797   Style.PointerAlignment = FormatStyle::PAS_Middle;
9798   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
9799               FormatStyle::PAS_Left);
9800   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
9801               FormatStyle::PAS_Right);
9802   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
9803               FormatStyle::PAS_Middle);
9804   // For backward compatibility:
9805   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
9806               FormatStyle::PAS_Left);
9807   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
9808               FormatStyle::PAS_Right);
9809   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
9810               FormatStyle::PAS_Middle);
9811
9812   Style.Standard = FormatStyle::LS_Auto;
9813   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
9814   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Cpp11);
9815   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
9816   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
9817   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
9818
9819   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
9820   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
9821               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
9822   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
9823               FormatStyle::BOS_None);
9824   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
9825               FormatStyle::BOS_All);
9826   // For backward compatibility:
9827   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
9828               FormatStyle::BOS_None);
9829   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
9830               FormatStyle::BOS_All);
9831
9832   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9833   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
9834               FormatStyle::BAS_Align);
9835   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
9836               FormatStyle::BAS_DontAlign);
9837   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
9838               FormatStyle::BAS_AlwaysBreak);
9839   // For backward compatibility:
9840   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
9841               FormatStyle::BAS_DontAlign);
9842   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
9843               FormatStyle::BAS_Align);
9844
9845   Style.UseTab = FormatStyle::UT_ForIndentation;
9846   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
9847   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
9848   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
9849   // For backward compatibility:
9850   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
9851   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
9852
9853   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
9854   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
9855               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
9856   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
9857               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
9858   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
9859               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
9860   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
9861               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
9862   // For backward compatibility:
9863   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
9864               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
9865   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
9866               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
9867
9868   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
9869   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
9870               FormatStyle::SBPO_Never);
9871   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
9872               FormatStyle::SBPO_Always);
9873   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
9874               FormatStyle::SBPO_ControlStatements);
9875   // For backward compatibility:
9876   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
9877               FormatStyle::SBPO_Never);
9878   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
9879               FormatStyle::SBPO_ControlStatements);
9880
9881   Style.ColumnLimit = 123;
9882   FormatStyle BaseStyle = getLLVMStyle();
9883   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
9884   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
9885
9886   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
9887   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
9888               FormatStyle::BS_Attach);
9889   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
9890               FormatStyle::BS_Linux);
9891   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
9892               FormatStyle::BS_Mozilla);
9893   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
9894               FormatStyle::BS_Stroustrup);
9895   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
9896               FormatStyle::BS_Allman);
9897   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
9898   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
9899               FormatStyle::BS_WebKit);
9900   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
9901               FormatStyle::BS_Custom);
9902
9903   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
9904   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
9905               FormatStyle::RTBS_None);
9906   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
9907               FormatStyle::RTBS_All);
9908   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
9909               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
9910   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
9911               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
9912   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
9913               AlwaysBreakAfterReturnType,
9914               FormatStyle::RTBS_TopLevelDefinitions);
9915
9916   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
9917   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
9918               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
9919   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
9920               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
9921   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
9922               AlwaysBreakAfterDefinitionReturnType,
9923               FormatStyle::DRTBS_TopLevel);
9924
9925   Style.NamespaceIndentation = FormatStyle::NI_All;
9926   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
9927               FormatStyle::NI_None);
9928   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
9929               FormatStyle::NI_Inner);
9930   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
9931               FormatStyle::NI_All);
9932
9933   // FIXME: This is required because parsing a configuration simply overwrites
9934   // the first N elements of the list instead of resetting it.
9935   Style.ForEachMacros.clear();
9936   std::vector<std::string> BoostForeach;
9937   BoostForeach.push_back("BOOST_FOREACH");
9938   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
9939   std::vector<std::string> BoostAndQForeach;
9940   BoostAndQForeach.push_back("BOOST_FOREACH");
9941   BoostAndQForeach.push_back("Q_FOREACH");
9942   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
9943               BoostAndQForeach);
9944
9945   Style.IncludeCategories.clear();
9946   std::vector<FormatStyle::IncludeCategory> ExpectedCategories = {{"abc/.*", 2},
9947                                                                   {".*", 1}};
9948   CHECK_PARSE("IncludeCategories:\n"
9949               "  - Regex: abc/.*\n"
9950               "    Priority: 2\n"
9951               "  - Regex: .*\n"
9952               "    Priority: 1",
9953               IncludeCategories, ExpectedCategories);
9954 }
9955
9956 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
9957   FormatStyle Style = {};
9958   Style.Language = FormatStyle::LK_Cpp;
9959   CHECK_PARSE("Language: Cpp\n"
9960               "IndentWidth: 12",
9961               IndentWidth, 12u);
9962   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
9963                                "IndentWidth: 34",
9964                                &Style),
9965             ParseError::Unsuitable);
9966   EXPECT_EQ(12u, Style.IndentWidth);
9967   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
9968   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
9969
9970   Style.Language = FormatStyle::LK_JavaScript;
9971   CHECK_PARSE("Language: JavaScript\n"
9972               "IndentWidth: 12",
9973               IndentWidth, 12u);
9974   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
9975   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
9976                                "IndentWidth: 34",
9977                                &Style),
9978             ParseError::Unsuitable);
9979   EXPECT_EQ(23u, Style.IndentWidth);
9980   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
9981   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
9982
9983   CHECK_PARSE("BasedOnStyle: LLVM\n"
9984               "IndentWidth: 67",
9985               IndentWidth, 67u);
9986
9987   CHECK_PARSE("---\n"
9988               "Language: JavaScript\n"
9989               "IndentWidth: 12\n"
9990               "---\n"
9991               "Language: Cpp\n"
9992               "IndentWidth: 34\n"
9993               "...\n",
9994               IndentWidth, 12u);
9995
9996   Style.Language = FormatStyle::LK_Cpp;
9997   CHECK_PARSE("---\n"
9998               "Language: JavaScript\n"
9999               "IndentWidth: 12\n"
10000               "---\n"
10001               "Language: Cpp\n"
10002               "IndentWidth: 34\n"
10003               "...\n",
10004               IndentWidth, 34u);
10005   CHECK_PARSE("---\n"
10006               "IndentWidth: 78\n"
10007               "---\n"
10008               "Language: JavaScript\n"
10009               "IndentWidth: 56\n"
10010               "...\n",
10011               IndentWidth, 78u);
10012
10013   Style.ColumnLimit = 123;
10014   Style.IndentWidth = 234;
10015   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
10016   Style.TabWidth = 345;
10017   EXPECT_FALSE(parseConfiguration("---\n"
10018                                   "IndentWidth: 456\n"
10019                                   "BreakBeforeBraces: Allman\n"
10020                                   "---\n"
10021                                   "Language: JavaScript\n"
10022                                   "IndentWidth: 111\n"
10023                                   "TabWidth: 111\n"
10024                                   "---\n"
10025                                   "Language: Cpp\n"
10026                                   "BreakBeforeBraces: Stroustrup\n"
10027                                   "TabWidth: 789\n"
10028                                   "...\n",
10029                                   &Style));
10030   EXPECT_EQ(123u, Style.ColumnLimit);
10031   EXPECT_EQ(456u, Style.IndentWidth);
10032   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
10033   EXPECT_EQ(789u, Style.TabWidth);
10034
10035   EXPECT_EQ(parseConfiguration("---\n"
10036                                "Language: JavaScript\n"
10037                                "IndentWidth: 56\n"
10038                                "---\n"
10039                                "IndentWidth: 78\n"
10040                                "...\n",
10041                                &Style),
10042             ParseError::Error);
10043   EXPECT_EQ(parseConfiguration("---\n"
10044                                "Language: JavaScript\n"
10045                                "IndentWidth: 56\n"
10046                                "---\n"
10047                                "Language: JavaScript\n"
10048                                "IndentWidth: 78\n"
10049                                "...\n",
10050                                &Style),
10051             ParseError::Error);
10052
10053   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
10054 }
10055
10056 #undef CHECK_PARSE
10057
10058 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
10059   FormatStyle Style = {};
10060   Style.Language = FormatStyle::LK_JavaScript;
10061   Style.BreakBeforeTernaryOperators = true;
10062   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
10063   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
10064
10065   Style.BreakBeforeTernaryOperators = true;
10066   EXPECT_EQ(0, parseConfiguration("---\n"
10067                                   "BasedOnStyle: Google\n"
10068                                   "---\n"
10069                                   "Language: JavaScript\n"
10070                                   "IndentWidth: 76\n"
10071                                   "...\n",
10072                                   &Style)
10073                    .value());
10074   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
10075   EXPECT_EQ(76u, Style.IndentWidth);
10076   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
10077 }
10078
10079 TEST_F(FormatTest, ConfigurationRoundTripTest) {
10080   FormatStyle Style = getLLVMStyle();
10081   std::string YAML = configurationAsText(Style);
10082   FormatStyle ParsedStyle = {};
10083   ParsedStyle.Language = FormatStyle::LK_Cpp;
10084   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
10085   EXPECT_EQ(Style, ParsedStyle);
10086 }
10087
10088 TEST_F(FormatTest, WorksFor8bitEncodings) {
10089   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
10090             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
10091             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
10092             "\"\xef\xee\xf0\xf3...\"",
10093             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
10094                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
10095                    "\xef\xee\xf0\xf3...\"",
10096                    getLLVMStyleWithColumns(12)));
10097 }
10098
10099 TEST_F(FormatTest, HandlesUTF8BOM) {
10100   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
10101   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
10102             format("\xef\xbb\xbf#include <iostream>"));
10103   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
10104             format("\xef\xbb\xbf\n#include <iostream>"));
10105 }
10106
10107 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
10108 #if !defined(_MSC_VER)
10109
10110 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
10111   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
10112                getLLVMStyleWithColumns(35));
10113   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
10114                getLLVMStyleWithColumns(31));
10115   verifyFormat("// Однажды в студёную зимнюю пору...",
10116                getLLVMStyleWithColumns(36));
10117   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
10118   verifyFormat("/* Однажды в студёную зимнюю пору... */",
10119                getLLVMStyleWithColumns(39));
10120   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
10121                getLLVMStyleWithColumns(35));
10122 }
10123
10124 TEST_F(FormatTest, SplitsUTF8Strings) {
10125   // Non-printable characters' width is currently considered to be the length in
10126   // bytes in UTF8. The characters can be displayed in very different manner
10127   // (zero-width, single width with a substitution glyph, expanded to their code
10128   // (e.g. "<8d>"), so there's no single correct way to handle them.
10129   EXPECT_EQ("\"aaaaÄ\"\n"
10130             "\"\xc2\x8d\";",
10131             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
10132   EXPECT_EQ("\"aaaaaaaÄ\"\n"
10133             "\"\xc2\x8d\";",
10134             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
10135   EXPECT_EQ("\"Однажды, в \"\n"
10136             "\"студёную \"\n"
10137             "\"зимнюю \"\n"
10138             "\"пору,\"",
10139             format("\"Однажды, в студёную зимнюю пору,\"",
10140                    getLLVMStyleWithColumns(13)));
10141   EXPECT_EQ(
10142       "\"一 二 三 \"\n"
10143       "\"四 五六 \"\n"
10144       "\"七 八 九 \"\n"
10145       "\"十\"",
10146       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
10147   EXPECT_EQ("\"一\t二 \"\n"
10148             "\"\t三 \"\n"
10149             "\"四 五\t六 \"\n"
10150             "\"\t七 \"\n"
10151             "\"八九十\tqq\"",
10152             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
10153                    getLLVMStyleWithColumns(11)));
10154
10155   // UTF8 character in an escape sequence.
10156   EXPECT_EQ("\"aaaaaa\"\n"
10157             "\"\\\xC2\x8D\"",
10158             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
10159 }
10160
10161 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
10162   EXPECT_EQ("const char *sssss =\n"
10163             "    \"一二三四五六七八\\\n"
10164             " 九 十\";",
10165             format("const char *sssss = \"一二三四五六七八\\\n"
10166                    " 九 十\";",
10167                    getLLVMStyleWithColumns(30)));
10168 }
10169
10170 TEST_F(FormatTest, SplitsUTF8LineComments) {
10171   EXPECT_EQ("// aaaaÄ\xc2\x8d",
10172             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
10173   EXPECT_EQ("// Я из лесу\n"
10174             "// вышел; был\n"
10175             "// сильный\n"
10176             "// мороз.",
10177             format("// Я из лесу вышел; был сильный мороз.",
10178                    getLLVMStyleWithColumns(13)));
10179   EXPECT_EQ("// 一二三\n"
10180             "// 四五六七\n"
10181             "// 八  九\n"
10182             "// 十",
10183             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
10184 }
10185
10186 TEST_F(FormatTest, SplitsUTF8BlockComments) {
10187   EXPECT_EQ("/* Гляжу,\n"
10188             " * поднимается\n"
10189             " * медленно в\n"
10190             " * гору\n"
10191             " * Лошадка,\n"
10192             " * везущая\n"
10193             " * хворосту\n"
10194             " * воз. */",
10195             format("/* Гляжу, поднимается медленно в гору\n"
10196                    " * Лошадка, везущая хворосту воз. */",
10197                    getLLVMStyleWithColumns(13)));
10198   EXPECT_EQ(
10199       "/* 一二三\n"
10200       " * 四五六七\n"
10201       " * 八  九\n"
10202       " * 十  */",
10203       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
10204   EXPECT_EQ("/* 𝓣𝓮𝓼𝓽 𝔣𝔬𝔲𝔯\n"
10205             " * 𝕓𝕪𝕥𝕖\n"
10206             " * 𝖀𝕿𝕱-𝟠 */",
10207             format("/* 𝓣𝓮𝓼𝓽 𝔣𝔬𝔲𝔯 𝕓𝕪𝕥𝕖 𝖀𝕿𝕱-𝟠 */", getLLVMStyleWithColumns(12)));
10208 }
10209
10210 #endif // _MSC_VER
10211
10212 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
10213   FormatStyle Style = getLLVMStyle();
10214
10215   Style.ConstructorInitializerIndentWidth = 4;
10216   verifyFormat(
10217       "SomeClass::Constructor()\n"
10218       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
10219       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
10220       Style);
10221
10222   Style.ConstructorInitializerIndentWidth = 2;
10223   verifyFormat(
10224       "SomeClass::Constructor()\n"
10225       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
10226       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
10227       Style);
10228
10229   Style.ConstructorInitializerIndentWidth = 0;
10230   verifyFormat(
10231       "SomeClass::Constructor()\n"
10232       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
10233       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
10234       Style);
10235 }
10236
10237 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
10238   FormatStyle Style = getLLVMStyle();
10239   Style.BreakConstructorInitializersBeforeComma = true;
10240   Style.ConstructorInitializerIndentWidth = 4;
10241   verifyFormat("SomeClass::Constructor()\n"
10242                "    : a(a)\n"
10243                "    , b(b)\n"
10244                "    , c(c) {}",
10245                Style);
10246   verifyFormat("SomeClass::Constructor()\n"
10247                "    : a(a) {}",
10248                Style);
10249
10250   Style.ColumnLimit = 0;
10251   verifyFormat("SomeClass::Constructor()\n"
10252                "    : a(a) {}",
10253                Style);
10254   verifyFormat("SomeClass::Constructor()\n"
10255                "    : a(a)\n"
10256                "    , b(b)\n"
10257                "    , c(c) {}",
10258                Style);
10259   verifyFormat("SomeClass::Constructor()\n"
10260                "    : a(a) {\n"
10261                "  foo();\n"
10262                "  bar();\n"
10263                "}",
10264                Style);
10265
10266   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10267   verifyFormat("SomeClass::Constructor()\n"
10268                "    : a(a)\n"
10269                "    , b(b)\n"
10270                "    , c(c) {\n}",
10271                Style);
10272   verifyFormat("SomeClass::Constructor()\n"
10273                "    : a(a) {\n}",
10274                Style);
10275
10276   Style.ColumnLimit = 80;
10277   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
10278   Style.ConstructorInitializerIndentWidth = 2;
10279   verifyFormat("SomeClass::Constructor()\n"
10280                "  : a(a)\n"
10281                "  , b(b)\n"
10282                "  , c(c) {}",
10283                Style);
10284
10285   Style.ConstructorInitializerIndentWidth = 0;
10286   verifyFormat("SomeClass::Constructor()\n"
10287                ": a(a)\n"
10288                ", b(b)\n"
10289                ", c(c) {}",
10290                Style);
10291
10292   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
10293   Style.ConstructorInitializerIndentWidth = 4;
10294   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
10295   verifyFormat(
10296       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
10297       Style);
10298   verifyFormat(
10299       "SomeClass::Constructor()\n"
10300       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
10301       Style);
10302   Style.ConstructorInitializerIndentWidth = 4;
10303   Style.ColumnLimit = 60;
10304   verifyFormat("SomeClass::Constructor()\n"
10305                "    : aaaaaaaa(aaaaaaaa)\n"
10306                "    , aaaaaaaa(aaaaaaaa)\n"
10307                "    , aaaaaaaa(aaaaaaaa) {}",
10308                Style);
10309 }
10310
10311 TEST_F(FormatTest, Destructors) {
10312   verifyFormat("void F(int &i) { i.~int(); }");
10313   verifyFormat("void F(int &i) { i->~int(); }");
10314 }
10315
10316 TEST_F(FormatTest, FormatsWithWebKitStyle) {
10317   FormatStyle Style = getWebKitStyle();
10318
10319   // Don't indent in outer namespaces.
10320   verifyFormat("namespace outer {\n"
10321                "int i;\n"
10322                "namespace inner {\n"
10323                "    int i;\n"
10324                "} // namespace inner\n"
10325                "} // namespace outer\n"
10326                "namespace other_outer {\n"
10327                "int i;\n"
10328                "}",
10329                Style);
10330
10331   // Don't indent case labels.
10332   verifyFormat("switch (variable) {\n"
10333                "case 1:\n"
10334                "case 2:\n"
10335                "    doSomething();\n"
10336                "    break;\n"
10337                "default:\n"
10338                "    ++variable;\n"
10339                "}",
10340                Style);
10341
10342   // Wrap before binary operators.
10343   EXPECT_EQ("void f()\n"
10344             "{\n"
10345             "    if (aaaaaaaaaaaaaaaa\n"
10346             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
10347             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
10348             "        return;\n"
10349             "}",
10350             format("void f() {\n"
10351                    "if (aaaaaaaaaaaaaaaa\n"
10352                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
10353                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
10354                    "return;\n"
10355                    "}",
10356                    Style));
10357
10358   // Allow functions on a single line.
10359   verifyFormat("void f() { return; }", Style);
10360
10361   // Constructor initializers are formatted one per line with the "," on the
10362   // new line.
10363   verifyFormat("Constructor()\n"
10364                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
10365                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
10366                "          aaaaaaaaaaaaaa)\n"
10367                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
10368                "{\n"
10369                "}",
10370                Style);
10371   verifyFormat("SomeClass::Constructor()\n"
10372                "    : a(a)\n"
10373                "{\n"
10374                "}",
10375                Style);
10376   EXPECT_EQ("SomeClass::Constructor()\n"
10377             "    : a(a)\n"
10378             "{\n"
10379             "}",
10380             format("SomeClass::Constructor():a(a){}", Style));
10381   verifyFormat("SomeClass::Constructor()\n"
10382                "    : a(a)\n"
10383                "    , b(b)\n"
10384                "    , c(c)\n"
10385                "{\n"
10386                "}",
10387                Style);
10388   verifyFormat("SomeClass::Constructor()\n"
10389                "    : a(a)\n"
10390                "{\n"
10391                "    foo();\n"
10392                "    bar();\n"
10393                "}",
10394                Style);
10395
10396   // Access specifiers should be aligned left.
10397   verifyFormat("class C {\n"
10398                "public:\n"
10399                "    int i;\n"
10400                "};",
10401                Style);
10402
10403   // Do not align comments.
10404   verifyFormat("int a; // Do not\n"
10405                "double b; // align comments.",
10406                Style);
10407
10408   // Do not align operands.
10409   EXPECT_EQ("ASSERT(aaaa\n"
10410             "    || bbbb);",
10411             format("ASSERT ( aaaa\n||bbbb);", Style));
10412
10413   // Accept input's line breaks.
10414   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
10415             "    || bbbbbbbbbbbbbbb) {\n"
10416             "    i++;\n"
10417             "}",
10418             format("if (aaaaaaaaaaaaaaa\n"
10419                    "|| bbbbbbbbbbbbbbb) { i++; }",
10420                    Style));
10421   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
10422             "    i++;\n"
10423             "}",
10424             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
10425
10426   // Don't automatically break all macro definitions (llvm.org/PR17842).
10427   verifyFormat("#define aNumber 10", Style);
10428   // However, generally keep the line breaks that the user authored.
10429   EXPECT_EQ("#define aNumber \\\n"
10430             "    10",
10431             format("#define aNumber \\\n"
10432                    " 10",
10433                    Style));
10434
10435   // Keep empty and one-element array literals on a single line.
10436   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
10437             "                                  copyItems:YES];",
10438             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
10439                    "copyItems:YES];",
10440                    Style));
10441   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
10442             "                                  copyItems:YES];",
10443             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
10444                    "             copyItems:YES];",
10445                    Style));
10446   // FIXME: This does not seem right, there should be more indentation before
10447   // the array literal's entries. Nested blocks have the same problem.
10448   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
10449             "    @\"a\",\n"
10450             "    @\"a\"\n"
10451             "]\n"
10452             "                                  copyItems:YES];",
10453             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
10454                    "     @\"a\",\n"
10455                    "     @\"a\"\n"
10456                    "     ]\n"
10457                    "       copyItems:YES];",
10458                    Style));
10459   EXPECT_EQ(
10460       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
10461       "                                  copyItems:YES];",
10462       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
10463              "   copyItems:YES];",
10464              Style));
10465
10466   verifyFormat("[self.a b:c c:d];", Style);
10467   EXPECT_EQ("[self.a b:c\n"
10468             "        c:d];",
10469             format("[self.a b:c\n"
10470                    "c:d];",
10471                    Style));
10472 }
10473
10474 TEST_F(FormatTest, FormatsLambdas) {
10475   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
10476   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
10477   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
10478   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
10479   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
10480   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
10481   verifyFormat("void f() {\n"
10482                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
10483                "}\n");
10484   verifyFormat("void f() {\n"
10485                "  other(x.begin(), //\n"
10486                "        x.end(),   //\n"
10487                "        [&](int, int) { return 1; });\n"
10488                "}\n");
10489   verifyFormat("SomeFunction([]() { // A cool function...\n"
10490                "  return 43;\n"
10491                "});");
10492   EXPECT_EQ("SomeFunction([]() {\n"
10493             "#define A a\n"
10494             "  return 43;\n"
10495             "});",
10496             format("SomeFunction([](){\n"
10497                    "#define A a\n"
10498                    "return 43;\n"
10499                    "});"));
10500   verifyFormat("void f() {\n"
10501                "  SomeFunction([](decltype(x), A *a) {});\n"
10502                "}");
10503   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10504                "    [](const aaaaaaaaaa &a) { return a; });");
10505   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
10506                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
10507                "});");
10508   verifyFormat("Constructor()\n"
10509                "    : Field([] { // comment\n"
10510                "        int i;\n"
10511                "      }) {}");
10512   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
10513                "  return some_parameter.size();\n"
10514                "};");
10515   verifyFormat("int i = aaaaaa ? 1 //\n"
10516                "               : [] {\n"
10517                "                   return 2; //\n"
10518                "                 }();");
10519   verifyFormat("llvm::errs() << \"number of twos is \"\n"
10520                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
10521                "                  return x == 2; // force break\n"
10522                "                });");
10523   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa([=](\n"
10524                "    int iiiiiiiiiiii) {\n"
10525                "  return aaaaaaaaaaaaaaaaaaaaaaa != aaaaaaaaaaaaaaaaaaaaaaa;\n"
10526                "});",
10527                getLLVMStyleWithColumns(60));
10528   verifyFormat("SomeFunction({[&] {\n"
10529                "                // comment\n"
10530                "              },\n"
10531                "              [&] {\n"
10532                "                // comment\n"
10533                "              }});");
10534   verifyFormat("SomeFunction({[&] {\n"
10535                "  // comment\n"
10536                "}});");
10537   verifyFormat("virtual aaaaaaaaaaaaaaaa(std::function<bool()> bbbbbbbbbbbb =\n"
10538                "                             [&]() { return true; },\n"
10539                "                         aaaaa aaaaaaaaa);");
10540
10541   // Lambdas with return types.
10542   verifyFormat("int c = []() -> int { return 2; }();\n");
10543   verifyFormat("int c = []() -> int * { return 2; }();\n");
10544   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
10545   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
10546   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
10547   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
10548   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
10549   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
10550   verifyFormat("[a, a]() -> a<1> {};");
10551   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
10552                "                   int j) -> int {\n"
10553                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
10554                "};");
10555   verifyFormat(
10556       "aaaaaaaaaaaaaaaaaaaaaa(\n"
10557       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
10558       "      return aaaaaaaaaaaaaaaaa;\n"
10559       "    });",
10560       getLLVMStyleWithColumns(70));
10561
10562   // Multiple lambdas in the same parentheses change indentation rules.
10563   verifyFormat("SomeFunction(\n"
10564                "    []() {\n"
10565                "      int i = 42;\n"
10566                "      return i;\n"
10567                "    },\n"
10568                "    []() {\n"
10569                "      int j = 43;\n"
10570                "      return j;\n"
10571                "    });");
10572
10573   // More complex introducers.
10574   verifyFormat("return [i, args...] {};");
10575
10576   // Not lambdas.
10577   verifyFormat("constexpr char hello[]{\"hello\"};");
10578   verifyFormat("double &operator[](int i) { return 0; }\n"
10579                "int i;");
10580   verifyFormat("std::unique_ptr<int[]> foo() {}");
10581   verifyFormat("int i = a[a][a]->f();");
10582   verifyFormat("int i = (*b)[a]->f();");
10583
10584   // Other corner cases.
10585   verifyFormat("void f() {\n"
10586                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
10587                "      );\n"
10588                "}");
10589
10590   // Lambdas created through weird macros.
10591   verifyFormat("void f() {\n"
10592                "  MACRO((const AA &a) { return 1; });\n"
10593                "}");
10594
10595   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
10596                "      doo_dah();\n"
10597                "      doo_dah();\n"
10598                "    })) {\n"
10599                "}");
10600   verifyFormat("auto lambda = []() {\n"
10601                "  int a = 2\n"
10602                "#if A\n"
10603                "          + 2\n"
10604                "#endif\n"
10605                "      ;\n"
10606                "};");
10607 }
10608
10609 TEST_F(FormatTest, FormatsBlocks) {
10610   FormatStyle ShortBlocks = getLLVMStyle();
10611   ShortBlocks.AllowShortBlocksOnASingleLine = true;
10612   verifyFormat("int (^Block)(int, int);", ShortBlocks);
10613   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
10614   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
10615   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
10616   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
10617   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
10618
10619   verifyFormat("foo(^{ bar(); });", ShortBlocks);
10620   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
10621   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
10622
10623   verifyFormat("[operation setCompletionBlock:^{\n"
10624                "  [self onOperationDone];\n"
10625                "}];");
10626   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
10627                "  [self onOperationDone];\n"
10628                "}]};");
10629   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
10630                "  f();\n"
10631                "}];");
10632   verifyFormat("int a = [operation block:^int(int *i) {\n"
10633                "  return 1;\n"
10634                "}];");
10635   verifyFormat("[myObject doSomethingWith:arg1\n"
10636                "                      aaa:^int(int *a) {\n"
10637                "                        return 1;\n"
10638                "                      }\n"
10639                "                      bbb:f(a * bbbbbbbb)];");
10640
10641   verifyFormat("[operation setCompletionBlock:^{\n"
10642                "  [self.delegate newDataAvailable];\n"
10643                "}];",
10644                getLLVMStyleWithColumns(60));
10645   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
10646                "  NSString *path = [self sessionFilePath];\n"
10647                "  if (path) {\n"
10648                "    // ...\n"
10649                "  }\n"
10650                "});");
10651   verifyFormat("[[SessionService sharedService]\n"
10652                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
10653                "      if (window) {\n"
10654                "        [self windowDidLoad:window];\n"
10655                "      } else {\n"
10656                "        [self errorLoadingWindow];\n"
10657                "      }\n"
10658                "    }];");
10659   verifyFormat("void (^largeBlock)(void) = ^{\n"
10660                "  // ...\n"
10661                "};\n",
10662                getLLVMStyleWithColumns(40));
10663   verifyFormat("[[SessionService sharedService]\n"
10664                "    loadWindowWithCompletionBlock: //\n"
10665                "        ^(SessionWindow *window) {\n"
10666                "          if (window) {\n"
10667                "            [self windowDidLoad:window];\n"
10668                "          } else {\n"
10669                "            [self errorLoadingWindow];\n"
10670                "          }\n"
10671                "        }];",
10672                getLLVMStyleWithColumns(60));
10673   verifyFormat("[myObject doSomethingWith:arg1\n"
10674                "    firstBlock:^(Foo *a) {\n"
10675                "      // ...\n"
10676                "      int i;\n"
10677                "    }\n"
10678                "    secondBlock:^(Bar *b) {\n"
10679                "      // ...\n"
10680                "      int i;\n"
10681                "    }\n"
10682                "    thirdBlock:^Foo(Bar *b) {\n"
10683                "      // ...\n"
10684                "      int i;\n"
10685                "    }];");
10686   verifyFormat("[myObject doSomethingWith:arg1\n"
10687                "               firstBlock:-1\n"
10688                "              secondBlock:^(Bar *b) {\n"
10689                "                // ...\n"
10690                "                int i;\n"
10691                "              }];");
10692
10693   verifyFormat("f(^{\n"
10694                "  @autoreleasepool {\n"
10695                "    if (a) {\n"
10696                "      g();\n"
10697                "    }\n"
10698                "  }\n"
10699                "});");
10700   verifyFormat("Block b = ^int *(A *a, B *b) {}");
10701
10702   FormatStyle FourIndent = getLLVMStyle();
10703   FourIndent.ObjCBlockIndentWidth = 4;
10704   verifyFormat("[operation setCompletionBlock:^{\n"
10705                "    [self onOperationDone];\n"
10706                "}];",
10707                FourIndent);
10708 }
10709
10710 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
10711   FormatStyle ZeroColumn = getLLVMStyle();
10712   ZeroColumn.ColumnLimit = 0;
10713
10714   verifyFormat("[[SessionService sharedService] "
10715                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
10716                "  if (window) {\n"
10717                "    [self windowDidLoad:window];\n"
10718                "  } else {\n"
10719                "    [self errorLoadingWindow];\n"
10720                "  }\n"
10721                "}];",
10722                ZeroColumn);
10723   EXPECT_EQ("[[SessionService sharedService]\n"
10724             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
10725             "      if (window) {\n"
10726             "        [self windowDidLoad:window];\n"
10727             "      } else {\n"
10728             "        [self errorLoadingWindow];\n"
10729             "      }\n"
10730             "    }];",
10731             format("[[SessionService sharedService]\n"
10732                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
10733                    "                if (window) {\n"
10734                    "    [self windowDidLoad:window];\n"
10735                    "  } else {\n"
10736                    "    [self errorLoadingWindow];\n"
10737                    "  }\n"
10738                    "}];",
10739                    ZeroColumn));
10740   verifyFormat("[myObject doSomethingWith:arg1\n"
10741                "    firstBlock:^(Foo *a) {\n"
10742                "      // ...\n"
10743                "      int i;\n"
10744                "    }\n"
10745                "    secondBlock:^(Bar *b) {\n"
10746                "      // ...\n"
10747                "      int i;\n"
10748                "    }\n"
10749                "    thirdBlock:^Foo(Bar *b) {\n"
10750                "      // ...\n"
10751                "      int i;\n"
10752                "    }];",
10753                ZeroColumn);
10754   verifyFormat("f(^{\n"
10755                "  @autoreleasepool {\n"
10756                "    if (a) {\n"
10757                "      g();\n"
10758                "    }\n"
10759                "  }\n"
10760                "});",
10761                ZeroColumn);
10762   verifyFormat("void (^largeBlock)(void) = ^{\n"
10763                "  // ...\n"
10764                "};",
10765                ZeroColumn);
10766
10767   ZeroColumn.AllowShortBlocksOnASingleLine = true;
10768   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
10769             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
10770   ZeroColumn.AllowShortBlocksOnASingleLine = false;
10771   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
10772             "  int i;\n"
10773             "};",
10774             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
10775 }
10776
10777 TEST_F(FormatTest, SupportsCRLF) {
10778   EXPECT_EQ("int a;\r\n"
10779             "int b;\r\n"
10780             "int c;\r\n",
10781             format("int a;\r\n"
10782                    "  int b;\r\n"
10783                    "    int c;\r\n",
10784                    getLLVMStyle()));
10785   EXPECT_EQ("int a;\r\n"
10786             "int b;\r\n"
10787             "int c;\r\n",
10788             format("int a;\r\n"
10789                    "  int b;\n"
10790                    "    int c;\r\n",
10791                    getLLVMStyle()));
10792   EXPECT_EQ("int a;\n"
10793             "int b;\n"
10794             "int c;\n",
10795             format("int a;\r\n"
10796                    "  int b;\n"
10797                    "    int c;\n",
10798                    getLLVMStyle()));
10799   EXPECT_EQ("\"aaaaaaa \"\r\n"
10800             "\"bbbbbbb\";\r\n",
10801             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
10802   EXPECT_EQ("#define A \\\r\n"
10803             "  b;      \\\r\n"
10804             "  c;      \\\r\n"
10805             "  d;\r\n",
10806             format("#define A \\\r\n"
10807                    "  b; \\\r\n"
10808                    "  c; d; \r\n",
10809                    getGoogleStyle()));
10810
10811   EXPECT_EQ("/*\r\n"
10812             "multi line block comments\r\n"
10813             "should not introduce\r\n"
10814             "an extra carriage return\r\n"
10815             "*/\r\n",
10816             format("/*\r\n"
10817                    "multi line block comments\r\n"
10818                    "should not introduce\r\n"
10819                    "an extra carriage return\r\n"
10820                    "*/\r\n"));
10821 }
10822
10823 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
10824   verifyFormat("MY_CLASS(C) {\n"
10825                "  int i;\n"
10826                "  int j;\n"
10827                "};");
10828 }
10829
10830 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
10831   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
10832   TwoIndent.ContinuationIndentWidth = 2;
10833
10834   EXPECT_EQ("int i =\n"
10835             "  longFunction(\n"
10836             "    arg);",
10837             format("int i = longFunction(arg);", TwoIndent));
10838
10839   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
10840   SixIndent.ContinuationIndentWidth = 6;
10841
10842   EXPECT_EQ("int i =\n"
10843             "      longFunction(\n"
10844             "            arg);",
10845             format("int i = longFunction(arg);", SixIndent));
10846 }
10847
10848 TEST_F(FormatTest, SpacesInAngles) {
10849   FormatStyle Spaces = getLLVMStyle();
10850   Spaces.SpacesInAngles = true;
10851
10852   verifyFormat("static_cast< int >(arg);", Spaces);
10853   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
10854   verifyFormat("f< int, float >();", Spaces);
10855   verifyFormat("template <> g() {}", Spaces);
10856   verifyFormat("template < std::vector< int > > f() {}", Spaces);
10857   verifyFormat("std::function< void(int, int) > fct;", Spaces);
10858   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
10859                Spaces);
10860
10861   Spaces.Standard = FormatStyle::LS_Cpp03;
10862   Spaces.SpacesInAngles = true;
10863   verifyFormat("A< A< int > >();", Spaces);
10864
10865   Spaces.SpacesInAngles = false;
10866   verifyFormat("A<A<int> >();", Spaces);
10867
10868   Spaces.Standard = FormatStyle::LS_Cpp11;
10869   Spaces.SpacesInAngles = true;
10870   verifyFormat("A< A< int > >();", Spaces);
10871
10872   Spaces.SpacesInAngles = false;
10873   verifyFormat("A<A<int>>();", Spaces);
10874 }
10875
10876 TEST_F(FormatTest, TripleAngleBrackets) {
10877   verifyFormat("f<<<1, 1>>>();");
10878   verifyFormat("f<<<1, 1, 1, s>>>();");
10879   verifyFormat("f<<<a, b, c, d>>>();");
10880   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
10881   verifyFormat("f<param><<<1, 1>>>();");
10882   verifyFormat("f<1><<<1, 1>>>();");
10883   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
10884   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
10885                "aaaaaaaaaaa<<<\n    1, 1>>>();");
10886 }
10887
10888 TEST_F(FormatTest, MergeLessLessAtEnd) {
10889   verifyFormat("<<");
10890   EXPECT_EQ("< < <", format("\\\n<<<"));
10891   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
10892                "aaallvm::outs() <<");
10893   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
10894                "aaaallvm::outs()\n    <<");
10895 }
10896
10897 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
10898   std::string code = "#if A\n"
10899                      "#if B\n"
10900                      "a.\n"
10901                      "#endif\n"
10902                      "    a = 1;\n"
10903                      "#else\n"
10904                      "#endif\n"
10905                      "#if C\n"
10906                      "#else\n"
10907                      "#endif\n";
10908   EXPECT_EQ(code, format(code));
10909 }
10910
10911 TEST_F(FormatTest, HandleConflictMarkers) {
10912   // Git/SVN conflict markers.
10913   EXPECT_EQ("int a;\n"
10914             "void f() {\n"
10915             "  callme(some(parameter1,\n"
10916             "<<<<<<< text by the vcs\n"
10917             "              parameter2),\n"
10918             "||||||| text by the vcs\n"
10919             "              parameter2),\n"
10920             "         parameter3,\n"
10921             "======= text by the vcs\n"
10922             "              parameter2, parameter3),\n"
10923             ">>>>>>> text by the vcs\n"
10924             "         otherparameter);\n",
10925             format("int a;\n"
10926                    "void f() {\n"
10927                    "  callme(some(parameter1,\n"
10928                    "<<<<<<< text by the vcs\n"
10929                    "  parameter2),\n"
10930                    "||||||| text by the vcs\n"
10931                    "  parameter2),\n"
10932                    "  parameter3,\n"
10933                    "======= text by the vcs\n"
10934                    "  parameter2,\n"
10935                    "  parameter3),\n"
10936                    ">>>>>>> text by the vcs\n"
10937                    "  otherparameter);\n"));
10938
10939   // Perforce markers.
10940   EXPECT_EQ("void f() {\n"
10941             "  function(\n"
10942             ">>>> text by the vcs\n"
10943             "      parameter,\n"
10944             "==== text by the vcs\n"
10945             "      parameter,\n"
10946             "==== text by the vcs\n"
10947             "      parameter,\n"
10948             "<<<< text by the vcs\n"
10949             "      parameter);\n",
10950             format("void f() {\n"
10951                    "  function(\n"
10952                    ">>>> text by the vcs\n"
10953                    "  parameter,\n"
10954                    "==== text by the vcs\n"
10955                    "  parameter,\n"
10956                    "==== text by the vcs\n"
10957                    "  parameter,\n"
10958                    "<<<< text by the vcs\n"
10959                    "  parameter);\n"));
10960
10961   EXPECT_EQ("<<<<<<<\n"
10962             "|||||||\n"
10963             "=======\n"
10964             ">>>>>>>",
10965             format("<<<<<<<\n"
10966                    "|||||||\n"
10967                    "=======\n"
10968                    ">>>>>>>"));
10969
10970   EXPECT_EQ("<<<<<<<\n"
10971             "|||||||\n"
10972             "int i;\n"
10973             "=======\n"
10974             ">>>>>>>",
10975             format("<<<<<<<\n"
10976                    "|||||||\n"
10977                    "int i;\n"
10978                    "=======\n"
10979                    ">>>>>>>"));
10980
10981   // FIXME: Handle parsing of macros around conflict markers correctly:
10982   EXPECT_EQ("#define Macro \\\n"
10983             "<<<<<<<\n"
10984             "Something \\\n"
10985             "|||||||\n"
10986             "Else \\\n"
10987             "=======\n"
10988             "Other \\\n"
10989             ">>>>>>>\n"
10990             "    End int i;\n",
10991             format("#define Macro \\\n"
10992                    "<<<<<<<\n"
10993                    "  Something \\\n"
10994                    "|||||||\n"
10995                    "  Else \\\n"
10996                    "=======\n"
10997                    "  Other \\\n"
10998                    ">>>>>>>\n"
10999                    "  End\n"
11000                    "int i;\n"));
11001 }
11002
11003 TEST_F(FormatTest, DisableRegions) {
11004   EXPECT_EQ("int i;\n"
11005             "// clang-format off\n"
11006             "  int j;\n"
11007             "// clang-format on\n"
11008             "int k;",
11009             format(" int  i;\n"
11010                    "   // clang-format off\n"
11011                    "  int j;\n"
11012                    " // clang-format on\n"
11013                    "   int   k;"));
11014   EXPECT_EQ("int i;\n"
11015             "/* clang-format off */\n"
11016             "  int j;\n"
11017             "/* clang-format on */\n"
11018             "int k;",
11019             format(" int  i;\n"
11020                    "   /* clang-format off */\n"
11021                    "  int j;\n"
11022                    " /* clang-format on */\n"
11023                    "   int   k;"));
11024 }
11025
11026 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
11027   format("? ) =");
11028   verifyNoCrash("#define a\\\n /**/}");
11029 }
11030
11031 TEST_F(FormatTest, FormatsTableGenCode) {
11032   FormatStyle Style = getLLVMStyle();
11033   Style.Language = FormatStyle::LK_TableGen;
11034   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
11035 }
11036
11037 } // end namespace
11038 } // end namespace format
11039 } // end namespace clang