FormatTest.cpp revision 9637dda705e39110bfff66742542a58dd2470ad2
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#define DEBUG_TYPE "format-test"
11
12#include "clang/Format/Format.h"
13#include "clang/Lex/Lexer.h"
14#include "llvm/Support/Debug.h"
15#include "gtest/gtest.h"
16
17namespace clang {
18namespace format {
19
20class FormatTest : public ::testing::Test {
21protected:
22  std::string format(llvm::StringRef Code, unsigned Offset, unsigned Length,
23                     const FormatStyle &Style) {
24    DEBUG(llvm::errs() << "---\n");
25    std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length));
26    tooling::Replacements Replaces = reformat(Style, Code, Ranges);
27    ReplacementCount = Replaces.size();
28    std::string Result = applyAllReplacements(Code, Replaces);
29    EXPECT_NE("", Result);
30    DEBUG(llvm::errs() << "\n" << Result << "\n\n");
31    return Result;
32  }
33
34  std::string
35  format(llvm::StringRef Code, const FormatStyle &Style = getLLVMStyle()) {
36    return format(Code, 0, Code.size(), Style);
37  }
38
39  std::string messUp(llvm::StringRef Code) {
40    std::string MessedUp(Code.str());
41    bool InComment = false;
42    bool InPreprocessorDirective = false;
43    bool JustReplacedNewline = false;
44    for (unsigned i = 0, e = MessedUp.size() - 1; i != e; ++i) {
45      if (MessedUp[i] == '/' && MessedUp[i + 1] == '/') {
46        if (JustReplacedNewline)
47          MessedUp[i - 1] = '\n';
48        InComment = true;
49      } else if (MessedUp[i] == '#' && (JustReplacedNewline || i == 0)) {
50        if (i != 0)
51          MessedUp[i - 1] = '\n';
52        InPreprocessorDirective = true;
53      } else if (MessedUp[i] == '\\' && MessedUp[i + 1] == '\n') {
54        MessedUp[i] = ' ';
55        MessedUp[i + 1] = ' ';
56      } else if (MessedUp[i] == '\n') {
57        if (InComment) {
58          InComment = false;
59        } else if (InPreprocessorDirective) {
60          InPreprocessorDirective = false;
61        } else {
62          JustReplacedNewline = true;
63          MessedUp[i] = ' ';
64        }
65      } else if (MessedUp[i] != ' ') {
66        JustReplacedNewline = false;
67      }
68    }
69    return MessedUp;
70  }
71
72  FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
73    FormatStyle Style = getLLVMStyle();
74    Style.ColumnLimit = ColumnLimit;
75    return Style;
76  }
77
78  FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
79    FormatStyle Style = getGoogleStyle();
80    Style.ColumnLimit = ColumnLimit;
81    return Style;
82  }
83
84  void verifyFormat(llvm::StringRef Code,
85                    const FormatStyle &Style = getLLVMStyle()) {
86    EXPECT_EQ(Code.str(), format(messUp(Code), Style));
87  }
88
89  void verifyGoogleFormat(llvm::StringRef Code) {
90    verifyFormat(Code, getGoogleStyle());
91  }
92
93  void verifyIndependentOfContext(llvm::StringRef text) {
94    verifyFormat(text);
95    verifyFormat(llvm::Twine("void f() { " + text + " }").str());
96  }
97
98  int ReplacementCount;
99};
100
101TEST_F(FormatTest, MessUp) {
102  EXPECT_EQ("1 2 3", messUp("1 2 3"));
103  EXPECT_EQ("1 2 3\n", messUp("1\n2\n3\n"));
104  EXPECT_EQ("a\n//b\nc", messUp("a\n//b\nc"));
105  EXPECT_EQ("a\n#b\nc", messUp("a\n#b\nc"));
106  EXPECT_EQ("a\n#b  c  d\ne", messUp("a\n#b\\\nc\\\nd\ne"));
107}
108
109//===----------------------------------------------------------------------===//
110// Basic function tests.
111//===----------------------------------------------------------------------===//
112
113TEST_F(FormatTest, DoesNotChangeCorrectlyFormatedCode) {
114  EXPECT_EQ(";", format(";"));
115}
116
117TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
118  EXPECT_EQ("int i;", format("  int i;"));
119  EXPECT_EQ("\nint i;", format(" \n\t \r  int i;"));
120  EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
121  EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
122}
123
124TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
125  EXPECT_EQ("int i;", format("int\ni;"));
126}
127
128TEST_F(FormatTest, FormatsNestedBlockStatements) {
129  EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
130}
131
132TEST_F(FormatTest, FormatsNestedCall) {
133  verifyFormat("Method(f1, f2(f3));");
134  verifyFormat("Method(f1(f2, f3()));");
135  verifyFormat("Method(f1(f2, (f3())));");
136}
137
138TEST_F(FormatTest, NestedNameSpecifiers) {
139  verifyFormat("vector< ::Type> v;");
140  verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
141}
142
143TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
144  EXPECT_EQ("if (a) {\n"
145            "  f();\n"
146            "}",
147            format("if(a){f();}"));
148  EXPECT_EQ(4, ReplacementCount);
149  EXPECT_EQ("if (a) {\n"
150            "  f();\n"
151            "}",
152            format("if (a) {\n"
153                   "  f();\n"
154                   "}"));
155  EXPECT_EQ(0, ReplacementCount);
156}
157
158TEST_F(FormatTest, RemovesTrailingWhitespaceOfFormattedLine) {
159  EXPECT_EQ("int a;\nint b;", format("int a; \nint b;", 0, 0, getLLVMStyle()));
160  EXPECT_EQ("int a;", format("int a;         "));
161  EXPECT_EQ("int a;\n", format("int a;  \n   \n   \n "));
162  EXPECT_EQ("int a;\nint b;    ",
163            format("int a;  \nint b;    ", 0, 0, getLLVMStyle()));
164}
165
166TEST_F(FormatTest, FormatsCorrectRegionForLeadingWhitespace) {
167  EXPECT_EQ("int b;\nint a;",
168            format("int b;\n   int a;", 7, 0, getLLVMStyle()));
169  EXPECT_EQ("int b;\n   int a;",
170            format("int b;\n   int a;", 6, 0, getLLVMStyle()));
171
172  EXPECT_EQ("#define A  \\\n"
173            "  int a;   \\\n"
174            "  int b;",
175            format("#define A  \\\n"
176                   "  int a;   \\\n"
177                   "    int b;",
178                   26, 0, getLLVMStyleWithColumns(12)));
179  EXPECT_EQ("#define A  \\\n"
180            "  int a;   \\\n"
181            "    int b;",
182            format("#define A  \\\n"
183                   "  int a;   \\\n"
184                   "    int b;",
185                   25, 0, getLLVMStyleWithColumns(12)));
186}
187
188TEST_F(FormatTest, RemovesWhitespaceWhenTriggeredOnEmptyLine) {
189  EXPECT_EQ("int  a;\n\n int b;",
190            format("int  a;\n  \n\n int b;", 7, 0, getLLVMStyle()));
191  EXPECT_EQ("int  a;\n\n int b;",
192            format("int  a;\n  \n\n int b;", 9, 0, getLLVMStyle()));
193}
194
195TEST_F(FormatTest, RemovesEmptyLines) {
196  EXPECT_EQ("class C {\n"
197            "  int i;\n"
198            "};",
199            format("class C {\n"
200                   " int i;\n"
201                   "\n"
202                   "};"));
203
204  // Don't remove empty lines in more complex control statements.
205  EXPECT_EQ("void f() {\n"
206            "  if (a) {\n"
207            "    f();\n"
208            "\n"
209            "  } else if (b) {\n"
210            "    f();\n"
211            "  }\n"
212            "}",
213            format("void f() {\n"
214                   "  if (a) {\n"
215                   "    f();\n"
216                   "\n"
217                   "  } else if (b) {\n"
218                   "    f();\n"
219                   "\n"
220                   "  }\n"
221                   "\n"
222                   "}"));
223
224  // FIXME: This is slightly inconsistent.
225  EXPECT_EQ("namespace {\n"
226            "int i;\n"
227            "}",
228            format("namespace {\n"
229                   "int i;\n"
230                   "\n"
231                   "}"));
232  EXPECT_EQ("namespace {\n"
233            "int i;\n"
234            "\n"
235            "} // namespace",
236            format("namespace {\n"
237                   "int i;\n"
238                   "\n"
239                   "}  // namespace"));
240}
241
242TEST_F(FormatTest, ReformatsMovedLines) {
243  EXPECT_EQ(
244      "template <typename T> T *getFETokenInfo() const {\n"
245      "  return static_cast<T *>(FETokenInfo);\n"
246      "}\n"
247      "  int a; // <- Should not be formatted",
248      format(
249          "template<typename T>\n"
250          "T *getFETokenInfo() const { return static_cast<T*>(FETokenInfo); }\n"
251          "  int a; // <- Should not be formatted",
252          9, 5, getLLVMStyle()));
253}
254
255//===----------------------------------------------------------------------===//
256// Tests for control statements.
257//===----------------------------------------------------------------------===//
258
259TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
260  verifyFormat("if (true)\n  f();\ng();");
261  verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
262  verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
263
264  FormatStyle AllowsMergedIf = getLLVMStyle();
265  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
266  verifyFormat("if (a)\n"
267               "  // comment\n"
268               "  f();",
269               AllowsMergedIf);
270  verifyFormat("if (a)\n"
271               "  ;",
272               AllowsMergedIf);
273  verifyFormat("if (a)\n"
274               "  if (b) return;",
275               AllowsMergedIf);
276
277  verifyFormat("if (a) // Can't merge this\n"
278               "  f();\n",
279               AllowsMergedIf);
280  verifyFormat("if (a) /* still don't merge */\n"
281               "  f();",
282               AllowsMergedIf);
283  verifyFormat("if (a) { // Never merge this\n"
284               "  f();\n"
285               "}",
286               AllowsMergedIf);
287  verifyFormat("if (a) { /* Never merge this */\n"
288               "  f();\n"
289               "}",
290               AllowsMergedIf);
291
292  EXPECT_EQ("if (a) return;", format("if(a)\nreturn;", 7, 1, AllowsMergedIf));
293  EXPECT_EQ("if (a) return; // comment",
294            format("if(a)\nreturn; // comment", 20, 1, AllowsMergedIf));
295
296  AllowsMergedIf.ColumnLimit = 14;
297  verifyFormat("if (a) return;", AllowsMergedIf);
298  verifyFormat("if (aaaaaaaaa)\n"
299               "  return;",
300               AllowsMergedIf);
301
302  AllowsMergedIf.ColumnLimit = 13;
303  verifyFormat("if (a)\n  return;", AllowsMergedIf);
304}
305
306TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
307  FormatStyle AllowsMergedLoops = getLLVMStyle();
308  AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
309  verifyFormat("while (true) continue;", AllowsMergedLoops);
310  verifyFormat("for (;;) continue;", AllowsMergedLoops);
311  verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
312  verifyFormat("while (true)\n"
313               "  ;",
314               AllowsMergedLoops);
315  verifyFormat("for (;;)\n"
316               "  ;",
317               AllowsMergedLoops);
318  verifyFormat("for (;;)\n"
319               "  for (;;) continue;",
320               AllowsMergedLoops);
321  verifyFormat("for (;;) // Can't merge this\n"
322               "  continue;",
323               AllowsMergedLoops);
324  verifyFormat("for (;;) /* still don't merge */\n"
325               "  continue;",
326               AllowsMergedLoops);
327}
328
329TEST_F(FormatTest, ParseIfElse) {
330  verifyFormat("if (true)\n"
331               "  if (true)\n"
332               "    if (true)\n"
333               "      f();\n"
334               "    else\n"
335               "      g();\n"
336               "  else\n"
337               "    h();\n"
338               "else\n"
339               "  i();");
340  verifyFormat("if (true)\n"
341               "  if (true)\n"
342               "    if (true) {\n"
343               "      if (true)\n"
344               "        f();\n"
345               "    } else {\n"
346               "      g();\n"
347               "    }\n"
348               "  else\n"
349               "    h();\n"
350               "else {\n"
351               "  i();\n"
352               "}");
353}
354
355TEST_F(FormatTest, ElseIf) {
356  verifyFormat("if (a) {\n} else if (b) {\n}");
357  verifyFormat("if (a)\n"
358               "  f();\n"
359               "else if (b)\n"
360               "  g();\n"
361               "else\n"
362               "  h();");
363}
364
365TEST_F(FormatTest, FormatsForLoop) {
366  verifyFormat(
367      "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
368      "     ++VeryVeryLongLoopVariable)\n"
369      "  ;");
370  verifyFormat("for (;;)\n"
371               "  f();");
372  verifyFormat("for (;;) {\n}");
373  verifyFormat("for (;;) {\n"
374               "  f();\n"
375               "}");
376  verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
377
378  verifyFormat(
379      "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
380      "                                          E = UnwrappedLines.end();\n"
381      "     I != E; ++I) {\n}");
382
383  verifyFormat(
384      "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
385      "     ++IIIII) {\n}");
386  verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
387               "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
388               "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
389  verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
390               "         I = FD->getDeclsInPrototypeScope().begin(),\n"
391               "         E = FD->getDeclsInPrototypeScope().end();\n"
392               "     I != E; ++I) {\n}");
393
394  // FIXME: Not sure whether we want extra identation in line 3 here:
395  verifyFormat(
396      "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
397      "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
398      "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
399      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
400      "     ++aaaaaaaaaaa) {\n}");
401  verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
402               "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
403               "}");
404  verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
405               "         aaaaaaaaaa);\n"
406               "     iter; ++iter) {\n"
407               "}");
408
409  FormatStyle NoBinPacking = getLLVMStyle();
410  NoBinPacking.BinPackParameters = false;
411  verifyFormat("for (int aaaaaaaaaaa = 1;\n"
412               "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
413               "                                           aaaaaaaaaaaaaaaa,\n"
414               "                                           aaaaaaaaaaaaaaaa,\n"
415               "                                           aaaaaaaaaaaaaaaa);\n"
416               "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
417               "}",
418               NoBinPacking);
419  verifyFormat(
420      "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
421      "                                          E = UnwrappedLines.end();\n"
422      "     I != E;\n"
423      "     ++I) {\n}",
424      NoBinPacking);
425}
426
427TEST_F(FormatTest, RangeBasedForLoops) {
428  verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
429               "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
430  verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
431               "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
432  verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
433               "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
434}
435
436TEST_F(FormatTest, FormatsWhileLoop) {
437  verifyFormat("while (true) {\n}");
438  verifyFormat("while (true)\n"
439               "  f();");
440  verifyFormat("while () {\n}");
441  verifyFormat("while () {\n"
442               "  f();\n"
443               "}");
444}
445
446TEST_F(FormatTest, FormatsDoWhile) {
447  verifyFormat("do {\n"
448               "  do_something();\n"
449               "} while (something());");
450  verifyFormat("do\n"
451               "  do_something();\n"
452               "while (something());");
453}
454
455TEST_F(FormatTest, FormatsSwitchStatement) {
456  verifyFormat("switch (x) {\n"
457               "case 1:\n"
458               "  f();\n"
459               "  break;\n"
460               "case kFoo:\n"
461               "case ns::kBar:\n"
462               "case kBaz:\n"
463               "  break;\n"
464               "default:\n"
465               "  g();\n"
466               "  break;\n"
467               "}");
468  verifyFormat("switch (x) {\n"
469               "case 1: {\n"
470               "  f();\n"
471               "  break;\n"
472               "}\n"
473               "}");
474  verifyFormat("switch (x) {\n"
475               "case 1: {\n"
476               "  f();\n"
477               "  {\n"
478               "    g();\n"
479               "    h();\n"
480               "  }\n"
481               "  break;\n"
482               "}\n"
483               "}");
484  verifyFormat("switch (x) {\n"
485               "case 1: {\n"
486               "  f();\n"
487               "  if (foo) {\n"
488               "    g();\n"
489               "    h();\n"
490               "  }\n"
491               "  break;\n"
492               "}\n"
493               "}");
494  verifyFormat("switch (x) {\n"
495               "case 1: {\n"
496               "  f();\n"
497               "  g();\n"
498               "} break;\n"
499               "}");
500  verifyFormat("switch (test)\n"
501               "  ;");
502  verifyFormat("switch (x) {\n"
503               "default: {\n"
504               "  // Do nothing.\n"
505               "}\n"
506               "}");
507  verifyFormat("switch (x) {\n"
508               "// comment\n"
509               "// if 1, do f()\n"
510               "case 1:\n"
511               "  f();\n"
512               "}");
513  verifyFormat("switch (x) {\n"
514               "case 1:\n"
515               "  // Do amazing stuff\n"
516               "  {\n"
517               "    f();\n"
518               "    g();\n"
519               "  }\n"
520               "  break;\n"
521               "}");
522  verifyFormat("#define A          \\\n"
523               "  switch (x) {     \\\n"
524               "  case a:          \\\n"
525               "    foo = b;       \\\n"
526               "  }", getLLVMStyleWithColumns(20));
527
528  verifyGoogleFormat("switch (x) {\n"
529                     "  case 1:\n"
530                     "    f();\n"
531                     "    break;\n"
532                     "  case kFoo:\n"
533                     "  case ns::kBar:\n"
534                     "  case kBaz:\n"
535                     "    break;\n"
536                     "  default:\n"
537                     "    g();\n"
538                     "    break;\n"
539                     "}");
540  verifyGoogleFormat("switch (x) {\n"
541                     "  case 1: {\n"
542                     "    f();\n"
543                     "    break;\n"
544                     "  }\n"
545                     "}");
546  verifyGoogleFormat("switch (test)\n"
547                     "    ;");
548}
549
550TEST_F(FormatTest, FormatsLabels) {
551  verifyFormat("void f() {\n"
552               "  some_code();\n"
553               "test_label:\n"
554               "  some_other_code();\n"
555               "  {\n"
556               "    some_more_code();\n"
557               "  another_label:\n"
558               "    some_more_code();\n"
559               "  }\n"
560               "}");
561  verifyFormat("some_code();\n"
562               "test_label:\n"
563               "some_other_code();");
564}
565
566//===----------------------------------------------------------------------===//
567// Tests for comments.
568//===----------------------------------------------------------------------===//
569
570TEST_F(FormatTest, UnderstandsSingleLineComments) {
571  verifyFormat("//* */");
572  verifyFormat("// line 1\n"
573               "// line 2\n"
574               "void f() {}\n");
575
576  verifyFormat("void f() {\n"
577               "  // Doesn't do anything\n"
578               "}");
579  verifyFormat("SomeObject\n"
580               "    // Calling someFunction on SomeObject\n"
581               "    .someFunction();");
582  verifyFormat("void f(int i,  // some comment (probably for i)\n"
583               "       int j,  // some comment (probably for j)\n"
584               "       int k); // some comment (probably for k)");
585  verifyFormat("void f(int i,\n"
586               "       // some comment (probably for j)\n"
587               "       int j,\n"
588               "       // some comment (probably for k)\n"
589               "       int k);");
590
591  verifyFormat("int i    // This is a fancy variable\n"
592               "    = 5; // with nicely aligned comment.");
593
594  verifyFormat("// Leading comment.\n"
595               "int a; // Trailing comment.");
596  verifyFormat("int a; // Trailing comment\n"
597               "       // on 2\n"
598               "       // or 3 lines.\n"
599               "int b;");
600  verifyFormat("int a; // Trailing comment\n"
601               "\n"
602               "// Leading comment.\n"
603               "int b;");
604  verifyFormat("int a;    // Comment.\n"
605               "          // More details.\n"
606               "int bbbb; // Another comment.");
607  verifyFormat(
608      "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
609      "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   // comment\n"
610      "int cccccccccccccccccccccccccccccc;       // comment\n"
611      "int ddd;                     // looooooooooooooooooooooooong comment\n"
612      "int aaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
613      "int bbbbbbbbbbbbbbbbbbbbb;   // comment\n"
614      "int ccccccccccccccccccc;     // comment");
615
616  verifyFormat("#include \"a\"     // comment\n"
617               "#include \"a/b/c\" // comment");
618  verifyFormat("#include <a>     // comment\n"
619               "#include <a/b/c> // comment");
620  EXPECT_EQ("#include \\\n"
621            "  \"a\"            // comment\n"
622            "#include \"a/b/c\" // comment",
623            format("#include \\\n"
624                   "  \"a\" // comment\n"
625                   "#include \"a/b/c\" // comment"));
626
627  verifyFormat("enum E {\n"
628               "  // comment\n"
629               "  VAL_A, // comment\n"
630               "  VAL_B\n"
631               "};");
632
633  verifyFormat(
634      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
635      "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // Trailing comment");
636  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
637               "    // Comment inside a statement.\n"
638               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
639  verifyFormat(
640      "bool aaaaaaaaaaaaa = // comment\n"
641      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
642      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
643
644  verifyFormat("int aaaa; // aaaaa\n"
645               "int aa;   // aaaaaaa",
646               getLLVMStyleWithColumns(20));
647
648  EXPECT_EQ("void f() { // This does something ..\n"
649            "}\n"
650            "int a; // This is unrelated",
651            format("void f()    {     // This does something ..\n"
652                   "  }\n"
653                   "int   a;     // This is unrelated"));
654  EXPECT_EQ("class C {\n"
655            "  void f() { // This does something ..\n"
656            "  }          // awesome..\n"
657            "\n"
658            "  int a; // This is unrelated\n"
659            "};",
660            format("class C{void f()    { // This does something ..\n"
661                   "      } // awesome..\n"
662                   " \n"
663                   "int a;    // This is unrelated\n"
664                   "};"));
665
666  EXPECT_EQ("int i; // single line trailing comment",
667            format("int i;\\\n// single line trailing comment"));
668
669  verifyGoogleFormat("int a;  // Trailing comment.");
670
671  verifyFormat("someFunction(anotherFunction( // Force break.\n"
672               "    parameter));");
673
674  verifyGoogleFormat("#endif  // HEADER_GUARD");
675
676  verifyFormat("const char *test[] = {\n"
677               "  // A\n"
678               "  \"aaaa\",\n"
679               "  // B\n"
680               "  \"aaaaa\",\n"
681               "};");
682  verifyGoogleFormat(
683      "aaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
684      "    aaaaaaaaaaaaaaaaaaaaaa);  // 81_cols_with_this_comment");
685  EXPECT_EQ("D(a, {\n"
686            "  // test\n"
687            "  int a;\n"
688            "});",
689            format("D(a, {\n"
690                   "// test\n"
691                   "int a;\n"
692                   "});"));
693
694  EXPECT_EQ("lineWith(); // comment\n"
695            "// at start\n"
696            "otherLine();",
697            format("lineWith();   // comment\n"
698                   "// at start\n"
699                   "otherLine();"));
700  EXPECT_EQ("lineWith(); // comment\n"
701            "            // at start\n"
702            "otherLine();",
703            format("lineWith();   // comment\n"
704                   " // at start\n"
705                   "otherLine();"));
706
707  EXPECT_EQ("lineWith(); // comment\n"
708            "// at start\n"
709            "otherLine(); // comment",
710            format("lineWith();   // comment\n"
711                   "// at start\n"
712                   "otherLine();   // comment"));
713  EXPECT_EQ("lineWith();\n"
714            "// at start\n"
715            "otherLine(); // comment",
716            format("lineWith();\n"
717                   " // at start\n"
718                   "otherLine();   // comment"));
719  EXPECT_EQ("// first\n"
720            "// at start\n"
721            "otherLine(); // comment",
722            format("// first\n"
723                   " // at start\n"
724                   "otherLine();   // comment"));
725  EXPECT_EQ("f();\n"
726            "// first\n"
727            "// at start\n"
728            "otherLine(); // comment",
729            format("f();\n"
730                   "// first\n"
731                   " // at start\n"
732                   "otherLine();   // comment"));
733}
734
735TEST_F(FormatTest, CanFormatCommentsLocally) {
736  EXPECT_EQ("int a;    // comment\n"
737            "int    b; // comment",
738            format("int   a; // comment\n"
739                   "int    b; // comment",
740                   0, 0, getLLVMStyle()));
741  EXPECT_EQ("int   a; // comment\n"
742            "         // line 2\n"
743            "int b;",
744            format("int   a; // comment\n"
745                   "            // line 2\n"
746                   "int b;",
747                   28, 0, getLLVMStyle()));
748  EXPECT_EQ("int aaaaaa; // comment\n"
749            "int b;\n"
750            "int c; // unrelated comment",
751            format("int aaaaaa; // comment\n"
752                   "int b;\n"
753                   "int   c; // unrelated comment",
754                   31, 0, getLLVMStyle()));
755}
756
757TEST_F(FormatTest, RemovesTrailingWhitespaceOfComments) {
758  EXPECT_EQ("// comment", format("// comment  "));
759  EXPECT_EQ("int aaaaaaa, bbbbbbb; // comment",
760            format("int aaaaaaa, bbbbbbb; // comment                   ",
761                   getLLVMStyleWithColumns(33)));
762}
763
764TEST_F(FormatTest, UnderstandsBlockComments) {
765  verifyFormat("f(/*noSpaceAfterParameterNamingComment=*/true);");
766  EXPECT_EQ(
767      "f(aaaaaaaaaaaaaaaaaaaaaaaaa, /* Trailing comment for aa... */\n"
768      "  bbbbbbbbbbbbbbbbbbbbbbbbb);",
769      format("f(aaaaaaaaaaaaaaaaaaaaaaaaa ,   \\\n/* Trailing comment for aa... */\n"
770             "  bbbbbbbbbbbbbbbbbbbbbbbbb);"));
771  EXPECT_EQ(
772      "f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
773      "  /* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);",
774      format("f(aaaaaaaaaaaaaaaaaaaaaaaaa    ,   \n"
775             "/* Leading comment for bb... */   bbbbbbbbbbbbbbbbbbbbbbbbb);"));
776  EXPECT_EQ(
777      "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
778      "    aaaaaaaaaaaaaaaaaa,\n"
779      "    aaaaaaaaaaaaaaaaaa) { /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
780      "}",
781      format("void      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
782             "                      aaaaaaaaaaaaaaaaaa  ,\n"
783             "    aaaaaaaaaaaaaaaaaa) {   /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
784             "}"));
785
786  FormatStyle NoBinPacking = getLLVMStyle();
787  NoBinPacking.BinPackParameters = false;
788  verifyFormat("aaaaaaaa(/* parameter 1 */ aaaaaa,\n"
789               "         /* parameter 2 */ aaaaaa,\n"
790               "         /* parameter 3 */ aaaaaa,\n"
791               "         /* parameter 4 */ aaaaaa);",
792               NoBinPacking);
793}
794
795TEST_F(FormatTest, AlignsBlockComments) {
796  EXPECT_EQ("/*\n"
797            " * Really multi-line\n"
798            " * comment.\n"
799            " */\n"
800            "void f() {}",
801            format("  /*\n"
802                   "   * Really multi-line\n"
803                   "   * comment.\n"
804                   "   */\n"
805                   "  void f() {}"));
806  EXPECT_EQ("class C {\n"
807            "  /*\n"
808            "   * Another multi-line\n"
809            "   * comment.\n"
810            "   */\n"
811            "  void f() {}\n"
812            "};",
813            format("class C {\n"
814                   "/*\n"
815                   " * Another multi-line\n"
816                   " * comment.\n"
817                   " */\n"
818                   "void f() {}\n"
819                   "};"));
820  EXPECT_EQ("/*\n"
821            "  1. This is a comment with non-trivial formatting.\n"
822            "     1.1. We have to indent/outdent all lines equally\n"
823            "         1.1.1. to keep the formatting.\n"
824            " */",
825            format("  /*\n"
826                   "    1. This is a comment with non-trivial formatting.\n"
827                   "       1.1. We have to indent/outdent all lines equally\n"
828                   "           1.1.1. to keep the formatting.\n"
829                   "   */"));
830  EXPECT_EQ("/*\n"
831            "Don't try to outdent if there's not enough inentation.\n"
832            "*/",
833            format("  /*\n"
834                   " Don't try to outdent if there's not enough inentation.\n"
835                   " */"));
836
837  EXPECT_EQ("int i; /* Comment with empty...\n"
838            "        *\n"
839            "        * line. */",
840            format("int i; /* Comment with empty...\n"
841                   "        *\n"
842                   "        * line. */"));
843}
844
845TEST_F(FormatTest, CorrectlyHandlesLengthOfBlockComments) {
846  EXPECT_EQ("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
847            "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */",
848            format("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
849                   "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */"));
850  EXPECT_EQ(
851      "void ffffffffffff(\n"
852      "    int aaaaaaaa, int bbbbbbbb,\n"
853      "    int cccccccccccc) { /*\n"
854      "                           aaaaaaaaaa\n"
855      "                           aaaaaaaaaaaaa\n"
856      "                           bbbbbbbbbbbbbb\n"
857      "                           bbbbbbbbbb\n"
858      "                         */\n"
859      "}",
860      format("void ffffffffffff(int aaaaaaaa, int bbbbbbbb, int cccccccccccc)\n"
861             "{ /*\n"
862             "     aaaaaaaaaa aaaaaaaaaaaaa\n"
863             "     bbbbbbbbbbbbbb bbbbbbbbbb\n"
864             "   */\n"
865             "}",
866             getLLVMStyleWithColumns(40)));
867}
868
869TEST_F(FormatTest, SplitsLongCxxComments) {
870  EXPECT_EQ("// A comment that\n"
871            "// doesn't fit on\n"
872            "// one line",
873            format("// A comment that doesn't fit on one line",
874                   getLLVMStyleWithColumns(20)));
875  EXPECT_EQ("// a b c d\n"
876            "// e f  g\n"
877            "// h i j k",
878            format("// a b c d e f  g h i j k",
879                   getLLVMStyleWithColumns(10)));
880  EXPECT_EQ("// a b c d\n"
881            "// e f  g\n"
882            "// h i j k",
883            format("\\\n// a b c d e f  g h i j k",
884                   getLLVMStyleWithColumns(10)));
885  EXPECT_EQ("if (true) // A comment that\n"
886            "          // doesn't fit on\n"
887            "          // one line",
888            format("if (true) // A comment that doesn't fit on one line   ",
889                   getLLVMStyleWithColumns(30)));
890  EXPECT_EQ("//    Don't_touch_leading_whitespace",
891            format("//    Don't_touch_leading_whitespace",
892                   getLLVMStyleWithColumns(20)));
893  EXPECT_EQ("// Add leading\n"
894            "// whitespace",
895            format("//Add leading whitespace", getLLVMStyleWithColumns(20)));
896  EXPECT_EQ("// whitespace", format("//whitespace", getLLVMStyle()));
897  EXPECT_EQ("// Even if it makes the line exceed the column\n"
898            "// limit",
899            format("//Even if it makes the line exceed the column limit",
900                   getLLVMStyleWithColumns(51)));
901  EXPECT_EQ("//--But not here", format("//--But not here", getLLVMStyle()));
902  EXPECT_EQ("// A comment before\n"
903            "// a macro\n"
904            "// definition\n"
905            "#define a b",
906            format("// A comment before a macro definition\n"
907                   "#define a b",
908                   getLLVMStyleWithColumns(20)));
909  EXPECT_EQ("void ffffff(int aaaaaaaaa,  // wwww\n"
910            "            int a, int bbb, // xxxxxxx\n"
911            "                            // yyyyyyyyy\n"
912            "            int c, int d, int e) {}",
913            format("void ffffff(\n"
914                   "    int aaaaaaaaa, // wwww\n"
915                   "    int a,\n"
916                   "    int bbb, // xxxxxxx yyyyyyyyy\n"
917                   "    int c, int d, int e) {}",
918                   getLLVMStyleWithColumns(40)));
919  EXPECT_EQ("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
920            format("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
921                   getLLVMStyleWithColumns(20)));
922}
923
924TEST_F(FormatTest, PriorityOfCommentBreaking) {
925  EXPECT_EQ("if (xxx == yyy && // aaaaaaaaaaaa\n"
926            "                  // bbbbbbbbb\n"
927            "    zzz)\n"
928            "  q();",
929            format("if (xxx == yyy && // aaaaaaaaaaaa bbbbbbbbb\n"
930                   "    zzz) q();",
931                   getLLVMStyleWithColumns(40)));
932  EXPECT_EQ("if (xxxxxxxxxx ==\n"
933            "        yyy && // aaaaaa bbbbbbbb cccc\n"
934            "    zzz)\n"
935            "  q();",
936            format("if (xxxxxxxxxx == yyy && // aaaaaa bbbbbbbb cccc\n"
937                   "    zzz) q();",
938                   getLLVMStyleWithColumns(40)));
939  EXPECT_EQ("if (xxxxxxxxxx &&\n"
940            "        yyy || // aaaaaa bbbbbbbb cccc\n"
941            "    zzz)\n"
942            "  q();",
943            format("if (xxxxxxxxxx && yyy || // aaaaaa bbbbbbbb cccc\n"
944                   "    zzz) q();",
945                   getLLVMStyleWithColumns(40)));
946  EXPECT_EQ("fffffffff(&xxx, // aaaaaaaaaaaa\n"
947            "                // bbbbbbbbbbb\n"
948            "          zzz);",
949            format("fffffffff(&xxx, // aaaaaaaaaaaa bbbbbbbbbbb\n"
950                   " zzz);",
951                   getLLVMStyleWithColumns(40)));
952}
953
954TEST_F(FormatTest, MultiLineCommentsInDefines) {
955  EXPECT_EQ("#define A(x) /* \\\n"
956            "  a comment     \\\n"
957            "  inside */     \\\n"
958            "  f();",
959            format("#define A(x) /* \\\n"
960                   "  a comment     \\\n"
961                   "  inside */     \\\n"
962                   "  f();",
963                   getLLVMStyleWithColumns(17)));
964  EXPECT_EQ("#define A(      \\\n"
965            "    x) /*       \\\n"
966            "  a comment     \\\n"
967            "  inside */     \\\n"
968            "  f();",
969            format("#define A(      \\\n"
970                   "    x) /*       \\\n"
971                   "  a comment     \\\n"
972                   "  inside */     \\\n"
973                   "  f();",
974                   getLLVMStyleWithColumns(17)));
975}
976
977TEST_F(FormatTest, ParsesCommentsAdjacentToPPDirectives) {
978  EXPECT_EQ("namespace {}\n// Test\n#define A",
979            format("namespace {}\n   // Test\n#define A"));
980  EXPECT_EQ("namespace {}\n/* Test */\n#define A",
981            format("namespace {}\n   /* Test */\n#define A"));
982  EXPECT_EQ("namespace {}\n/* Test */ #define A",
983            format("namespace {}\n   /* Test */    #define A"));
984}
985
986TEST_F(FormatTest, SplitsLongLinesInComments) {
987  EXPECT_EQ("/* This is a long\n"
988            " * comment that\n"
989            " * doesn't\n"
990            " * fit on one line.\n"
991            " */",
992            format("/* "
993                   "This is a long                                         "
994                   "comment that "
995                   "doesn't                                    "
996                   "fit on one line.  */",
997                   getLLVMStyleWithColumns(20)));
998  EXPECT_EQ("/* a b c d\n"
999            " * e f  g\n"
1000            " * h i j k\n"
1001            " */",
1002            format("/* a b c d e f  g h i j k */",
1003                   getLLVMStyleWithColumns(10)));
1004  EXPECT_EQ("/* a b c d\n"
1005            " * e f  g\n"
1006            " * h i j k\n"
1007            " */",
1008            format("\\\n/* a b c d e f  g h i j k */",
1009                   getLLVMStyleWithColumns(10)));
1010  EXPECT_EQ("/*\n"
1011            "This is a long\n"
1012            "comment that doesn't\n"
1013            "fit on one line.\n"
1014            "*/",
1015            format("/*\n"
1016                   "This is a long                                         "
1017                   "comment that doesn't                                    "
1018                   "fit on one line.                                      \n"
1019                   "*/", getLLVMStyleWithColumns(20)));
1020  EXPECT_EQ("/*\n"
1021            " * This is a long\n"
1022            " * comment that\n"
1023            " * doesn't fit on\n"
1024            " * one line.\n"
1025            " */",
1026            format("/*      \n"
1027                   " * This is a long "
1028                   "   comment that     "
1029                   "   doesn't fit on   "
1030                   "   one line.                                            \n"
1031                   " */", getLLVMStyleWithColumns(20)));
1032  EXPECT_EQ("/*\n"
1033            " * This_is_a_comment_with_words_that_dont_fit_on_one_line\n"
1034            " * so_it_should_be_broken\n"
1035            " * wherever_a_space_occurs\n"
1036            " */",
1037            format("/*\n"
1038                   " * This_is_a_comment_with_words_that_dont_fit_on_one_line "
1039                   "   so_it_should_be_broken "
1040                   "   wherever_a_space_occurs                             \n"
1041                   " */",
1042                   getLLVMStyleWithColumns(20)));
1043  EXPECT_EQ("/*\n"
1044            " *    This_comment_can_not_be_broken_into_lines\n"
1045            " */",
1046            format("/*\n"
1047                   " *    This_comment_can_not_be_broken_into_lines\n"
1048                   " */",
1049                   getLLVMStyleWithColumns(20)));
1050  EXPECT_EQ("{\n"
1051            "  /*\n"
1052            "  This is another\n"
1053            "  long comment that\n"
1054            "  doesn't fit on one\n"
1055            "  line    1234567890\n"
1056            "  */\n"
1057            "}",
1058            format("{\n"
1059                   "/*\n"
1060                   "This is another     "
1061                   "  long comment that "
1062                   "  doesn't fit on one"
1063                   "  line    1234567890\n"
1064                   "*/\n"
1065                   "}", getLLVMStyleWithColumns(20)));
1066  EXPECT_EQ("{\n"
1067            "  /*\n"
1068            "   * This        i s\n"
1069            "   * another comment\n"
1070            "   * t hat  doesn' t\n"
1071            "   * fit on one l i\n"
1072            "   * n e\n"
1073            "   */\n"
1074            "}",
1075            format("{\n"
1076                   "/*\n"
1077                   " * This        i s"
1078                   "   another comment"
1079                   "   t hat  doesn' t"
1080                   "   fit on one l i"
1081                   "   n e\n"
1082                   " */\n"
1083                   "}", getLLVMStyleWithColumns(20)));
1084  EXPECT_EQ("/*\n"
1085            " * This is a long\n"
1086            " * comment that\n"
1087            " * doesn't fit on\n"
1088            " * one line\n"
1089            " */",
1090            format("   /*\n"
1091                   "    * This is a long comment that doesn't fit on one line\n"
1092                   "    */", getLLVMStyleWithColumns(20)));
1093  EXPECT_EQ("{\n"
1094            "  if (something) /* This is a\n"
1095            "                    long\n"
1096            "                    comment */\n"
1097            "    ;\n"
1098            "}",
1099            format("{\n"
1100                   "  if (something) /* This is a long comment */\n"
1101                   "    ;\n"
1102                   "}",
1103                   getLLVMStyleWithColumns(30)));
1104
1105  EXPECT_EQ("/* A comment before\n"
1106            " * a macro\n"
1107            " * definition */\n"
1108            "#define a b",
1109            format("/* A comment before a macro definition */\n"
1110                   "#define a b",
1111                   getLLVMStyleWithColumns(20)));
1112
1113  EXPECT_EQ("/* some comment\n"
1114            "     *   a comment\n"
1115            "* that we break\n"
1116            " * another comment\n"
1117            "* we have to break\n"
1118            "* a left comment\n"
1119            " */",
1120            format("  /* some comment\n"
1121                   "       *   a comment that we break\n"
1122                   "   * another comment we have to break\n"
1123                   "* a left comment\n"
1124                   "   */",
1125                   getLLVMStyleWithColumns(20)));
1126
1127  EXPECT_EQ("/*\n"
1128            "\n"
1129            "\n"
1130            "    */\n",
1131            format("  /*       \n"
1132                   "      \n"
1133                   "               \n"
1134                   "      */\n"));
1135}
1136
1137TEST_F(FormatTest, SplitsLongLinesInCommentsInPreprocessor) {
1138  EXPECT_EQ("#define X          \\\n"
1139            "  /*               \\\n"
1140            "   Test            \\\n"
1141            "   Macro comment   \\\n"
1142            "   with a long     \\\n"
1143            "   line            \\\n"
1144            "   */              \\\n"
1145            "  A + B",
1146            format("#define X \\\n"
1147                   "  /*\n"
1148                   "   Test\n"
1149                   "   Macro comment with a long  line\n"
1150                   "   */ \\\n"
1151                   "  A + B",
1152                   getLLVMStyleWithColumns(20)));
1153  EXPECT_EQ("#define X          \\\n"
1154            "  /* Macro comment \\\n"
1155            "     with a long   \\\n"
1156            "     line */       \\\n"
1157            "  A + B",
1158            format("#define X \\\n"
1159                   "  /* Macro comment with a long\n"
1160                   "     line */ \\\n"
1161                   "  A + B",
1162                   getLLVMStyleWithColumns(20)));
1163  EXPECT_EQ("#define X          \\\n"
1164            "  /* Macro comment \\\n"
1165            "   * with a long   \\\n"
1166            "   * line */       \\\n"
1167            "  A + B",
1168            format("#define X \\\n"
1169                   "  /* Macro comment with a long  line */ \\\n"
1170                   "  A + B",
1171                   getLLVMStyleWithColumns(20)));
1172}
1173
1174TEST_F(FormatTest, CommentsInStaticInitializers) {
1175  EXPECT_EQ(
1176      "static SomeType type = { aaaaaaaaaaaaaaaaaaaa, /* comment */\n"
1177      "                         aaaaaaaaaaaaaaaaaaaa /* comment */,\n"
1178      "                         /* comment */ aaaaaaaaaaaaaaaaaaaa,\n"
1179      "                         aaaaaaaaaaaaaaaaaaaa, // comment\n"
1180      "                         aaaaaaaaaaaaaaaaaaaa };",
1181      format("static SomeType type = { aaaaaaaaaaaaaaaaaaaa  ,  /* comment */\n"
1182             "                   aaaaaaaaaaaaaaaaaaaa   /* comment */ ,\n"
1183             "                     /* comment */   aaaaaaaaaaaaaaaaaaaa ,\n"
1184             "              aaaaaaaaaaaaaaaaaaaa ,   // comment\n"
1185             "                  aaaaaaaaaaaaaaaaaaaa };"));
1186  verifyFormat("static SomeType type = { aaaaaaaaaaa, // comment for aa...\n"
1187               "                         bbbbbbbbbbb, ccccccccccc };");
1188  verifyFormat("static SomeType type = { aaaaaaaaaaa,\n"
1189               "                         // comment for bb....\n"
1190               "                         bbbbbbbbbbb, ccccccccccc };");
1191  verifyGoogleFormat(
1192      "static SomeType type = {aaaaaaaaaaa,  // comment for aa...\n"
1193      "                        bbbbbbbbbbb, ccccccccccc};");
1194  verifyGoogleFormat("static SomeType type = {aaaaaaaaaaa,\n"
1195                     "                        // comment for bb....\n"
1196                     "                        bbbbbbbbbbb, ccccccccccc};");
1197
1198  verifyFormat("S s = { { a, b, c },   // Group #1\n"
1199               "        { d, e, f },   // Group #2\n"
1200               "        { g, h, i } }; // Group #3");
1201  verifyFormat("S s = { { // Group #1\n"
1202               "          a, b, c },\n"
1203               "        { // Group #2\n"
1204               "          d, e, f },\n"
1205               "        { // Group #3\n"
1206               "          g, h, i } };");
1207
1208  EXPECT_EQ("S s = {\n"
1209            "  // Some comment\n"
1210            "  a,\n"
1211            "\n"
1212            "  // Comment after empty line\n"
1213            "  b\n"
1214            "}",
1215            format("S s =    {\n"
1216                   "      // Some comment\n"
1217                   "  a,\n"
1218                   "  \n"
1219                   "     // Comment after empty line\n"
1220                   "      b\n"
1221                   "}"));
1222  EXPECT_EQ("S s = {\n"
1223            "  /* Some comment */\n"
1224            "  a,\n"
1225            "\n"
1226            "  /* Comment after empty line */\n"
1227            "  b\n"
1228            "}",
1229            format("S s =    {\n"
1230                   "      /* Some comment */\n"
1231                   "  a,\n"
1232                   "  \n"
1233                   "     /* Comment after empty line */\n"
1234                   "      b\n"
1235                   "}"));
1236  verifyFormat("const uint8_t aaaaaaaaaaaaaaaaaaaaaa[0] = {\n"
1237               "  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1238               "  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1239               "  0x00, 0x00, 0x00, 0x00              // comment\n"
1240               "};");
1241}
1242
1243TEST_F(FormatTest, IgnoresIf0Contents) {
1244  EXPECT_EQ("#if 0\n"
1245            "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1246            "#endif\n"
1247            "void f() {}",
1248            format("#if 0\n"
1249                   "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1250                   "#endif\n"
1251                   "void f(  ) {  }"));
1252  EXPECT_EQ("#if false\n"
1253            "void f(  ) {  }\n"
1254            "#endif\n"
1255            "void g() {}\n",
1256            format("#if false\n"
1257                   "void f(  ) {  }\n"
1258                   "#endif\n"
1259                   "void g(  ) {  }\n"));
1260  EXPECT_EQ("enum E {\n"
1261            "  One,\n"
1262            "  Two,\n"
1263            "#if 0\n"
1264            "Three,\n"
1265            "      Four,\n"
1266            "#endif\n"
1267            "  Five\n"
1268            "};",
1269            format("enum E {\n"
1270                   "  One,Two,\n"
1271                   "#if 0\n"
1272                   "Three,\n"
1273                   "      Four,\n"
1274                   "#endif\n"
1275                   "  Five};"));
1276  EXPECT_EQ("enum F {\n"
1277            "  One,\n"
1278            "#if 1\n"
1279            "  Two,\n"
1280            "#if 0\n"
1281            "Three,\n"
1282            "      Four,\n"
1283            "#endif\n"
1284            "  Five\n"
1285            "#endif\n"
1286            "};",
1287            format("enum F {\n"
1288                   "One,\n"
1289                   "#if 1\n"
1290                   "Two,\n"
1291                   "#if 0\n"
1292                   "Three,\n"
1293                   "      Four,\n"
1294                   "#endif\n"
1295                   "Five\n"
1296                   "#endif\n"
1297                   "};"));
1298  EXPECT_EQ("enum G {\n"
1299            "  One,\n"
1300            "#if 0\n"
1301            "Two,\n"
1302            "#else\n"
1303            "  Three,\n"
1304            "#endif\n"
1305            "  Four\n"
1306            "};",
1307            format("enum G {\n"
1308                   "One,\n"
1309                   "#if 0\n"
1310                   "Two,\n"
1311                   "#else\n"
1312                   "Three,\n"
1313                   "#endif\n"
1314                   "Four\n"
1315                   "};"));
1316  EXPECT_EQ("enum H {\n"
1317            "  One,\n"
1318            "#if 0\n"
1319            "#ifdef Q\n"
1320            "Two,\n"
1321            "#else\n"
1322            "Three,\n"
1323            "#endif\n"
1324            "#endif\n"
1325            "  Four\n"
1326            "};",
1327            format("enum H {\n"
1328                   "One,\n"
1329                   "#if 0\n"
1330                   "#ifdef Q\n"
1331                   "Two,\n"
1332                   "#else\n"
1333                   "Three,\n"
1334                   "#endif\n"
1335                   "#endif\n"
1336                   "Four\n"
1337                   "};"));
1338  EXPECT_EQ("enum I {\n"
1339            "  One,\n"
1340            "#if /* test */ 0 || 1\n"
1341            "Two,\n"
1342            "Three,\n"
1343            "#endif\n"
1344            "  Four\n"
1345            "};",
1346            format("enum I {\n"
1347                   "One,\n"
1348                   "#if /* test */ 0 || 1\n"
1349                   "Two,\n"
1350                   "Three,\n"
1351                   "#endif\n"
1352                   "Four\n"
1353                   "};"));
1354  EXPECT_EQ("enum J {\n"
1355            "  One,\n"
1356            "#if 0\n"
1357            "#if 0\n"
1358            "Two,\n"
1359            "#else\n"
1360            "Three,\n"
1361            "#endif\n"
1362            "Four,\n"
1363            "#endif\n"
1364            "  Five\n"
1365            "};",
1366            format("enum J {\n"
1367                   "One,\n"
1368                   "#if 0\n"
1369                   "#if 0\n"
1370                   "Two,\n"
1371                   "#else\n"
1372                   "Three,\n"
1373                   "#endif\n"
1374                   "Four,\n"
1375                   "#endif\n"
1376                   "Five\n"
1377                   "};"));
1378
1379}
1380
1381//===----------------------------------------------------------------------===//
1382// Tests for classes, namespaces, etc.
1383//===----------------------------------------------------------------------===//
1384
1385TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1386  verifyFormat("class A {};");
1387}
1388
1389TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1390  verifyFormat("class A {\n"
1391               "public:\n"
1392               "public: // comment\n"
1393               "protected:\n"
1394               "private:\n"
1395               "  void f() {}\n"
1396               "};");
1397  verifyGoogleFormat("class A {\n"
1398                     " public:\n"
1399                     " protected:\n"
1400                     " private:\n"
1401                     "  void f() {}\n"
1402                     "};");
1403}
1404
1405TEST_F(FormatTest, SeparatesLogicalBlocks) {
1406  EXPECT_EQ("class A {\n"
1407            "public:\n"
1408            "  void f();\n"
1409            "\n"
1410            "private:\n"
1411            "  void g() {}\n"
1412            "  // test\n"
1413            "protected:\n"
1414            "  int h;\n"
1415            "};",
1416            format("class A {\n"
1417                   "public:\n"
1418                   "void f();\n"
1419                   "private:\n"
1420                   "void g() {}\n"
1421                   "// test\n"
1422                   "protected:\n"
1423                   "int h;\n"
1424                   "};"));
1425}
1426
1427TEST_F(FormatTest, FormatsClasses) {
1428  verifyFormat("class A : public B {};");
1429  verifyFormat("class A : public ::B {};");
1430
1431  verifyFormat(
1432      "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1433      "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1434  verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
1435               "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1436               "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1437  verifyFormat(
1438      "class A : public B, public C, public D, public E, public F {};");
1439  verifyFormat("class AAAAAAAAAAAA : public B,\n"
1440               "                     public C,\n"
1441               "                     public D,\n"
1442               "                     public E,\n"
1443               "                     public F,\n"
1444               "                     public G {};");
1445
1446  verifyFormat("class\n"
1447               "    ReallyReallyLongClassName {\n};",
1448               getLLVMStyleWithColumns(32));
1449}
1450
1451TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
1452  verifyFormat("class A {\n} a, b;");
1453  verifyFormat("struct A {\n} a, b;");
1454  verifyFormat("union A {\n} a;");
1455}
1456
1457TEST_F(FormatTest, FormatsEnum) {
1458  verifyFormat("enum {\n"
1459               "  Zero,\n"
1460               "  One = 1,\n"
1461               "  Two = One + 1,\n"
1462               "  Three = (One + Two),\n"
1463               "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1464               "  Five = (One, Two, Three, Four, 5)\n"
1465               "};");
1466  verifyFormat("enum Enum {};");
1467  verifyFormat("enum {};");
1468  verifyFormat("enum X E {\n} d;");
1469  verifyFormat("enum __attribute__((...)) E {\n} d;");
1470  verifyFormat("enum __declspec__((...)) E {\n} d;");
1471  verifyFormat("enum X f() {\n  a();\n  return 42;\n}");
1472}
1473
1474TEST_F(FormatTest, FormatsBitfields) {
1475  verifyFormat("struct Bitfields {\n"
1476               "  unsigned sClass : 8;\n"
1477               "  unsigned ValueKind : 2;\n"
1478               "};");
1479}
1480
1481TEST_F(FormatTest, FormatsNamespaces) {
1482  verifyFormat("namespace some_namespace {\n"
1483               "class A {};\n"
1484               "void f() { f(); }\n"
1485               "}");
1486  verifyFormat("namespace {\n"
1487               "class A {};\n"
1488               "void f() { f(); }\n"
1489               "}");
1490  verifyFormat("inline namespace X {\n"
1491               "class A {};\n"
1492               "void f() { f(); }\n"
1493               "}");
1494  verifyFormat("using namespace some_namespace;\n"
1495               "class A {};\n"
1496               "void f() { f(); }");
1497
1498  // This code is more common than we thought; if we
1499  // layout this correctly the semicolon will go into
1500  // its own line, which is undesireable.
1501  verifyFormat("namespace {};");
1502  verifyFormat("namespace {\n"
1503               "class A {};\n"
1504               "};");
1505
1506  verifyFormat("namespace {\n"
1507               "int SomeVariable = 0; // comment\n"
1508               "} // namespace");
1509  EXPECT_EQ("#ifndef HEADER_GUARD\n"
1510            "#define HEADER_GUARD\n"
1511            "namespace my_namespace {\n"
1512            "int i;\n"
1513            "} // my_namespace\n"
1514            "#endif // HEADER_GUARD",
1515            format("#ifndef HEADER_GUARD\n"
1516                   " #define HEADER_GUARD\n"
1517                   "   namespace my_namespace {\n"
1518                   "int i;\n"
1519                   "}    // my_namespace\n"
1520                   "#endif    // HEADER_GUARD"));
1521}
1522
1523TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
1524
1525TEST_F(FormatTest, FormatsInlineASM) {
1526  verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
1527  verifyFormat(
1528      "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
1529      "    \"cpuid\\n\\t\"\n"
1530      "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
1531      "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
1532      "    : \"a\"(value));");
1533}
1534
1535TEST_F(FormatTest, FormatTryCatch) {
1536  // FIXME: Handle try-catch explicitly in the UnwrappedLineParser, then we'll
1537  // also not create single-line-blocks.
1538  verifyFormat("try {\n"
1539               "  throw a * b;\n"
1540               "}\n"
1541               "catch (int a) {\n"
1542               "  // Do nothing.\n"
1543               "}\n"
1544               "catch (...) {\n"
1545               "  exit(42);\n"
1546               "}");
1547
1548  // Function-level try statements.
1549  verifyFormat("int f() try { return 4; }\n"
1550               "catch (...) {\n"
1551               "  return 5;\n"
1552               "}");
1553  verifyFormat("class A {\n"
1554               "  int a;\n"
1555               "  A() try : a(0) {}\n"
1556               "  catch (...) {\n"
1557               "    throw;\n"
1558               "  }\n"
1559               "};\n");
1560}
1561
1562TEST_F(FormatTest, FormatObjCTryCatch) {
1563  verifyFormat("@try {\n"
1564               "  f();\n"
1565               "}\n"
1566               "@catch (NSException e) {\n"
1567               "  @throw;\n"
1568               "}\n"
1569               "@finally {\n"
1570               "  exit(42);\n"
1571               "}");
1572}
1573
1574TEST_F(FormatTest, StaticInitializers) {
1575  verifyFormat("static SomeClass SC = { 1, 'a' };");
1576
1577  verifyFormat(
1578      "static SomeClass WithALoooooooooooooooooooongName = {\n"
1579      "  100000000, \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
1580      "};");
1581
1582  verifyFormat(
1583      "static SomeClass = { a, b, c, d, e, f, g, h, i, j,\n"
1584      "                     looooooooooooooooooooooooooooooooooongname,\n"
1585      "                     looooooooooooooooooooooooooooooong };");
1586  // Allow bin-packing in static initializers as this would often lead to
1587  // terrible results, e.g.:
1588  verifyGoogleFormat(
1589      "static SomeClass = {a, b, c, d, e, f, g, h, i, j,\n"
1590      "                    looooooooooooooooooooooooooooooooooongname,\n"
1591      "                    looooooooooooooooooooooooooooooong};");
1592  // Here, everything other than the "}" would fit on a line.
1593  verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
1594               "  100000000000000000000000\n"
1595               "};");
1596  EXPECT_EQ("S s = { a, b };", format("S s = {\n"
1597                                      "  a,\n"
1598                                      "\n"
1599                                      "  b\n"
1600                                      "};"));
1601
1602  // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
1603  // line. However, the formatting looks a bit off and this probably doesn't
1604  // happen often in practice.
1605  verifyFormat("static int Variable[1] = {\n"
1606               "  { 1000000000000000000000000000000000000 }\n"
1607               "};",
1608               getLLVMStyleWithColumns(40));
1609}
1610
1611TEST_F(FormatTest, DesignatedInitializers) {
1612  verifyFormat("const struct A a = { .a = 1, .b = 2 };");
1613  verifyFormat("const struct A a = { .aaaaaaaaaa = 1,\n"
1614               "                     .bbbbbbbbbb = 2,\n"
1615               "                     .cccccccccc = 3,\n"
1616               "                     .dddddddddd = 4,\n"
1617               "                     .eeeeeeeeee = 5 };");
1618  verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
1619               "  .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
1620               "  .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
1621               "  .ccccccccccccccccccccccccccc = 3,\n"
1622               "  .ddddddddddddddddddddddddddd = 4,\n"
1623               "  .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5\n"
1624               "};");
1625
1626  verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
1627}
1628
1629TEST_F(FormatTest, NestedStaticInitializers) {
1630  verifyFormat("static A x = { { {} } };\n");
1631  verifyFormat("static A x = { { { init1, init2, init3, init4 },\n"
1632               "                 { init1, init2, init3, init4 } } };");
1633
1634  verifyFormat("somes Status::global_reps[3] = {\n"
1635               "  { kGlobalRef, OK_CODE, NULL, NULL, NULL },\n"
1636               "  { kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL },\n"
1637               "  { kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL }\n"
1638               "};");
1639  verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
1640                     "  {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
1641                     "  {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
1642                     "  {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}\n"
1643                     "};");
1644  verifyFormat(
1645      "CGRect cg_rect = { { rect.fLeft, rect.fTop },\n"
1646      "                   { rect.fRight - rect.fLeft, rect.fBottom - rect.fTop"
1647      " } };");
1648
1649  verifyFormat(
1650      "SomeArrayOfSomeType a = { { { 1, 2, 3 }, { 1, 2, 3 },\n"
1651      "                            { 111111111111111111111111111111,\n"
1652      "                              222222222222222222222222222222,\n"
1653      "                              333333333333333333333333333333 },\n"
1654      "                            { 1, 2, 3 }, { 1, 2, 3 } } };");
1655  verifyFormat(
1656      "SomeArrayOfSomeType a = { { { 1, 2, 3 } }, { { 1, 2, 3 } },\n"
1657      "                          { { 111111111111111111111111111111,\n"
1658      "                              222222222222222222222222222222,\n"
1659      "                              333333333333333333333333333333 } },\n"
1660      "                          { { 1, 2, 3 } }, { { 1, 2, 3 } } };");
1661  verifyGoogleFormat(
1662      "SomeArrayOfSomeType a = {{{1, 2, 3}}, {{1, 2, 3}},\n"
1663      "                         {{111111111111111111111111111111,\n"
1664      "                           222222222222222222222222222222,\n"
1665      "                           333333333333333333333333333333}},\n"
1666      "                         {{1, 2, 3}}, {{1, 2, 3}}};");
1667
1668  // FIXME: We might at some point want to handle this similar to parameter
1669  // lists, where we have an option to put each on a single line.
1670  verifyFormat(
1671      "struct {\n"
1672      "  unsigned bit;\n"
1673      "  const char *const name;\n"
1674      "} kBitsToOs[] = { { kOsMac, \"Mac\" }, { kOsWin, \"Windows\" },\n"
1675      "                  { kOsLinux, \"Linux\" }, { kOsCrOS, \"Chrome OS\" } };");
1676}
1677
1678TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
1679  verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
1680               "                      \\\n"
1681               "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
1682}
1683
1684TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
1685  verifyFormat(
1686      "virtual void write(ELFWriter *writerrr,\n"
1687      "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
1688}
1689
1690TEST_F(FormatTest, LayoutUnknownPPDirective) {
1691  EXPECT_EQ("#123 \"A string literal\"",
1692            format("   #     123    \"A string literal\""));
1693  EXPECT_EQ("#;", format("#;"));
1694  verifyFormat("#\n;\n;\n;");
1695}
1696
1697TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
1698  EXPECT_EQ("#line 42 \"test\"\n",
1699            format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
1700  EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
1701                                    getLLVMStyleWithColumns(12)));
1702}
1703
1704TEST_F(FormatTest, EndOfFileEndsPPDirective) {
1705  EXPECT_EQ("#line 42 \"test\"",
1706            format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
1707  EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
1708}
1709
1710TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
1711  verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
1712  verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
1713  verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
1714  // FIXME: We never break before the macro name.
1715  verifyFormat("#define AA(\\\n    B)", getLLVMStyleWithColumns(12));
1716
1717  verifyFormat("#define A A\n#define A A");
1718  verifyFormat("#define A(X) A\n#define A A");
1719
1720  verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
1721  verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
1722}
1723
1724TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
1725  EXPECT_EQ("// somecomment\n"
1726            "#include \"a.h\"\n"
1727            "#define A(  \\\n"
1728            "    A, B)\n"
1729            "#include \"b.h\"\n"
1730            "// somecomment\n",
1731            format("  // somecomment\n"
1732                   "  #include \"a.h\"\n"
1733                   "#define A(A,\\\n"
1734                   "    B)\n"
1735                   "    #include \"b.h\"\n"
1736                   " // somecomment\n",
1737                   getLLVMStyleWithColumns(13)));
1738}
1739
1740TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
1741
1742TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
1743  EXPECT_EQ("#define A    \\\n"
1744            "  c;         \\\n"
1745            "  e;\n"
1746            "f;",
1747            format("#define A c; e;\n"
1748                   "f;",
1749                   getLLVMStyleWithColumns(14)));
1750}
1751
1752TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
1753
1754TEST_F(FormatTest, AlwaysFormatsEntireMacroDefinitions) {
1755  EXPECT_EQ("int  i;\n"
1756            "#define A \\\n"
1757            "  int i;  \\\n"
1758            "  int j\n"
1759            "int  k;",
1760            format("int  i;\n"
1761                   "#define A  \\\n"
1762                   " int   i    ;  \\\n"
1763                   " int   j\n"
1764                   "int  k;",
1765                   8, 0, getGoogleStyle())); // 8: position of "#define".
1766  EXPECT_EQ("int  i;\n"
1767            "#define A \\\n"
1768            "  int i;  \\\n"
1769            "  int j\n"
1770            "int  k;",
1771            format("int  i;\n"
1772                   "#define A  \\\n"
1773                   " int   i    ;  \\\n"
1774                   " int   j\n"
1775                   "int  k;",
1776                   45, 0, getGoogleStyle())); // 45: position of "j".
1777}
1778
1779TEST_F(FormatTest, MacroDefinitionInsideStatement) {
1780  EXPECT_EQ("int x,\n"
1781            "#define A\n"
1782            "    y;",
1783            format("int x,\n#define A\ny;"));
1784}
1785
1786TEST_F(FormatTest, HashInMacroDefinition) {
1787  verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
1788  verifyFormat("#define A \\\n"
1789               "  {       \\\n"
1790               "    f(#c);\\\n"
1791               "  }",
1792               getLLVMStyleWithColumns(11));
1793
1794  verifyFormat("#define A(X)         \\\n"
1795               "  void function##X()",
1796               getLLVMStyleWithColumns(22));
1797
1798  verifyFormat("#define A(a, b, c)   \\\n"
1799               "  void a##b##c()",
1800               getLLVMStyleWithColumns(22));
1801
1802  verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
1803}
1804
1805TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
1806  verifyFormat("#define A (1)");
1807}
1808
1809TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
1810  EXPECT_EQ("#define A b;", format("#define A \\\n"
1811                                   "          \\\n"
1812                                   "  b;",
1813                                   getLLVMStyleWithColumns(25)));
1814  EXPECT_EQ("#define A \\\n"
1815            "          \\\n"
1816            "  a;      \\\n"
1817            "  b;",
1818            format("#define A \\\n"
1819                   "          \\\n"
1820                   "  a;      \\\n"
1821                   "  b;",
1822                   getLLVMStyleWithColumns(11)));
1823  EXPECT_EQ("#define A \\\n"
1824            "  a;      \\\n"
1825            "          \\\n"
1826            "  b;",
1827            format("#define A \\\n"
1828                   "  a;      \\\n"
1829                   "          \\\n"
1830                   "  b;",
1831                   getLLVMStyleWithColumns(11)));
1832}
1833
1834TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
1835  verifyFormat("#define A :");
1836  verifyFormat("#define SOMECASES  \\\n"
1837               "  case 1:          \\\n"
1838               "  case 2\n",
1839               getLLVMStyleWithColumns(20));
1840  verifyFormat("#define A template <typename T>");
1841  verifyFormat("#define STR(x) #x\n"
1842               "f(STR(this_is_a_string_literal{));");
1843}
1844
1845TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
1846  verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
1847  EXPECT_EQ("class A : public QObject {\n"
1848            "  Q_OBJECT\n"
1849            "\n"
1850            "  A() {}\n"
1851            "};",
1852            format("class A  :  public QObject {\n"
1853                   "     Q_OBJECT\n"
1854                   "\n"
1855                   "  A() {\n}\n"
1856                   "}  ;"));
1857  EXPECT_EQ("SOME_MACRO\n"
1858            "namespace {\n"
1859            "void f();\n"
1860            "}",
1861            format("SOME_MACRO\n"
1862                   "  namespace    {\n"
1863                   "void   f(  );\n"
1864                   "}"));
1865  // Only if the identifier contains at least 5 characters.
1866  EXPECT_EQ("HTTP f();",
1867            format("HTTP\nf();"));
1868  EXPECT_EQ("MACRO\nf();",
1869            format("MACRO\nf();"));
1870  // Only if everything is upper case.
1871  EXPECT_EQ("class A : public QObject {\n"
1872            "  Q_Object A() {}\n"
1873            "};",
1874            format("class A  :  public QObject {\n"
1875                   "     Q_Object\n"
1876                   "\n"
1877                   "  A() {\n}\n"
1878                   "}  ;"));
1879}
1880
1881TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
1882  EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
1883            "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
1884            "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
1885            "class X {};\n"
1886            "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
1887            "int *createScopDetectionPass() { return 0; }",
1888            format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
1889                   "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
1890                   "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
1891                   "  class X {};\n"
1892                   "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
1893                   "  int *createScopDetectionPass() { return 0; }"));
1894  // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
1895  // braces, so that inner block is indented one level more.
1896  EXPECT_EQ("int q() {\n"
1897            "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
1898            "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
1899            "  IPC_END_MESSAGE_MAP()\n"
1900            "}",
1901            format("int q() {\n"
1902                   "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
1903                   "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
1904                   "  IPC_END_MESSAGE_MAP()\n"
1905                   "}"));
1906  EXPECT_EQ("int q() {\n"
1907            "  f(x);\n"
1908            "  f(x) {}\n"
1909            "  f(x)->g();\n"
1910            "  f(x)->*g();\n"
1911            "  f(x).g();\n"
1912            "  f(x) = x;\n"
1913            "  f(x) += x;\n"
1914            "  f(x) -= x;\n"
1915            "  f(x) *= x;\n"
1916            "  f(x) /= x;\n"
1917            "  f(x) %= x;\n"
1918            "  f(x) &= x;\n"
1919            "  f(x) |= x;\n"
1920            "  f(x) ^= x;\n"
1921            "  f(x) >>= x;\n"
1922            "  f(x) <<= x;\n"
1923            "  f(x)[y].z();\n"
1924            "  LOG(INFO) << x;\n"
1925            "  ifstream(x) >> x;\n"
1926            "}\n",
1927            format("int q() {\n"
1928                   "  f(x)\n;\n"
1929                   "  f(x)\n {}\n"
1930                   "  f(x)\n->g();\n"
1931                   "  f(x)\n->*g();\n"
1932                   "  f(x)\n.g();\n"
1933                   "  f(x)\n = x;\n"
1934                   "  f(x)\n += x;\n"
1935                   "  f(x)\n -= x;\n"
1936                   "  f(x)\n *= x;\n"
1937                   "  f(x)\n /= x;\n"
1938                   "  f(x)\n %= x;\n"
1939                   "  f(x)\n &= x;\n"
1940                   "  f(x)\n |= x;\n"
1941                   "  f(x)\n ^= x;\n"
1942                   "  f(x)\n >>= x;\n"
1943                   "  f(x)\n <<= x;\n"
1944                   "  f(x)\n[y].z();\n"
1945                   "  LOG(INFO)\n << x;\n"
1946                   "  ifstream(x)\n >> x;\n"
1947                   "}\n"));
1948  EXPECT_EQ("int q() {\n"
1949            "  f(x)\n"
1950            "  if (1) {\n"
1951            "  }\n"
1952            "  f(x)\n"
1953            "  while (1) {\n"
1954            "  }\n"
1955            "  f(x)\n"
1956            "  g(x);\n"
1957            "  f(x)\n"
1958            "  try {\n"
1959            "    q();\n"
1960            "  }\n"
1961            "  catch (...) {\n"
1962            "  }\n"
1963            "}\n",
1964            format("int q() {\n"
1965                   "f(x)\n"
1966                   "if (1) {}\n"
1967                   "f(x)\n"
1968                   "while (1) {}\n"
1969                   "f(x)\n"
1970                   "g(x);\n"
1971                   "f(x)\n"
1972                   "try { q(); } catch (...) {}\n"
1973                   "}\n"));
1974  EXPECT_EQ("class A {\n"
1975            "  A() : t(0) {}\n"
1976            "  A(X x)\n" // FIXME: function-level try blocks are broken.
1977            "  try : t(0) {\n"
1978            "  }\n"
1979            "  catch (...) {\n"
1980            "  }\n"
1981            "};",
1982            format("class A {\n"
1983                   "  A()\n : t(0) {}\n"
1984                   "  A(X x)\n"
1985                   "  try : t(0) {} catch (...) {}\n"
1986                   "};"));
1987}
1988
1989TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
1990  verifyFormat("#define A \\\n"
1991               "  f({     \\\n"
1992               "    g();  \\\n"
1993               "  });", getLLVMStyleWithColumns(11));
1994}
1995
1996TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
1997  EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
1998}
1999
2000TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
2001  verifyFormat("{\n  { a #c; }\n}");
2002}
2003
2004TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
2005  EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
2006            format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
2007  EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
2008            format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
2009}
2010
2011TEST_F(FormatTest, EscapedNewlineAtStartOfToken) {
2012  EXPECT_EQ(
2013      "#define A \\\n  int i;  \\\n  int j;",
2014      format("#define A \\\nint i;\\\n  int j;", getLLVMStyleWithColumns(11)));
2015  EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
2016}
2017
2018TEST_F(FormatTest, NoEscapedNewlineHandlingInBlockComments) {
2019  EXPECT_EQ("/* \\  \\  \\\n*/", format("\\\n/* \\  \\  \\\n*/"));
2020}
2021
2022TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
2023  verifyFormat("#define A \\\n"
2024               "  int v(  \\\n"
2025               "      a); \\\n"
2026               "  int i;",
2027               getLLVMStyleWithColumns(11));
2028}
2029
2030TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
2031  EXPECT_EQ(
2032      "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
2033      "                      \\\n"
2034      "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
2035      "\n"
2036      "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
2037      "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
2038      format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
2039             "\\\n"
2040             "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
2041             "  \n"
2042             "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
2043             "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
2044}
2045
2046TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
2047  EXPECT_EQ("int\n"
2048            "#define A\n"
2049            "    a;",
2050            format("int\n#define A\na;", getGoogleStyle()));
2051  verifyFormat("functionCallTo(\n"
2052               "    someOtherFunction(\n"
2053               "        withSomeParameters, whichInSequence,\n"
2054               "        areLongerThanALine(andAnotherCall,\n"
2055               "#define A B\n"
2056               "                           withMoreParamters,\n"
2057               "                           whichStronglyInfluenceTheLayout),\n"
2058               "        andMoreParameters),\n"
2059               "    trailing);",
2060               getLLVMStyleWithColumns(69));
2061}
2062
2063TEST_F(FormatTest, LayoutBlockInsideParens) {
2064  EXPECT_EQ("functionCall({\n"
2065            "  int i;\n"
2066            "});",
2067            format(" functionCall ( {int i;} );"));
2068
2069  // FIXME: This is bad, find a better and more generic solution.
2070  EXPECT_EQ("functionCall({\n"
2071            "  int i;\n"
2072            "},\n"
2073            "             aaaa, bbbb, cccc);",
2074            format(" functionCall ( {int i;},  aaaa,   bbbb, cccc);"));
2075  verifyFormat(
2076      "Aaa({\n"
2077      "  int i;\n"
2078      "},\n"
2079      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
2080      "                                     ccccccccccccccccc));");
2081}
2082
2083TEST_F(FormatTest, LayoutBlockInsideStatement) {
2084  EXPECT_EQ("SOME_MACRO { int i; }\n"
2085            "int i;",
2086            format("  SOME_MACRO  {int i;}  int i;"));
2087}
2088
2089TEST_F(FormatTest, LayoutNestedBlocks) {
2090  verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
2091               "  struct s {\n"
2092               "    int i;\n"
2093               "  };\n"
2094               "  s kBitsToOs[] = { { 10 } };\n"
2095               "  for (int i = 0; i < 10; ++i)\n"
2096               "    return;\n"
2097               "}");
2098}
2099
2100TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
2101  EXPECT_EQ("{}", format("{}"));
2102  verifyFormat("enum E {};");
2103  verifyFormat("enum E {}");
2104}
2105
2106//===----------------------------------------------------------------------===//
2107// Line break tests.
2108//===----------------------------------------------------------------------===//
2109
2110TEST_F(FormatTest, FormatsAwesomeMethodCall) {
2111  verifyFormat(
2112      "SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
2113      "                       parameter, parameter, parameter)),\n"
2114      "                   SecondLongCall(parameter));");
2115}
2116
2117TEST_F(FormatTest, PreventConfusingIndents) {
2118  verifyFormat(
2119      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2120      "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
2121      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2122      "    aaaaaaaaaaaaaaaaaaaaaaaa);");
2123  verifyFormat(
2124      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2125      "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
2126      "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
2127      "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
2128  verifyFormat(
2129      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
2130      "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
2131      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
2132      "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
2133  verifyFormat("int a = bbbb && ccc && fffff(\n"
2134               "#define A Just forcing a new line\n"
2135               "                           ddd);");
2136}
2137
2138TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
2139  verifyFormat(
2140      "bool aaaaaaa =\n"
2141      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
2142      "    bbbbbbbb();");
2143  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
2144               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
2145               "    ccccccccc == ddddddddddd;");
2146
2147  verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
2148               "                 aaaaaa) &&\n"
2149               "         bbbbbb && cccccc;");
2150  verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
2151               "                 aaaaaa) >>\n"
2152               "         bbbbbb;");
2153  verifyFormat("Whitespaces.addUntouchableComment(\n"
2154               "    SourceMgr.getSpellingColumnNumber(\n"
2155               "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
2156               "    1);");
2157
2158  verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2159               "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
2160               "    cccccc) {\n}");
2161
2162  // If the LHS of a comparison is not a binary expression itself, the
2163  // additional linebreak confuses many people.
2164  verifyFormat(
2165      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2166      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
2167      "}");
2168  verifyFormat(
2169      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2170      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
2171      "}");
2172  // Even explicit parentheses stress the precedence enough to make the
2173  // additional break unnecessary.
2174  verifyFormat(
2175      "if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2176      "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
2177      "}");
2178  // This cases is borderline, but with the indentation it is still readable.
2179  verifyFormat(
2180      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2181      "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2182      "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2183      "}",
2184      getLLVMStyleWithColumns(75));
2185
2186  // If the LHS is a binary expression, we should still use the additional break
2187  // as otherwise the formatting hides the operator precedence.
2188  verifyFormat(
2189      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2190      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2191      "    5) {\n"
2192      "}");
2193
2194  FormatStyle OnePerLine = getLLVMStyle();
2195  OnePerLine.BinPackParameters = false;
2196  verifyFormat(
2197      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2198      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2199      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
2200      OnePerLine);
2201}
2202
2203TEST_F(FormatTest, ExpressionIndentation) {
2204  verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2205               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2206               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2207               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2208               "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
2209               "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
2210               "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2211               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
2212               "                 ccccccccccccccccccccccccccccccccccccccccc;");
2213  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2214               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2215               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2216               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2217  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2218               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2219               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2220               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2221  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2222               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2223               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2224               "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2225  verifyFormat("if () {\n"
2226               "} else if (aaaaa && bbbbb > // break\n"
2227               "                        ccccc) {\n"
2228               "}");
2229
2230  // Presence of a trailing comment used to change indentation of b.
2231  verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
2232               "       b;\n"
2233               "return aaaaaaaaaaaaaaaaaaa +\n"
2234               "       b; //",
2235               getLLVMStyleWithColumns(30));
2236}
2237
2238TEST_F(FormatTest, ConstructorInitializers) {
2239  verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
2240  verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
2241               getLLVMStyleWithColumns(45));
2242  verifyFormat("Constructor()\n"
2243               "    : Inttializer(FitsOnTheLine) {}",
2244               getLLVMStyleWithColumns(44));
2245  verifyFormat("Constructor()\n"
2246               "    : Inttializer(FitsOnTheLine) {}",
2247               getLLVMStyleWithColumns(43));
2248
2249  verifyFormat(
2250      "SomeClass::Constructor()\n"
2251      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
2252
2253  verifyFormat(
2254      "SomeClass::Constructor()\n"
2255      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2256      "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
2257  verifyFormat(
2258      "SomeClass::Constructor()\n"
2259      "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2260      "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
2261
2262  verifyFormat("Constructor()\n"
2263               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2264               "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2265               "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2266               "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
2267
2268  verifyFormat("Constructor()\n"
2269               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2270               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2271
2272  verifyFormat("Constructor(int Parameter = 0)\n"
2273               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
2274               "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
2275
2276  // Here a line could be saved by splitting the second initializer onto two
2277  // lines, but that is not desireable.
2278  verifyFormat("Constructor()\n"
2279               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
2280               "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
2281               "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2282
2283  FormatStyle OnePerLine = getLLVMStyle();
2284  OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
2285  verifyFormat("SomeClass::Constructor()\n"
2286               "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2287               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2288               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
2289               OnePerLine);
2290  verifyFormat("SomeClass::Constructor()\n"
2291               "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
2292               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2293               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
2294               OnePerLine);
2295  verifyFormat("MyClass::MyClass(int var)\n"
2296               "    : some_var_(var),            // 4 space indent\n"
2297               "      some_other_var_(var + 1) { // lined up\n"
2298               "}",
2299               OnePerLine);
2300  verifyFormat("Constructor()\n"
2301               "    : aaaaa(aaaaaa),\n"
2302               "      aaaaa(aaaaaa),\n"
2303               "      aaaaa(aaaaaa),\n"
2304               "      aaaaa(aaaaaa),\n"
2305               "      aaaaa(aaaaaa) {}",
2306               OnePerLine);
2307  verifyFormat("Constructor()\n"
2308               "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
2309               "            aaaaaaaaaaaaaaaaaaaaaa) {}",
2310               OnePerLine);
2311}
2312
2313TEST_F(FormatTest, MemoizationTests) {
2314  // This breaks if the memoization lookup does not take \c Indent and
2315  // \c LastSpace into account.
2316  verifyFormat(
2317      "extern CFRunLoopTimerRef\n"
2318      "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
2319      "                     CFTimeInterval interval, CFOptionFlags flags,\n"
2320      "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
2321      "                     CFRunLoopTimerContext *context) {}");
2322
2323  // Deep nesting somewhat works around our memoization.
2324  verifyFormat(
2325      "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2326      "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2327      "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2328      "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2329      "                aaaaa())))))))))))))))))))))))))))))))))))))));",
2330      getLLVMStyleWithColumns(65));
2331  verifyFormat(
2332      "aaaaa(\n"
2333      "    aaaaa,\n"
2334      "    aaaaa(\n"
2335      "        aaaaa,\n"
2336      "        aaaaa(\n"
2337      "            aaaaa,\n"
2338      "            aaaaa(\n"
2339      "                aaaaa,\n"
2340      "                aaaaa(\n"
2341      "                    aaaaa,\n"
2342      "                    aaaaa(\n"
2343      "                        aaaaa,\n"
2344      "                        aaaaa(\n"
2345      "                            aaaaa,\n"
2346      "                            aaaaa(\n"
2347      "                                aaaaa,\n"
2348      "                                aaaaa(\n"
2349      "                                    aaaaa,\n"
2350      "                                    aaaaa(\n"
2351      "                                        aaaaa,\n"
2352      "                                        aaaaa(\n"
2353      "                                            aaaaa,\n"
2354      "                                            aaaaa(\n"
2355      "                                                aaaaa,\n"
2356      "                                                aaaaa))))))))))));",
2357      getLLVMStyleWithColumns(65));
2358  verifyFormat(
2359      "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"
2360      "                                  a),\n"
2361      "                                a),\n"
2362      "                              a),\n"
2363      "                            a),\n"
2364      "                          a),\n"
2365      "                        a),\n"
2366      "                      a),\n"
2367      "                    a),\n"
2368      "                  a),\n"
2369      "                a),\n"
2370      "              a),\n"
2371      "            a),\n"
2372      "          a),\n"
2373      "        a),\n"
2374      "      a),\n"
2375      "    a),\n"
2376      "  a)",
2377      getLLVMStyleWithColumns(65));
2378
2379  // This test takes VERY long when memoization is broken.
2380  FormatStyle OnePerLine = getLLVMStyle();
2381  OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
2382  OnePerLine.BinPackParameters = false;
2383  std::string input = "Constructor()\n"
2384                      "    : aaaa(a,\n";
2385  for (unsigned i = 0, e = 80; i != e; ++i) {
2386    input += "           a,\n";
2387  }
2388  input += "           a) {}";
2389  verifyFormat(input, OnePerLine);
2390}
2391
2392TEST_F(FormatTest, BreaksAsHighAsPossible) {
2393  verifyFormat(
2394      "void f() {\n"
2395      "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
2396      "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
2397      "    f();\n"
2398      "}");
2399  verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
2400               "    Intervals[i - 1].getRange().getLast()) {\n}");
2401}
2402
2403TEST_F(FormatTest, BreaksFunctionDeclarations) {
2404  // Principially, we break function declarations in a certain order:
2405  // 1) break amongst arguments.
2406  verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
2407               "                              Cccccccccccccc cccccccccccccc);");
2408
2409  // 2) break after return type.
2410  verifyFormat(
2411      "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2412      "    bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
2413      getGoogleStyle());
2414
2415  // 3) break after (.
2416  verifyFormat(
2417      "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
2418      "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
2419      getGoogleStyle());
2420
2421  // 4) break before after nested name specifiers.
2422  verifyFormat(
2423      "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2424      "    SomeClasssssssssssssssssssssssssssssssssssssss::\n"
2425      "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
2426      getGoogleStyle());
2427
2428  // However, there are exceptions, if a sufficient amount of lines can be
2429  // saved.
2430  // FIXME: The precise cut-offs wrt. the number of saved lines might need some
2431  // more adjusting.
2432  verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
2433               "                                  Cccccccccccccc cccccccccc,\n"
2434               "                                  Cccccccccccccc cccccccccc,\n"
2435               "                                  Cccccccccccccc cccccccccc,\n"
2436               "                                  Cccccccccccccc cccccccccc);");
2437  verifyFormat(
2438      "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2439      "    bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2440      "                Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2441      "                Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
2442      getGoogleStyle());
2443  verifyFormat(
2444      "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
2445      "                                          Cccccccccccccc cccccccccc,\n"
2446      "                                          Cccccccccccccc cccccccccc,\n"
2447      "                                          Cccccccccccccc cccccccccc,\n"
2448      "                                          Cccccccccccccc cccccccccc,\n"
2449      "                                          Cccccccccccccc cccccccccc,\n"
2450      "                                          Cccccccccccccc cccccccccc);");
2451  verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
2452               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2453               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2454               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2455               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
2456
2457  // Break after multi-line parameters.
2458  verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2459               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2460               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2461               "    bbbb bbbb);");
2462
2463  // Treat overloaded operators like other functions.
2464  verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
2465               "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
2466  verifyGoogleFormat(
2467      "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
2468      "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
2469}
2470
2471TEST_F(FormatTest, TrailingReturnType) {
2472  verifyFormat("auto foo() -> int;\n");
2473  verifyFormat("struct S {\n"
2474               "  auto bar() const -> int;\n"
2475               "};");
2476  verifyFormat("template <size_t Order, typename T>\n"
2477               "auto load_img(const std::string &filename)\n"
2478               "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
2479
2480  // Not trailing return types.
2481  verifyFormat("void f() { auto a = b->c(); }");
2482}
2483
2484TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
2485  // Avoid breaking before trailing 'const'.
2486  verifyFormat("void someLongFunction(\n"
2487               "    int someLongParameter) const {}",
2488               getLLVMStyleWithColumns(46));
2489  FormatStyle Style = getGoogleStyle();
2490  Style.ColumnLimit = 47;
2491  verifyFormat("void\n"
2492               "someLongFunction(int someLongParameter) const {\n}",
2493               getLLVMStyleWithColumns(47));
2494  verifyFormat("void someLongFunction(\n"
2495               "    int someLongParameter) const {}",
2496               Style);
2497  verifyFormat("LoooooongReturnType\n"
2498               "someLoooooooongFunction() const {}",
2499               getLLVMStyleWithColumns(47));
2500  verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
2501               "    const {}",
2502               Style);
2503
2504  // Avoid breaking before other trailing annotations, if they are not
2505  // function-like.
2506  verifyFormat("void SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2507               "                  aaaaaaaaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
2508
2509  // Breaking before function-like trailing annotations is fine to keep them
2510  // close to their arguments.
2511  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2512               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
2513  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
2514               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
2515  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
2516               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
2517
2518  verifyFormat(
2519      "void aaaaaaaaaaaaaaaaaa()\n"
2520      "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
2521      "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
2522  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2523               "    __attribute__((unused));");
2524  verifyFormat(
2525      "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2526      "    GUARDED_BY(aaaaaaaaaaaa);",
2527      getGoogleStyle());
2528  verifyFormat(
2529      "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2530      "    GUARDED_BY(aaaaaaaaaaaa);",
2531      getGoogleStyle());
2532}
2533
2534TEST_F(FormatTest, BreaksDesireably) {
2535  verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
2536               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
2537               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
2538  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2539               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2540               "}");
2541
2542  verifyFormat(
2543      "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2544      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2545
2546  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2547               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2548               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2549
2550  verifyFormat(
2551      "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2552      "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
2553      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2554      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
2555
2556  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2557               "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2558
2559  verifyFormat(
2560      "void f() {\n"
2561      "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
2562      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2563      "}");
2564  verifyFormat(
2565      "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2566      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2567  verifyFormat(
2568      "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2569      "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2570  verifyFormat(
2571      "aaaaaaaaaaaaaaaaa(\n"
2572      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2573      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2574
2575  // This test case breaks on an incorrect memoization, i.e. an optimization not
2576  // taking into account the StopAt value.
2577  verifyFormat(
2578      "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2579      "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2580      "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2581      "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2582
2583  verifyFormat("{\n  {\n    {\n"
2584               "      Annotation.SpaceRequiredBefore =\n"
2585               "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
2586               "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
2587               "    }\n  }\n}");
2588
2589  // Break on an outer level if there was a break on an inner level.
2590  EXPECT_EQ("f(g(h(a, // comment\n"
2591            "      b, c),\n"
2592            "    d, e),\n"
2593            "  x, y);",
2594            format("f(g(h(a, // comment\n"
2595                   "    b, c), d, e), x, y);"));
2596
2597  // Prefer breaking similar line breaks.
2598  verifyFormat(
2599      "const int kTrackingOptions = NSTrackingMouseMoved |\n"
2600      "                             NSTrackingMouseEnteredAndExited |\n"
2601      "                             NSTrackingActiveAlways;");
2602}
2603
2604TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
2605  FormatStyle NoBinPacking = getGoogleStyle();
2606  NoBinPacking.BinPackParameters = false;
2607  verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
2608               "  aaaaaaaaaaaaaaaaaaaa,\n"
2609               "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
2610               NoBinPacking);
2611  verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
2612               "        aaaaaaaaaaaaa,\n"
2613               "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
2614               NoBinPacking);
2615  verifyFormat(
2616      "aaaaaaaa(aaaaaaaaaaaaa,\n"
2617      "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2618      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
2619      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2620      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
2621      NoBinPacking);
2622  verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
2623               "    .aaaaaaaaaaaaaaaaaa();",
2624               NoBinPacking);
2625  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2626               "    aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);",
2627               NoBinPacking);
2628
2629  verifyFormat(
2630      "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2631      "             aaaaaaaaaaaa,\n"
2632      "             aaaaaaaaaaaa);",
2633      NoBinPacking);
2634  verifyFormat(
2635      "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
2636      "                               ddddddddddddddddddddddddddddd),\n"
2637      "             test);",
2638      NoBinPacking);
2639
2640  verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
2641               "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
2642               "            aaaaaaaaaaaaaaaaaaaaaaa> aaaaaaaaaaaaaaaaaa;",
2643               NoBinPacking);
2644  verifyFormat("a(\"a\"\n"
2645               "  \"a\",\n"
2646               "  a);");
2647
2648  NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
2649  verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
2650               "                aaaaaaaaa,\n"
2651               "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
2652               NoBinPacking);
2653  verifyFormat(
2654      "void f() {\n"
2655      "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
2656      "      .aaaaaaa();\n"
2657      "}",
2658      NoBinPacking);
2659  verifyFormat(
2660      "template <class SomeType, class SomeOtherType>\n"
2661      "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
2662      NoBinPacking);
2663}
2664
2665TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
2666  FormatStyle Style = getLLVMStyleWithColumns(15);
2667  Style.ExperimentalAutoDetectBinPacking = true;
2668  EXPECT_EQ("aaa(aaaa,\n"
2669            "    aaaa,\n"
2670            "    aaaa);\n"
2671            "aaa(aaaa,\n"
2672            "    aaaa,\n"
2673            "    aaaa);",
2674            format("aaa(aaaa,\n" // one-per-line
2675                   "  aaaa,\n"
2676                   "    aaaa  );\n"
2677                   "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
2678                   Style));
2679  EXPECT_EQ("aaa(aaaa, aaaa,\n"
2680            "    aaaa);\n"
2681            "aaa(aaaa, aaaa,\n"
2682            "    aaaa);",
2683            format("aaa(aaaa,  aaaa,\n" // bin-packed
2684                   "    aaaa  );\n"
2685                   "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
2686                   Style));
2687}
2688
2689TEST_F(FormatTest, FormatsBuilderPattern) {
2690  verifyFormat(
2691      "return llvm::StringSwitch<Reference::Kind>(name)\n"
2692      "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
2693      "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME).StartsWith(\".init\", ORDER_INIT)\n"
2694      "    .StartsWith(\".fini\", ORDER_FINI).StartsWith(\".hash\", ORDER_HASH)\n"
2695      "    .Default(ORDER_TEXT);\n");
2696
2697  verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
2698               "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
2699  verifyFormat(
2700      "aaaaaaa->aaaaaaa\n"
2701      "    ->aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2702      "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
2703  verifyFormat(
2704      "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
2705      "    aaaaaaaaaaaaaa);");
2706  verifyFormat(
2707      "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa = aaaaaa->aaaaaaaaaaaa()\n"
2708      "    ->aaaaaaaaaaaaaaaa(\n"
2709      "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2710      "    ->aaaaaaaaaaaaaaaaa();");
2711}
2712
2713TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
2714  verifyFormat(
2715      "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2716      "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
2717  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
2718               "    ccccccccccccccccccccccccc) {\n}");
2719  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
2720               "    ccccccccccccccccccccccccc) {\n}");
2721  verifyFormat(
2722      "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
2723      "    ccccccccccccccccccccccccc) {\n}");
2724  verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
2725               "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
2726               "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
2727               "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
2728  verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
2729               "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
2730               "    aaaaaaaaaaaaaaa != aa) {\n}");
2731}
2732
2733TEST_F(FormatTest, BreaksAfterAssignments) {
2734  verifyFormat(
2735      "unsigned Cost =\n"
2736      "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
2737      "                        SI->getPointerAddressSpaceee());\n");
2738  verifyFormat(
2739      "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
2740      "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
2741
2742  verifyFormat(
2743      "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa()\n"
2744      "    .aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
2745  verifyFormat("unsigned OriginalStartColumn =\n"
2746               "    SourceMgr.getSpellingColumnNumber(\n"
2747               "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
2748               "    1;");
2749}
2750
2751TEST_F(FormatTest, AlignsAfterAssignments) {
2752  verifyFormat(
2753      "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2754      "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
2755  verifyFormat(
2756      "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2757      "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
2758  verifyFormat(
2759      "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2760      "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
2761  verifyFormat(
2762      "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2763      "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
2764  verifyFormat(
2765      "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
2766      "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
2767      "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
2768}
2769
2770TEST_F(FormatTest, AlignsAfterReturn) {
2771  verifyFormat(
2772      "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2773      "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
2774  verifyFormat(
2775      "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2776      "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
2777  verifyFormat(
2778      "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
2779      "       aaaaaaaaaaaaaaaaaaaaaa();");
2780  verifyFormat(
2781      "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
2782      "        aaaaaaaaaaaaaaaaaaaaaa());");
2783  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2784               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2785  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2786               "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
2787               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2788}
2789
2790TEST_F(FormatTest, BreaksConditionalExpressions) {
2791  verifyFormat(
2792      "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2793      "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2794      "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2795  verifyFormat(
2796      "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2797      "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2798  verifyFormat(
2799      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
2800      "                                                    : aaaaaaaaaaaaa);");
2801  verifyFormat(
2802      "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2803      "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2804      "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2805      "                   aaaaaaaaaaaaa);");
2806  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2807               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2808               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2809               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2810               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2811  verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2812               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2813               "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2814               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2815               "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2816               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2817               "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2818
2819  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2820               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2821               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2822  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
2823               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2824               "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2825               "        : aaaaaaaaaaaaaaaa;");
2826  verifyFormat(
2827      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2828      "    ? aaaaaaaaaaaaaaa\n"
2829      "    : aaaaaaaaaaaaaaa;");
2830  verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
2831               "          aaaaaaaaa\n"
2832               "      ? b\n"
2833               "      : c);");
2834  verifyFormat(
2835      "unsigned Indent =\n"
2836      "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0\n"
2837      "                              ? IndentForLevel[TheLine.Level]\n"
2838      "                              : TheLine * 2,\n"
2839      "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
2840      getLLVMStyleWithColumns(70));
2841  verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
2842               "                  ? aaaaaaaaaaaaaaa\n"
2843               "                  : bbbbbbbbbbbbbbb //\n"
2844               "                        ? ccccccccccccccc\n"
2845               "                        : ddddddddddddddd;");
2846  verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
2847               "                  ? aaaaaaaaaaaaaaa\n"
2848               "                  : (bbbbbbbbbbbbbbb //\n"
2849               "                         ? ccccccccccccccc\n"
2850               "                         : ddddddddddddddd);");
2851
2852  FormatStyle NoBinPacking = getLLVMStyle();
2853  NoBinPacking.BinPackParameters = false;
2854  verifyFormat(
2855      "void f() {\n"
2856      "  g(aaa,\n"
2857      "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
2858      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2859      "        ? aaaaaaaaaaaaaaa\n"
2860      "        : aaaaaaaaaaaaaaa);\n"
2861      "}",
2862      NoBinPacking);
2863}
2864
2865TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
2866  verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
2867               "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
2868  verifyFormat("bool a = true, b = false;");
2869
2870  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
2871               "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
2872               "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
2873               "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
2874  verifyFormat(
2875      "bool aaaaaaaaaaaaaaaaaaaaa =\n"
2876      "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
2877      "     d = e && f;");
2878  verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
2879               "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
2880  verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
2881               "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
2882  verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
2883               "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
2884  // FIXME: If multiple variables are defined, the "*" needs to move to the new
2885  // line. Also fix indent for breaking after the type, this looks bad.
2886  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
2887               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
2888               "    *b = bbbbbbbbbbbbbbbbbbb;",
2889               getGoogleStyle());
2890
2891  // Not ideal, but pointer-with-type does not allow much here.
2892  verifyGoogleFormat(
2893      "aaaaaaaaa* a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
2894      "           *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;");
2895}
2896
2897TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
2898  verifyFormat("arr[foo ? bar : baz];");
2899  verifyFormat("f()[foo ? bar : baz];");
2900  verifyFormat("(a + b)[foo ? bar : baz];");
2901  verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
2902}
2903
2904TEST_F(FormatTest, AlignsStringLiterals) {
2905  verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
2906               "                                      \"short literal\");");
2907  verifyFormat(
2908      "looooooooooooooooooooooooongFunction(\n"
2909      "    \"short literal\"\n"
2910      "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
2911  verifyFormat("someFunction(\"Always break between multi-line\"\n"
2912               "             \" string literals\",\n"
2913               "             and, other, parameters);");
2914  EXPECT_EQ("fun + \"1243\" /* comment */\n"
2915            "      \"5678\";",
2916            format("fun + \"1243\" /* comment */\n"
2917                   "      \"5678\";",
2918                   getLLVMStyleWithColumns(28)));
2919  EXPECT_EQ(
2920      "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
2921      "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
2922      "         \"aaaaaaaaaaaaaaaa\";",
2923      format("aaaaaa ="
2924             "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
2925             "aaaaaaaaaaaaaaaaaaaaa\" "
2926             "\"aaaaaaaaaaaaaaaa\";"));
2927  verifyFormat("a = a + \"a\"\n"
2928               "        \"a\"\n"
2929               "        \"a\";");
2930  verifyFormat("f(\"a\", \"b\"\n"
2931               "       \"c\");");
2932
2933  verifyFormat(
2934      "#define LL_FORMAT \"ll\"\n"
2935      "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
2936      "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
2937
2938  verifyFormat("#define A(X)          \\\n"
2939               "  \"aaaaa\" #X \"bbbbbb\" \\\n"
2940               "  \"ccccc\"",
2941               getLLVMStyleWithColumns(23));
2942  verifyFormat("#define A \"def\"\n"
2943               "f(\"abc\" A \"ghi\"\n"
2944               "  \"jkl\");");
2945}
2946
2947TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
2948  FormatStyle NoBreak = getLLVMStyle();
2949  NoBreak.AlwaysBreakBeforeMultilineStrings = false;
2950  FormatStyle Break = getLLVMStyle();
2951  Break.AlwaysBreakBeforeMultilineStrings = true;
2952  EXPECT_EQ("aaaa = \"bbbb\"\n"
2953            "       \"cccc\";",
2954            format("aaaa=\"bbbb\" \"cccc\";", NoBreak));
2955  EXPECT_EQ("aaaa =\n"
2956            "    \"bbbb\"\n"
2957            "    \"cccc\";",
2958            format("aaaa=\"bbbb\" \"cccc\";", Break));
2959  EXPECT_EQ("aaaa(\"bbbb\"\n"
2960            "     \"cccc\");",
2961            format("aaaa(\"bbbb\" \"cccc\");", NoBreak));
2962  EXPECT_EQ("aaaa(\n"
2963            "    \"bbbb\"\n"
2964            "    \"cccc\");",
2965            format("aaaa(\"bbbb\" \"cccc\");", Break));
2966  EXPECT_EQ("aaaa(qqq, \"bbbb\"\n"
2967            "          \"cccc\");",
2968            format("aaaa(qqq, \"bbbb\" \"cccc\");", NoBreak));
2969  EXPECT_EQ("aaaa(qqq,\n"
2970            "     \"bbbb\"\n"
2971            "     \"cccc\");",
2972            format("aaaa(qqq, \"bbbb\" \"cccc\");", Break));
2973}
2974
2975TEST_F(FormatTest, AlignsPipes) {
2976  verifyFormat(
2977      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2978      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2979      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2980  verifyFormat(
2981      "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
2982      "                     << aaaaaaaaaaaaaaaaaaaa;");
2983  verifyFormat(
2984      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2985      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2986  verifyFormat(
2987      "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
2988      "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
2989      "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
2990  verifyFormat(
2991      "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2992      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2993      "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2994
2995  verifyFormat("return out << \"somepacket = {\\n\"\n"
2996               "           << \"  aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
2997               "           << \"  bbbb = \" << pkt.bbbb << \"\\n\"\n"
2998               "           << \"  cccccc = \" << pkt.cccccc << \"\\n\"\n"
2999               "           << \"  ddd = [\" << pkt.ddd << \"]\\n\"\n"
3000               "           << \"}\";");
3001
3002  verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
3003               "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
3004               "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
3005  verifyFormat(
3006      "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
3007      "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
3008      "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
3009      "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
3010      "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
3011  verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
3012               "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
3013  verifyFormat(
3014      "void f() {\n"
3015      "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
3016      "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
3017      "}");
3018
3019  // Breaking before the first "<<" is generally not desirable.
3020  verifyFormat(
3021      "llvm::errs()\n"
3022      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3023      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3024      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3025      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
3026      getLLVMStyleWithColumns(70));
3027  verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
3028               "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3029               "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
3030               "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3031               "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
3032               "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
3033               getLLVMStyleWithColumns(70));
3034
3035  // But sometimes, breaking before the first "<<" is necessary.
3036  verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
3037               "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3038               "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3039
3040  verifyFormat(
3041      "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3042      "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3043}
3044
3045TEST_F(FormatTest, UnderstandsEquals) {
3046  verifyFormat(
3047      "aaaaaaaaaaaaaaaaa =\n"
3048      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3049  verifyFormat(
3050      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3051      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
3052  verifyFormat(
3053      "if (a) {\n"
3054      "  f();\n"
3055      "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3056      "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
3057      "}");
3058
3059  verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3060               "        100000000 + 10000000) {\n}");
3061}
3062
3063TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
3064  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
3065               "    .looooooooooooooooooooooooooooooooooooooongFunction();");
3066
3067  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
3068               "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
3069
3070  verifyFormat(
3071      "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
3072      "                                                          Parameter2);");
3073
3074  verifyFormat(
3075      "ShortObject->shortFunction(\n"
3076      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
3077      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
3078
3079  verifyFormat("loooooooooooooongFunction(\n"
3080               "    LoooooooooooooongObject->looooooooooooooooongFunction());");
3081
3082  verifyFormat(
3083      "function(LoooooooooooooooooooooooooooooooooooongObject\n"
3084      "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
3085
3086  verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
3087               "    .WillRepeatedly(Return(SomeValue));");
3088  verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)]\n"
3089               "    .insert(ccccccccccccccccccccccc);");
3090  verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3091               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).aaaaa(aaaaa),\n"
3092               "      aaaaaaaaaaaaaaaaaaaaa);");
3093  verifyFormat(
3094      "aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3095      "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3096      "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3097      "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3098      "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
3099  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3100               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3101               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3102               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
3103               "}");
3104
3105  // Here, it is not necessary to wrap at "." or "->".
3106  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
3107               "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
3108  verifyFormat(
3109      "aaaaaaaaaaa->aaaaaaaaa(\n"
3110      "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3111      "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
3112
3113  verifyFormat(
3114      "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3115      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
3116  verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
3117               "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
3118  verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
3119               "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
3120
3121  // FIXME: Should we break before .a()?
3122  verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3123               "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).a();");
3124
3125  FormatStyle NoBinPacking = getLLVMStyle();
3126  NoBinPacking.BinPackParameters = false;
3127  verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
3128               "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
3129               "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
3130               "                         aaaaaaaaaaaaaaaaaaa,\n"
3131               "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
3132               NoBinPacking);
3133
3134  // If there is a subsequent call, change to hanging indentation.
3135  verifyFormat(
3136      "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3137      "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
3138      "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3139  verifyFormat(
3140      "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3141      "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
3142}
3143
3144TEST_F(FormatTest, WrapsTemplateDeclarations) {
3145  verifyFormat("template <typename T>\n"
3146               "virtual void loooooooooooongFunction(int Param1, int Param2);");
3147  verifyFormat(
3148      "template <typename T>\n"
3149      "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
3150  verifyFormat("template <typename T>\n"
3151               "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
3152               "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
3153  verifyFormat(
3154      "template <typename T>\n"
3155      "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
3156      "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
3157  verifyFormat(
3158      "template <typename T>\n"
3159      "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
3160      "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
3161      "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3162  verifyFormat("template <typename T>\n"
3163               "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3164               "    int aaaaaaaaaaaaaaaaaaaaaa);");
3165  verifyFormat(
3166      "template <typename T1, typename T2 = char, typename T3 = char,\n"
3167      "          typename T4 = char>\n"
3168      "void f();");
3169  verifyFormat(
3170      "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
3171      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3172
3173  verifyFormat("a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
3174               "    a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));");
3175
3176  verifyFormat("template <typename T> class C {};");
3177  verifyFormat("template <typename T> void f();");
3178  verifyFormat("template <typename T> void f() {}");
3179
3180  FormatStyle AlwaysBreak = getLLVMStyle();
3181  AlwaysBreak.AlwaysBreakTemplateDeclarations = true;
3182  verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
3183  verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
3184  verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
3185  verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3186               "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
3187               "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
3188  verifyFormat(
3189      "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
3190      "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3191      "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
3192      "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
3193      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3194      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
3195      "        bbbbbbbbbbbbbbbbbbbbbbbb);",
3196      getLLVMStyleWithColumns(72));
3197}
3198
3199TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
3200  verifyFormat(
3201      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3202      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3203  verifyFormat(
3204      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3205      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3206      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
3207
3208  // FIXME: Should we have the extra indent after the second break?
3209  verifyFormat(
3210      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3211      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3212      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3213
3214  verifyFormat(
3215      "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
3216      "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
3217
3218  // Breaking at nested name specifiers is generally not desirable.
3219  verifyFormat(
3220      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3221      "    aaaaaaaaaaaaaaaaaaaaaaa);");
3222
3223  verifyFormat(
3224      "aaaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3225      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3226      "                   aaaaaaaaaaaaaaaaaaaaa);",
3227      getLLVMStyleWithColumns(74));
3228
3229  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3230               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3231               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3232}
3233
3234TEST_F(FormatTest, UnderstandsTemplateParameters) {
3235  verifyFormat("A<int> a;");
3236  verifyFormat("A<A<A<int> > > a;");
3237  verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
3238  verifyFormat("bool x = a < 1 || 2 > a;");
3239  verifyFormat("bool x = 5 < f<int>();");
3240  verifyFormat("bool x = f<int>() > 5;");
3241  verifyFormat("bool x = 5 < a<int>::x;");
3242  verifyFormat("bool x = a < 4 ? a > 2 : false;");
3243  verifyFormat("bool x = f() ? a < 2 : a > 2;");
3244
3245  verifyGoogleFormat("A<A<int>> a;");
3246  verifyGoogleFormat("A<A<A<int>>> a;");
3247  verifyGoogleFormat("A<A<A<A<int>>>> a;");
3248  verifyGoogleFormat("A<A<int> > a;");
3249  verifyGoogleFormat("A<A<A<int> > > a;");
3250  verifyGoogleFormat("A<A<A<A<int> > > > a;");
3251  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
3252  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
3253
3254  verifyFormat("test >> a >> b;");
3255  verifyFormat("test << a >> b;");
3256
3257  verifyFormat("f<int>();");
3258  verifyFormat("template <typename T> void f() {}");
3259
3260  // Not template parameters.
3261  verifyFormat("return a < b && c > d;");
3262  verifyFormat("void f() {\n"
3263               "  while (a < b && c > d) {\n"
3264               "  }\n"
3265               "}");
3266}
3267
3268TEST_F(FormatTest, UnderstandsBinaryOperators) {
3269  verifyFormat("COMPARE(a, ==, b);");
3270}
3271
3272TEST_F(FormatTest, UnderstandsPointersToMembers) {
3273  verifyFormat("int A::*x;");
3274  verifyFormat("int (S::*func)(void *);");
3275  verifyFormat("void f() { int (S::*func)(void *); }");
3276  verifyFormat("typedef bool *(Class::*Member)() const;");
3277  verifyFormat("void f() {\n"
3278               "  (a->*f)();\n"
3279               "  a->*x;\n"
3280               "  (a.*f)();\n"
3281               "  ((*a).*f)();\n"
3282               "  a.*x;\n"
3283               "}");
3284  FormatStyle Style = getLLVMStyle();
3285  Style.PointerBindsToType = true;
3286  verifyFormat("typedef bool* (Class::*Member)() const;", Style);
3287}
3288
3289TEST_F(FormatTest, UnderstandsUnaryOperators) {
3290  verifyFormat("int a = -2;");
3291  verifyFormat("f(-1, -2, -3);");
3292  verifyFormat("a[-1] = 5;");
3293  verifyFormat("int a = 5 + -2;");
3294  verifyFormat("if (i == -1) {\n}");
3295  verifyFormat("if (i != -1) {\n}");
3296  verifyFormat("if (i > -1) {\n}");
3297  verifyFormat("if (i < -1) {\n}");
3298  verifyFormat("++(a->f());");
3299  verifyFormat("--(a->f());");
3300  verifyFormat("(a->f())++;");
3301  verifyFormat("a[42]++;");
3302  verifyFormat("if (!(a->f())) {\n}");
3303
3304  verifyFormat("a-- > b;");
3305  verifyFormat("b ? -a : c;");
3306  verifyFormat("n * sizeof char16;");
3307  verifyFormat("n * alignof char16;", getGoogleStyle());
3308  verifyFormat("sizeof(char);");
3309  verifyFormat("alignof(char);", getGoogleStyle());
3310
3311  verifyFormat("return -1;");
3312  verifyFormat("switch (a) {\n"
3313               "case -1:\n"
3314               "  break;\n"
3315               "}");
3316  verifyFormat("#define X -1");
3317  verifyFormat("#define X -kConstant");
3318
3319  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { -5, +3 };");
3320  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { +5, -3 };");
3321
3322  verifyFormat("int a = /* confusing comment */ -1;");
3323  // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
3324  verifyFormat("int a = i /* confusing comment */++;");
3325}
3326
3327TEST_F(FormatTest, UndestandsOverloadedOperators) {
3328  verifyFormat("bool operator<();");
3329  verifyFormat("bool operator>();");
3330  verifyFormat("bool operator=();");
3331  verifyFormat("bool operator==();");
3332  verifyFormat("bool operator!=();");
3333  verifyFormat("int operator+();");
3334  verifyFormat("int operator++();");
3335  verifyFormat("bool operator();");
3336  verifyFormat("bool operator()();");
3337  verifyFormat("bool operator[]();");
3338  verifyFormat("operator bool();");
3339  verifyFormat("operator int();");
3340  verifyFormat("operator void *();");
3341  verifyFormat("operator SomeType<int>();");
3342  verifyFormat("operator SomeType<int, int>();");
3343  verifyFormat("operator SomeType<SomeType<int> >();");
3344  verifyFormat("void *operator new(std::size_t size);");
3345  verifyFormat("void *operator new[](std::size_t size);");
3346  verifyFormat("void operator delete(void *ptr);");
3347  verifyFormat("void operator delete[](void *ptr);");
3348  verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
3349               "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
3350
3351  verifyFormat(
3352      "ostream &operator<<(ostream &OutputStream,\n"
3353      "                    SomeReallyLongType WithSomeReallyLongValue);");
3354  verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
3355               "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
3356               "  return left.group < right.group;\n"
3357               "}");
3358  verifyFormat("SomeType &operator=(const SomeType &S);");
3359
3360  verifyGoogleFormat("operator void*();");
3361  verifyGoogleFormat("operator SomeType<SomeType<int>>();");
3362}
3363
3364TEST_F(FormatTest, UnderstandsNewAndDelete) {
3365  verifyFormat("void f() {\n"
3366               "  A *a = new A;\n"
3367               "  A *a = new (placement) A;\n"
3368               "  delete a;\n"
3369               "  delete (A *)a;\n"
3370               "}");
3371}
3372
3373TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
3374  verifyFormat("int *f(int *a) {}");
3375  verifyFormat("int main(int argc, char **argv) {}");
3376  verifyFormat("Test::Test(int b) : a(b * b) {}");
3377  verifyIndependentOfContext("f(a, *a);");
3378  verifyFormat("void g() { f(*a); }");
3379  verifyIndependentOfContext("int a = b * 10;");
3380  verifyIndependentOfContext("int a = 10 * b;");
3381  verifyIndependentOfContext("int a = b * c;");
3382  verifyIndependentOfContext("int a += b * c;");
3383  verifyIndependentOfContext("int a -= b * c;");
3384  verifyIndependentOfContext("int a *= b * c;");
3385  verifyIndependentOfContext("int a /= b * c;");
3386  verifyIndependentOfContext("int a = *b;");
3387  verifyIndependentOfContext("int a = *b * c;");
3388  verifyIndependentOfContext("int a = b * *c;");
3389  verifyIndependentOfContext("return 10 * b;");
3390  verifyIndependentOfContext("return *b * *c;");
3391  verifyIndependentOfContext("return a & ~b;");
3392  verifyIndependentOfContext("f(b ? *c : *d);");
3393  verifyIndependentOfContext("int a = b ? *c : *d;");
3394  verifyIndependentOfContext("*b = a;");
3395  verifyIndependentOfContext("a * ~b;");
3396  verifyIndependentOfContext("a * !b;");
3397  verifyIndependentOfContext("a * +b;");
3398  verifyIndependentOfContext("a * -b;");
3399  verifyIndependentOfContext("a * ++b;");
3400  verifyIndependentOfContext("a * --b;");
3401  verifyIndependentOfContext("a[4] * b;");
3402  verifyIndependentOfContext("a[a * a] = 1;");
3403  verifyIndependentOfContext("f() * b;");
3404  verifyIndependentOfContext("a * [self dostuff];");
3405  verifyIndependentOfContext("int x = a * (a + b);");
3406  verifyIndependentOfContext("(a *)(a + b);");
3407  verifyIndependentOfContext("int *pa = (int *)&a;");
3408  verifyIndependentOfContext("return sizeof(int **);");
3409  verifyIndependentOfContext("return sizeof(int ******);");
3410  verifyIndependentOfContext("return (int **&)a;");
3411  verifyIndependentOfContext("f((*PointerToArray)[10]);");
3412  verifyFormat("void f(Type (*parameter)[10]) {}");
3413  verifyGoogleFormat("return sizeof(int**);");
3414  verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
3415  verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
3416  verifyFormat("auto a = [](int **&, int ***) {};");
3417
3418  verifyIndependentOfContext("InvalidRegions[*R] = 0;");
3419
3420  verifyIndependentOfContext("A<int *> a;");
3421  verifyIndependentOfContext("A<int **> a;");
3422  verifyIndependentOfContext("A<int *, int *> a;");
3423  verifyIndependentOfContext(
3424      "const char *const p = reinterpret_cast<const char *const>(q);");
3425  verifyIndependentOfContext("A<int **, int **> a;");
3426  verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
3427  verifyFormat("for (char **a = b; *a; ++a) {\n}");
3428  verifyFormat("for (; a && b;) {\n}");
3429
3430  verifyFormat(
3431      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3432      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3433
3434  verifyGoogleFormat("int main(int argc, char** argv) {}");
3435  verifyGoogleFormat("A<int*> a;");
3436  verifyGoogleFormat("A<int**> a;");
3437  verifyGoogleFormat("A<int*, int*> a;");
3438  verifyGoogleFormat("A<int**, int**> a;");
3439  verifyGoogleFormat("f(b ? *c : *d);");
3440  verifyGoogleFormat("int a = b ? *c : *d;");
3441  verifyGoogleFormat("Type* t = **x;");
3442  verifyGoogleFormat("Type* t = *++*x;");
3443  verifyGoogleFormat("*++*x;");
3444  verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
3445  verifyGoogleFormat("Type* t = x++ * y;");
3446  verifyGoogleFormat(
3447      "const char* const p = reinterpret_cast<const char* const>(q);");
3448
3449  verifyIndependentOfContext("a = *(x + y);");
3450  verifyIndependentOfContext("a = &(x + y);");
3451  verifyIndependentOfContext("*(x + y).call();");
3452  verifyIndependentOfContext("&(x + y)->call();");
3453  verifyFormat("void f() { &(*I).first; }");
3454
3455  verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
3456  verifyFormat(
3457      "int *MyValues = {\n"
3458      "  *A, // Operator detection might be confused by the '{'\n"
3459      "  *BB // Operator detection might be confused by previous comment\n"
3460      "};");
3461
3462  verifyIndependentOfContext("if (int *a = &b)");
3463  verifyIndependentOfContext("if (int &a = *b)");
3464  verifyIndependentOfContext("if (a & b[i])");
3465  verifyIndependentOfContext("if (a::b::c::d & b[i])");
3466  verifyIndependentOfContext("if (*b[i])");
3467  verifyIndependentOfContext("if (int *a = (&b))");
3468  verifyIndependentOfContext("while (int *a = &b)");
3469  verifyFormat("void f() {\n"
3470               "  for (const int &v : Values) {\n"
3471               "  }\n"
3472               "}");
3473  verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
3474  verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
3475
3476  verifyFormat("#define MACRO     \\\n"
3477               "  int *i = a * b; \\\n"
3478               "  void f(a *b);",
3479               getLLVMStyleWithColumns(19));
3480
3481  verifyIndependentOfContext("A = new SomeType *[Length];");
3482  verifyIndependentOfContext("A = new SomeType *[Length]();");
3483  verifyIndependentOfContext("T **t = new T *;");
3484  verifyIndependentOfContext("T **t = new T *();");
3485  verifyGoogleFormat("A = new SomeType* [Length]();");
3486  verifyGoogleFormat("A = new SomeType* [Length];");
3487  verifyGoogleFormat("T** t = new T*;");
3488  verifyGoogleFormat("T** t = new T*();");
3489
3490  FormatStyle PointerLeft = getLLVMStyle();
3491  PointerLeft.PointerBindsToType = true;
3492  verifyFormat("delete *x;", PointerLeft);
3493}
3494
3495TEST_F(FormatTest, UnderstandsEllipsis) {
3496  verifyFormat("int printf(const char *fmt, ...);");
3497  verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
3498  verifyFormat("template <class... Ts> void Foo(Ts *... ts) {}");
3499
3500  FormatStyle PointersLeft = getLLVMStyle();
3501  PointersLeft.PointerBindsToType = true;
3502  verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", PointersLeft);
3503}
3504
3505TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
3506  EXPECT_EQ("int *a;\n"
3507            "int *a;\n"
3508            "int *a;",
3509            format("int *a;\n"
3510                   "int* a;\n"
3511                   "int *a;",
3512                   getGoogleStyle()));
3513  EXPECT_EQ("int* a;\n"
3514            "int* a;\n"
3515            "int* a;",
3516            format("int* a;\n"
3517                   "int* a;\n"
3518                   "int *a;",
3519                   getGoogleStyle()));
3520  EXPECT_EQ("int *a;\n"
3521            "int *a;\n"
3522            "int *a;",
3523            format("int *a;\n"
3524                   "int * a;\n"
3525                   "int *  a;",
3526                   getGoogleStyle()));
3527}
3528
3529TEST_F(FormatTest, UnderstandsRvalueReferences) {
3530  verifyFormat("int f(int &&a) {}");
3531  verifyFormat("int f(int a, char &&b) {}");
3532  verifyFormat("void f() { int &&a = b; }");
3533  verifyGoogleFormat("int f(int a, char&& b) {}");
3534  verifyGoogleFormat("void f() { int&& a = b; }");
3535
3536  verifyIndependentOfContext("A<int &&> a;");
3537  verifyIndependentOfContext("A<int &&, int &&> a;");
3538  verifyGoogleFormat("A<int&&> a;");
3539  verifyGoogleFormat("A<int&&, int&&> a;");
3540}
3541
3542TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
3543  verifyFormat("void f() {\n"
3544               "  x[aaaaaaaaa -\n"
3545               "    b] = 23;\n"
3546               "}",
3547               getLLVMStyleWithColumns(15));
3548}
3549
3550TEST_F(FormatTest, FormatsCasts) {
3551  verifyFormat("Type *A = static_cast<Type *>(P);");
3552  verifyFormat("Type *A = (Type *)P;");
3553  verifyFormat("Type *A = (vector<Type *, int *>)P;");
3554  verifyFormat("int a = (int)(2.0f);");
3555  verifyFormat("int a = (int)2.0f;");
3556  verifyFormat("x[(int32)y];");
3557  verifyFormat("x = (int32)y;");
3558  verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
3559  verifyFormat("int a = (int)*b;");
3560  verifyFormat("int a = (int)2.0f;");
3561  verifyFormat("int a = (int)~0;");
3562  verifyFormat("int a = (int)++a;");
3563  verifyFormat("int a = (int)sizeof(int);");
3564  verifyFormat("int a = (int)+2;");
3565  verifyFormat("my_int a = (my_int)2.0f;");
3566  verifyFormat("my_int a = (my_int)sizeof(int);");
3567  verifyFormat("return (my_int)aaa;");
3568
3569  // FIXME: Without type knowledge, this can still fall apart miserably.
3570  verifyFormat("void f() { my_int a = (my_int) * b; }");
3571  verifyFormat("void f() { return P ? (my_int) * P : (my_int)0; }");
3572  verifyFormat("my_int a = (my_int) ~0;");
3573  verifyFormat("my_int a = (my_int)++ a;");
3574  verifyFormat("my_int a = (my_int) + 2;");
3575
3576  // These are not casts.
3577  verifyFormat("void f(int *) {}");
3578  verifyFormat("f(foo)->b;");
3579  verifyFormat("f(foo).b;");
3580  verifyFormat("f(foo)(b);");
3581  verifyFormat("f(foo)[b];");
3582  verifyFormat("[](foo) { return 4; }(bar)];");
3583  verifyFormat("(*funptr)(foo)[4];");
3584  verifyFormat("funptrs[4](foo)[4];");
3585  verifyFormat("void f(int *);");
3586  verifyFormat("void f(int *) = 0;");
3587  verifyFormat("void f(SmallVector<int>) {}");
3588  verifyFormat("void f(SmallVector<int>);");
3589  verifyFormat("void f(SmallVector<int>) = 0;");
3590  verifyFormat("void f(int i = (kValue) * kMask) {}");
3591  verifyFormat("void f(int i = (kA * kB) & kMask) {}");
3592  verifyFormat("int a = sizeof(int) * b;");
3593  verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
3594  verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
3595  verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
3596  verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
3597
3598  // These are not casts, but at some point were confused with casts.
3599  verifyFormat("virtual void foo(int *) override;");
3600  verifyFormat("virtual void foo(char &) const;");
3601  verifyFormat("virtual void foo(int *a, char *) const;");
3602  verifyFormat("int a = sizeof(int *) + b;");
3603  verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
3604
3605  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
3606               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
3607  // FIXME: The indentation here is not ideal.
3608  verifyFormat(
3609      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3610      "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
3611      "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
3612}
3613
3614TEST_F(FormatTest, FormatsFunctionTypes) {
3615  verifyFormat("A<bool()> a;");
3616  verifyFormat("A<SomeType()> a;");
3617  verifyFormat("A<void (*)(int, std::string)> a;");
3618  verifyFormat("A<void *(int)>;");
3619  verifyFormat("void *(*a)(int *, SomeType *);");
3620  verifyFormat("int (*func)(void *);");
3621  verifyFormat("void f() { int (*func)(void *); }");
3622
3623  verifyGoogleFormat("A<void*(int*, SomeType*)>;");
3624  verifyGoogleFormat("void* (*a)(int);");
3625
3626  // Other constructs can look somewhat like function types:
3627  verifyFormat("A<sizeof(*x)> a;");
3628  verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
3629}
3630
3631TEST_F(FormatTest, BreaksLongDeclarations) {
3632  verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
3633               "    AnotherNameForTheLongType;",
3634               getGoogleStyle());
3635  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
3636               "    LoooooooooooooooooooooooooooooooooooooooongVariable;",
3637               getGoogleStyle());
3638  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
3639               "    LoooooooooooooooooooooooooooooooooooooooongVariable;",
3640               getGoogleStyle());
3641  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
3642               "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
3643               getGoogleStyle());
3644  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
3645               "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
3646  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
3647               "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
3648
3649  // FIXME: Without the comment, this breaks after "(".
3650  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
3651               "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
3652               getGoogleStyle());
3653
3654  verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
3655               "                  int LoooooooooooooooooooongParam2) {}");
3656  verifyFormat(
3657      "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
3658      "                                   SourceLocation L, IdentifierIn *II,\n"
3659      "                                   Type *T) {}");
3660  verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
3661               "ReallyReallyLongFunctionName(\n"
3662               "    const std::string &SomeParameter,\n"
3663               "    const SomeType<string, SomeOtherTemplateParameter> &\n"
3664               "        ReallyReallyLongParameterName,\n"
3665               "    const SomeType<string, SomeOtherTemplateParameter> &\n"
3666               "        AnotherLongParameterName) {}");
3667  verifyFormat("template <typename A>\n"
3668               "SomeLoooooooooooooooooooooongType<\n"
3669               "    typename some_namespace::SomeOtherType<A>::Type>\n"
3670               "Function() {}");
3671  verifyFormat(
3672      "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
3673      "    aaaaaaaaaaaaaaaaaaaaaaa;",
3674      getGoogleStyle());
3675
3676  verifyGoogleFormat(
3677      "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
3678      "                                   SourceLocation L) {}");
3679  verifyGoogleFormat(
3680      "some_namespace::LongReturnType\n"
3681      "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
3682      "    int first_long_parameter, int second_parameter) {}");
3683
3684  verifyGoogleFormat("template <typename T>\n"
3685                     "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
3686                     "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
3687  verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3688                     "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
3689}
3690
3691TEST_F(FormatTest, FormatsArrays) {
3692  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3693               "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
3694  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3695               "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
3696  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3697               "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
3698  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3699               "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3700               "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
3701  verifyFormat(
3702      "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
3703      "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3704      "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
3705}
3706
3707TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
3708  verifyFormat("(a)->b();");
3709  verifyFormat("--a;");
3710}
3711
3712TEST_F(FormatTest, HandlesIncludeDirectives) {
3713  verifyFormat("#include <string>\n"
3714               "#include <a/b/c.h>\n"
3715               "#include \"a/b/string\"\n"
3716               "#include \"string.h\"\n"
3717               "#include \"string.h\"\n"
3718               "#include <a-a>\n"
3719               "#include < path with space >\n"
3720               "#include \"abc.h\" // this is included for ABC\n"
3721               "#include \"some long include\" // with a comment\n"
3722               "#include \"some very long include paaaaaaaaaaaaaaaaaaaaaaath\"",
3723               getLLVMStyleWithColumns(35));
3724
3725  verifyFormat("#import <string>");
3726  verifyFormat("#import <a/b/c.h>");
3727  verifyFormat("#import \"a/b/string\"");
3728  verifyFormat("#import \"string.h\"");
3729  verifyFormat("#import \"string.h\"");
3730}
3731
3732//===----------------------------------------------------------------------===//
3733// Error recovery tests.
3734//===----------------------------------------------------------------------===//
3735
3736TEST_F(FormatTest, IncompleteParameterLists) {
3737  FormatStyle NoBinPacking = getLLVMStyle();
3738  NoBinPacking.BinPackParameters = false;
3739  verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
3740               "                        double *min_x,\n"
3741               "                        double *max_x,\n"
3742               "                        double *min_y,\n"
3743               "                        double *max_y,\n"
3744               "                        double *min_z,\n"
3745               "                        double *max_z, ) {}",
3746               NoBinPacking);
3747}
3748
3749TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
3750  verifyFormat("void f() { return; }\n42");
3751  verifyFormat("void f() {\n"
3752               "  if (0)\n"
3753               "    return;\n"
3754               "}\n"
3755               "42");
3756  verifyFormat("void f() { return }\n42");
3757  verifyFormat("void f() {\n"
3758               "  if (0)\n"
3759               "    return\n"
3760               "}\n"
3761               "42");
3762}
3763
3764TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
3765  EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
3766  EXPECT_EQ("void f() {\n"
3767            "  if (a)\n"
3768            "    return\n"
3769            "}",
3770            format("void  f  (  )  {  if  ( a )  return  }"));
3771  EXPECT_EQ("namespace N {\n"
3772            "void f()\n"
3773            "}",
3774            format("namespace  N  {  void f()  }"));
3775  EXPECT_EQ("namespace N {\n"
3776            "void f() {}\n"
3777            "void g()\n"
3778            "}",
3779            format("namespace N  { void f( ) { } void g( ) }"));
3780}
3781
3782TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
3783  verifyFormat("int aaaaaaaa =\n"
3784               "    // Overlylongcomment\n"
3785               "    b;",
3786               getLLVMStyleWithColumns(20));
3787  verifyFormat("function(\n"
3788               "    ShortArgument,\n"
3789               "    LoooooooooooongArgument);\n",
3790               getLLVMStyleWithColumns(20));
3791}
3792
3793TEST_F(FormatTest, IncorrectAccessSpecifier) {
3794  verifyFormat("public:");
3795  verifyFormat("class A {\n"
3796               "public\n"
3797               "  void f() {}\n"
3798               "};");
3799  verifyFormat("public\n"
3800               "int qwerty;");
3801  verifyFormat("public\n"
3802               "B {}");
3803  verifyFormat("public\n"
3804               "{}");
3805  verifyFormat("public\n"
3806               "B { int x; }");
3807}
3808
3809TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
3810  verifyFormat("{");
3811  verifyFormat("#})");
3812}
3813
3814TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
3815  verifyFormat("do {\n}");
3816  verifyFormat("do {\n}\n"
3817               "f();");
3818  verifyFormat("do {\n}\n"
3819               "wheeee(fun);");
3820  verifyFormat("do {\n"
3821               "  f();\n"
3822               "}");
3823}
3824
3825TEST_F(FormatTest, IncorrectCodeMissingParens) {
3826  verifyFormat("if {\n  foo;\n  foo();\n}");
3827  verifyFormat("switch {\n  foo;\n  foo();\n}");
3828  verifyFormat("for {\n  foo;\n  foo();\n}");
3829  verifyFormat("while {\n  foo;\n  foo();\n}");
3830  verifyFormat("do {\n  foo;\n  foo();\n} while;");
3831}
3832
3833TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
3834  verifyFormat("namespace {\n"
3835               "class Foo {  Foo  (\n"
3836               "};\n"
3837               "} // comment");
3838}
3839
3840TEST_F(FormatTest, IncorrectCodeErrorDetection) {
3841  EXPECT_EQ("{\n{}\n", format("{\n{\n}\n"));
3842  EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
3843  EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
3844  EXPECT_EQ("{\n  {}\n  }\n}\n", format("{\n  {\n    }\n  }\n}\n"));
3845
3846  EXPECT_EQ("{\n"
3847            "    {\n"
3848            " breakme(\n"
3849            "     qwe);\n"
3850            "}\n",
3851            format("{\n"
3852                   "    {\n"
3853                   " breakme(qwe);\n"
3854                   "}\n",
3855                   getLLVMStyleWithColumns(10)));
3856}
3857
3858TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
3859  verifyFormat("int x = {\n"
3860               "  avariable,\n"
3861               "  b(alongervariable)\n"
3862               "};",
3863               getLLVMStyleWithColumns(25));
3864}
3865
3866TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
3867  verifyFormat("return (a)(b) { 1, 2, 3 };");
3868}
3869
3870TEST_F(FormatTest, LayoutCxx11ConstructorBraceInitializers) {
3871    verifyFormat("vector<int> x{ 1, 2, 3, 4 };");
3872    verifyFormat("vector<T> x{ {}, {}, {}, {} };");
3873    verifyFormat("f({ 1, 2 });");
3874    verifyFormat("auto v = Foo{ 1 };");
3875    verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });");
3876    verifyFormat("Class::Class : member{ 1, 2, 3 } {}");
3877    verifyFormat("new vector<int>{ 1, 2, 3 };");
3878    verifyFormat("new int[3]{ 1, 2, 3 };");
3879    verifyFormat("return { arg1, arg2 };");
3880    verifyFormat("return { arg1, SomeType{ parameter } };");
3881    verifyFormat("new T{ arg1, arg2 };");
3882    verifyFormat("class Class {\n"
3883                 "  T member = { arg1, arg2 };\n"
3884                 "};");
3885    verifyFormat(
3886        "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3887        "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
3888        "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
3889        "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };");
3890    verifyFormat("DoSomethingWithVector({} /* No data */);");
3891    verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });");
3892    verifyFormat(
3893        "someFunction(OtherParam, BracedList{\n"
3894        "                           // comment 1 (Forcing interesting break)\n"
3895        "                           param1, param2,\n"
3896        "                           // comment 2\n"
3897        "                           param3, param4\n"
3898        "                         });");
3899
3900    FormatStyle NoSpaces = getLLVMStyle();
3901    NoSpaces.SpacesInBracedLists = false;
3902    verifyFormat("vector<int> x{1, 2, 3, 4};", NoSpaces);
3903    verifyFormat("vector<T> x{{}, {}, {}, {}};", NoSpaces);
3904    verifyFormat("f({1, 2});", NoSpaces);
3905    verifyFormat("auto v = Foo{-1};", NoSpaces);
3906    verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});", NoSpaces);
3907    verifyFormat("Class::Class : member{1, 2, 3} {}", NoSpaces);
3908    verifyFormat("new vector<int>{1, 2, 3};", NoSpaces);
3909    verifyFormat("new int[3]{1, 2, 3};", NoSpaces);
3910    verifyFormat("return {arg1, arg2};", NoSpaces);
3911    verifyFormat("return {arg1, SomeType{parameter}};", NoSpaces);
3912    verifyFormat("new T{arg1, arg2};", NoSpaces);
3913    verifyFormat("class Class {\n"
3914                 "  T member = {arg1, arg2};\n"
3915                 "};",
3916                 NoSpaces);
3917}
3918
3919TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
3920  verifyFormat("void f() { return 42; }");
3921  verifyFormat("void f() {\n"
3922               "  // Comment\n"
3923               "}");
3924  verifyFormat("{\n"
3925               "#error {\n"
3926               "  int a;\n"
3927               "}");
3928  verifyFormat("{\n"
3929               "  int a;\n"
3930               "#error {\n"
3931               "}");
3932  verifyFormat("void f() {} // comment");
3933  verifyFormat("void f() { int a; } // comment");
3934  verifyFormat("void f() {\n"
3935               "} // comment",
3936               getLLVMStyleWithColumns(15));
3937
3938  verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
3939  verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
3940
3941  verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
3942  verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
3943}
3944
3945TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
3946  // Elaborate type variable declarations.
3947  verifyFormat("struct foo a = { bar };\nint n;");
3948  verifyFormat("class foo a = { bar };\nint n;");
3949  verifyFormat("union foo a = { bar };\nint n;");
3950
3951  // Elaborate types inside function definitions.
3952  verifyFormat("struct foo f() {}\nint n;");
3953  verifyFormat("class foo f() {}\nint n;");
3954  verifyFormat("union foo f() {}\nint n;");
3955
3956  // Templates.
3957  verifyFormat("template <class X> void f() {}\nint n;");
3958  verifyFormat("template <struct X> void f() {}\nint n;");
3959  verifyFormat("template <union X> void f() {}\nint n;");
3960
3961  // Actual definitions...
3962  verifyFormat("struct {\n} n;");
3963  verifyFormat(
3964      "template <template <class T, class Y>, class Z> class X {\n} n;");
3965  verifyFormat("union Z {\n  int n;\n} x;");
3966  verifyFormat("class MACRO Z {\n} n;");
3967  verifyFormat("class MACRO(X) Z {\n} n;");
3968  verifyFormat("class __attribute__(X) Z {\n} n;");
3969  verifyFormat("class __declspec(X) Z {\n} n;");
3970  verifyFormat("class A##B##C {\n} n;");
3971
3972  // Redefinition from nested context:
3973  verifyFormat("class A::B::C {\n} n;");
3974
3975  // Template definitions.
3976  verifyFormat(
3977      "template <typename F>\n"
3978      "Matcher(const Matcher<F> &Other,\n"
3979      "        typename enable_if_c<is_base_of<F, T>::value &&\n"
3980      "                             !is_same<F, T>::value>::type * = 0)\n"
3981      "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
3982
3983  // FIXME: This is still incorrectly handled at the formatter side.
3984  verifyFormat("template <> struct X < 15, i < 3 && 42 < 50 && 33<28> {};");
3985
3986  // FIXME:
3987  // This now gets parsed incorrectly as class definition.
3988  // verifyFormat("class A<int> f() {\n}\nint n;");
3989
3990  // Elaborate types where incorrectly parsing the structural element would
3991  // break the indent.
3992  verifyFormat("if (true)\n"
3993               "  class X x;\n"
3994               "else\n"
3995               "  f();\n");
3996
3997  // This is simply incomplete. Formatting is not important, but must not crash.
3998  verifyFormat("class A:");
3999}
4000
4001TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
4002  verifyFormat("#error Leave     all         white!!!!! space* alone!\n");
4003  verifyFormat("#warning Leave     all         white!!!!! space* alone!\n");
4004  EXPECT_EQ("#error 1", format("  #  error   1"));
4005  EXPECT_EQ("#warning 1", format("  #  warning 1"));
4006}
4007
4008TEST_F(FormatTest, FormatHashIfExpressions) {
4009  // FIXME: Come up with a better indentation for #elif.
4010  verifyFormat(
4011      "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
4012      "    defined(BBBBBBBB)\n"
4013      "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
4014      "    defined(BBBBBBBB)\n"
4015      "#endif",
4016      getLLVMStyleWithColumns(65));
4017}
4018
4019TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
4020  FormatStyle AllowsMergedIf = getGoogleStyle();
4021  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
4022  verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
4023  verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
4024  verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
4025  EXPECT_EQ("if (true) return 42;",
4026            format("if (true)\nreturn 42;", AllowsMergedIf));
4027  FormatStyle ShortMergedIf = AllowsMergedIf;
4028  ShortMergedIf.ColumnLimit = 25;
4029  verifyFormat("#define A \\\n"
4030               "  if (true) return 42;",
4031               ShortMergedIf);
4032  verifyFormat("#define A \\\n"
4033               "  f();    \\\n"
4034               "  if (true)\n"
4035               "#define B",
4036               ShortMergedIf);
4037  verifyFormat("#define A \\\n"
4038               "  f();    \\\n"
4039               "  if (true)\n"
4040               "g();",
4041               ShortMergedIf);
4042  verifyFormat("{\n"
4043               "#ifdef A\n"
4044               "  // Comment\n"
4045               "  if (true) continue;\n"
4046               "#endif\n"
4047               "  // Comment\n"
4048               "  if (true) continue;",
4049               ShortMergedIf);
4050}
4051
4052TEST_F(FormatTest, BlockCommentsInControlLoops) {
4053  verifyFormat("if (0) /* a comment in a strange place */ {\n"
4054               "  f();\n"
4055               "}");
4056  verifyFormat("if (0) /* a comment in a strange place */ {\n"
4057               "  f();\n"
4058               "} /* another comment */ else /* comment #3 */ {\n"
4059               "  g();\n"
4060               "}");
4061  verifyFormat("while (0) /* a comment in a strange place */ {\n"
4062               "  f();\n"
4063               "}");
4064  verifyFormat("for (;;) /* a comment in a strange place */ {\n"
4065               "  f();\n"
4066               "}");
4067  verifyFormat("do /* a comment in a strange place */ {\n"
4068               "  f();\n"
4069               "} /* another comment */ while (0);");
4070}
4071
4072TEST_F(FormatTest, BlockComments) {
4073  EXPECT_EQ("/* */ /* */ /* */\n/* */ /* */ /* */",
4074            format("/* *//* */  /* */\n/* *//* */  /* */"));
4075  EXPECT_EQ("/* */ a /* */ b;", format("  /* */  a/* */  b;"));
4076  EXPECT_EQ("#define A /*123*/\\\n"
4077            "  b\n"
4078            "/* */\n"
4079            "someCall(\n"
4080            "    parameter);",
4081            format("#define A /*123*/ b\n"
4082                   "/* */\n"
4083                   "someCall(parameter);",
4084                   getLLVMStyleWithColumns(15)));
4085
4086  EXPECT_EQ("#define A\n"
4087            "/* */ someCall(\n"
4088            "    parameter);",
4089            format("#define A\n"
4090                   "/* */someCall(parameter);",
4091                   getLLVMStyleWithColumns(15)));
4092  EXPECT_EQ("/*\n**\n*/", format("/*\n**\n*/"));
4093  EXPECT_EQ("/*\n"
4094            "*\n"
4095            " * aaaaaa\n"
4096            "*aaaaaa\n"
4097            "*/",
4098            format("/*\n"
4099                   "*\n"
4100                   " * aaaaaa aaaaaa\n"
4101                   "*/",
4102                   getLLVMStyleWithColumns(10)));
4103  EXPECT_EQ("/*\n"
4104            "**\n"
4105            "* aaaaaa\n"
4106            "*aaaaaa\n"
4107            "*/",
4108            format("/*\n"
4109                   "**\n"
4110                   "* aaaaaa aaaaaa\n"
4111                   "*/",
4112                   getLLVMStyleWithColumns(10)));
4113
4114  FormatStyle NoBinPacking = getLLVMStyle();
4115  NoBinPacking.BinPackParameters = false;
4116  EXPECT_EQ("someFunction(1, /* comment 1 */\n"
4117            "             2, /* comment 2 */\n"
4118            "             3, /* comment 3 */\n"
4119            "             aaaa,\n"
4120            "             bbbb);",
4121            format("someFunction (1,   /* comment 1 */\n"
4122                   "                2, /* comment 2 */  \n"
4123                   "               3,   /* comment 3 */\n"
4124                   "aaaa, bbbb );",
4125                   NoBinPacking));
4126  verifyFormat(
4127      "bool aaaaaaaaaaaaa = /* comment: */ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4128      "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4129  EXPECT_EQ(
4130      "bool aaaaaaaaaaaaa = /* trailing comment */\n"
4131      "    aaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4132      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;",
4133      format(
4134          "bool       aaaaaaaaaaaaa =       /* trailing comment */\n"
4135          "    aaaaaaaaaaaaaaaaaaaaaaaaaaa||aaaaaaaaaaaaaaaaaaaaaaaaa    ||\n"
4136          "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa   || aaaaaaaaaaaaaaaaaaaaaaaaaa;"));
4137  EXPECT_EQ(
4138      "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
4139      "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   /* comment */\n"
4140      "int cccccccccccccccccccccccccccccc;       /* comment */\n",
4141      format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
4142             "int      bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n"
4143             "int    cccccccccccccccccccccccccccccc;  /* comment */\n"));
4144
4145  verifyFormat("void f(int * /* unused */) {}");
4146
4147  EXPECT_EQ("/*\n"
4148            " **\n"
4149            " */",
4150            format("/*\n"
4151                   " **\n"
4152                   " */"));
4153  EXPECT_EQ("/*\n"
4154            " *q\n"
4155            " */",
4156            format("/*\n"
4157                   " *q\n"
4158                   " */"));
4159  EXPECT_EQ("/*\n"
4160            " * q\n"
4161            " */",
4162            format("/*\n"
4163                   " * q\n"
4164                   " */"));
4165  EXPECT_EQ("/*\n"
4166            " **/",
4167            format("/*\n"
4168                   " **/"));
4169  EXPECT_EQ("/*\n"
4170            " ***/",
4171            format("/*\n"
4172                   " ***/"));
4173}
4174
4175TEST_F(FormatTest, BlockCommentsInMacros) {
4176  EXPECT_EQ("#define A          \\\n"
4177            "  {                \\\n"
4178            "    /* one line */ \\\n"
4179            "    someCall();",
4180            format("#define A {        \\\n"
4181                   "  /* one line */   \\\n"
4182                   "  someCall();",
4183                   getLLVMStyleWithColumns(20)));
4184  EXPECT_EQ("#define A          \\\n"
4185            "  {                \\\n"
4186            "    /* previous */ \\\n"
4187            "    /* one line */ \\\n"
4188            "    someCall();",
4189            format("#define A {        \\\n"
4190                   "  /* previous */   \\\n"
4191                   "  /* one line */   \\\n"
4192                   "  someCall();",
4193                   getLLVMStyleWithColumns(20)));
4194}
4195
4196TEST_F(FormatTest, BlockCommentsAtEndOfLine) {
4197  EXPECT_EQ("a = {\n"
4198            "  1111 /*    */\n"
4199            "};",
4200            format("a = {1111 /*    */\n"
4201                   "};",
4202                   getLLVMStyleWithColumns(15)));
4203  EXPECT_EQ("a = {\n"
4204            "  1111 /*      */\n"
4205            "};",
4206            format("a = {1111 /*      */\n"
4207                   "};",
4208                   getLLVMStyleWithColumns(15)));
4209
4210  // FIXME: The formatting is still wrong here.
4211  EXPECT_EQ("a = {\n"
4212            "  1111 /*      a\n"
4213            "          */\n"
4214            "};",
4215            format("a = {1111 /*      a */\n"
4216                   "};",
4217                   getLLVMStyleWithColumns(15)));
4218}
4219
4220TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
4221  // FIXME: This is not what we want...
4222  verifyFormat("{\n"
4223               "// a"
4224               "// b");
4225}
4226
4227TEST_F(FormatTest, FormatStarDependingOnContext) {
4228  verifyFormat("void f(int *a);");
4229  verifyFormat("void f() { f(fint * b); }");
4230  verifyFormat("class A {\n  void f(int *a);\n};");
4231  verifyFormat("class A {\n  int *a;\n};");
4232  verifyFormat("namespace a {\n"
4233               "namespace b {\n"
4234               "class A {\n"
4235               "  void f() {}\n"
4236               "  int *a;\n"
4237               "};\n"
4238               "}\n"
4239               "}");
4240}
4241
4242TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
4243  verifyFormat("while");
4244  verifyFormat("operator");
4245}
4246
4247//===----------------------------------------------------------------------===//
4248// Objective-C tests.
4249//===----------------------------------------------------------------------===//
4250
4251TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
4252  verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
4253  EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
4254            format("-(NSUInteger)indexOfObject:(id)anObject;"));
4255  EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
4256  EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
4257  EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
4258            format("-(NSInteger)Method3:(id)anObject;"));
4259  EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
4260            format("-(NSInteger)Method4:(id)anObject;"));
4261  EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
4262            format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
4263  EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
4264            format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
4265  EXPECT_EQ(
4266      "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;",
4267      format(
4268          "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;"));
4269
4270  // Very long objectiveC method declaration.
4271  verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
4272               "                    inRange:(NSRange)range\n"
4273               "                   outRange:(NSRange)out_range\n"
4274               "                  outRange1:(NSRange)out_range1\n"
4275               "                  outRange2:(NSRange)out_range2\n"
4276               "                  outRange3:(NSRange)out_range3\n"
4277               "                  outRange4:(NSRange)out_range4\n"
4278               "                  outRange5:(NSRange)out_range5\n"
4279               "                  outRange6:(NSRange)out_range6\n"
4280               "                  outRange7:(NSRange)out_range7\n"
4281               "                  outRange8:(NSRange)out_range8\n"
4282               "                  outRange9:(NSRange)out_range9;");
4283
4284  verifyFormat("- (int)sum:(vector<int>)numbers;");
4285  verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
4286  // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
4287  // protocol lists (but not for template classes):
4288  //verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
4289
4290  verifyFormat("- (int (*)())foo:(int (*)())f;");
4291  verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
4292
4293  // If there's no return type (very rare in practice!), LLVM and Google style
4294  // agree.
4295  verifyFormat("- foo;");
4296  verifyFormat("- foo:(int)f;");
4297  verifyGoogleFormat("- foo:(int)foo;");
4298}
4299
4300TEST_F(FormatTest, FormatObjCBlocks) {
4301  verifyFormat("int (^Block)(int, int);");
4302  verifyFormat("int (^Block1)(int, int) = ^(int i, int j)");
4303}
4304
4305TEST_F(FormatTest, FormatObjCInterface) {
4306  verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
4307               "@public\n"
4308               "  int field1;\n"
4309               "@protected\n"
4310               "  int field2;\n"
4311               "@private\n"
4312               "  int field3;\n"
4313               "@package\n"
4314               "  int field4;\n"
4315               "}\n"
4316               "+ (id)init;\n"
4317               "@end");
4318
4319  verifyGoogleFormat("@interface Foo : NSObject<NSSomeDelegate> {\n"
4320                     " @public\n"
4321                     "  int field1;\n"
4322                     " @protected\n"
4323                     "  int field2;\n"
4324                     " @private\n"
4325                     "  int field3;\n"
4326                     " @package\n"
4327                     "  int field4;\n"
4328                     "}\n"
4329                     "+ (id)init;\n"
4330                     "@end");
4331
4332  verifyFormat("@interface /* wait for it */ Foo\n"
4333               "+ (id)init;\n"
4334               "// Look, a comment!\n"
4335               "- (int)answerWith:(int)i;\n"
4336               "@end");
4337
4338  verifyFormat("@interface Foo\n"
4339               "@end\n"
4340               "@interface Bar\n"
4341               "@end");
4342
4343  verifyFormat("@interface Foo : Bar\n"
4344               "+ (id)init;\n"
4345               "@end");
4346
4347  verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
4348               "+ (id)init;\n"
4349               "@end");
4350
4351  verifyGoogleFormat("@interface Foo : Bar<Baz, Quux>\n"
4352                     "+ (id)init;\n"
4353                     "@end");
4354
4355  verifyFormat("@interface Foo (HackStuff)\n"
4356               "+ (id)init;\n"
4357               "@end");
4358
4359  verifyFormat("@interface Foo ()\n"
4360               "+ (id)init;\n"
4361               "@end");
4362
4363  verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
4364               "+ (id)init;\n"
4365               "@end");
4366
4367  verifyGoogleFormat("@interface Foo (HackStuff)<MyProtocol>\n"
4368                     "+ (id)init;\n"
4369                     "@end");
4370
4371  verifyFormat("@interface Foo {\n"
4372               "  int _i;\n"
4373               "}\n"
4374               "+ (id)init;\n"
4375               "@end");
4376
4377  verifyFormat("@interface Foo : Bar {\n"
4378               "  int _i;\n"
4379               "}\n"
4380               "+ (id)init;\n"
4381               "@end");
4382
4383  verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
4384               "  int _i;\n"
4385               "}\n"
4386               "+ (id)init;\n"
4387               "@end");
4388
4389  verifyFormat("@interface Foo (HackStuff) {\n"
4390               "  int _i;\n"
4391               "}\n"
4392               "+ (id)init;\n"
4393               "@end");
4394
4395  verifyFormat("@interface Foo () {\n"
4396               "  int _i;\n"
4397               "}\n"
4398               "+ (id)init;\n"
4399               "@end");
4400
4401  verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
4402               "  int _i;\n"
4403               "}\n"
4404               "+ (id)init;\n"
4405               "@end");
4406}
4407
4408TEST_F(FormatTest, FormatObjCImplementation) {
4409  verifyFormat("@implementation Foo : NSObject {\n"
4410               "@public\n"
4411               "  int field1;\n"
4412               "@protected\n"
4413               "  int field2;\n"
4414               "@private\n"
4415               "  int field3;\n"
4416               "@package\n"
4417               "  int field4;\n"
4418               "}\n"
4419               "+ (id)init {\n}\n"
4420               "@end");
4421
4422  verifyGoogleFormat("@implementation Foo : NSObject {\n"
4423                     " @public\n"
4424                     "  int field1;\n"
4425                     " @protected\n"
4426                     "  int field2;\n"
4427                     " @private\n"
4428                     "  int field3;\n"
4429                     " @package\n"
4430                     "  int field4;\n"
4431                     "}\n"
4432                     "+ (id)init {\n}\n"
4433                     "@end");
4434
4435  verifyFormat("@implementation Foo\n"
4436               "+ (id)init {\n"
4437               "  if (true)\n"
4438               "    return nil;\n"
4439               "}\n"
4440               "// Look, a comment!\n"
4441               "- (int)answerWith:(int)i {\n"
4442               "  return i;\n"
4443               "}\n"
4444               "+ (int)answerWith:(int)i {\n"
4445               "  return i;\n"
4446               "}\n"
4447               "@end");
4448
4449  verifyFormat("@implementation Foo\n"
4450               "@end\n"
4451               "@implementation Bar\n"
4452               "@end");
4453
4454  verifyFormat("@implementation Foo : Bar\n"
4455               "+ (id)init {\n}\n"
4456               "- (void)foo {\n}\n"
4457               "@end");
4458
4459  verifyFormat("@implementation Foo {\n"
4460               "  int _i;\n"
4461               "}\n"
4462               "+ (id)init {\n}\n"
4463               "@end");
4464
4465  verifyFormat("@implementation Foo : Bar {\n"
4466               "  int _i;\n"
4467               "}\n"
4468               "+ (id)init {\n}\n"
4469               "@end");
4470
4471  verifyFormat("@implementation Foo (HackStuff)\n"
4472               "+ (id)init {\n}\n"
4473               "@end");
4474}
4475
4476TEST_F(FormatTest, FormatObjCProtocol) {
4477  verifyFormat("@protocol Foo\n"
4478               "@property(weak) id delegate;\n"
4479               "- (NSUInteger)numberOfThings;\n"
4480               "@end");
4481
4482  verifyFormat("@protocol MyProtocol <NSObject>\n"
4483               "- (NSUInteger)numberOfThings;\n"
4484               "@end");
4485
4486  verifyGoogleFormat("@protocol MyProtocol<NSObject>\n"
4487                     "- (NSUInteger)numberOfThings;\n"
4488                     "@end");
4489
4490  verifyFormat("@protocol Foo;\n"
4491               "@protocol Bar;\n");
4492
4493  verifyFormat("@protocol Foo\n"
4494               "@end\n"
4495               "@protocol Bar\n"
4496               "@end");
4497
4498  verifyFormat("@protocol myProtocol\n"
4499               "- (void)mandatoryWithInt:(int)i;\n"
4500               "@optional\n"
4501               "- (void)optional;\n"
4502               "@required\n"
4503               "- (void)required;\n"
4504               "@optional\n"
4505               "@property(assign) int madProp;\n"
4506               "@end\n");
4507}
4508
4509TEST_F(FormatTest, FormatObjCMethodDeclarations) {
4510  verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
4511               "                   rect:(NSRect)theRect\n"
4512               "               interval:(float)theInterval {\n"
4513               "}");
4514  verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
4515               "          longKeyword:(NSRect)theRect\n"
4516               "    evenLongerKeyword:(float)theInterval\n"
4517               "                error:(NSError **)theError {\n"
4518               "}");
4519}
4520
4521TEST_F(FormatTest, FormatObjCMethodExpr) {
4522  verifyFormat("[foo bar:baz];");
4523  verifyFormat("return [foo bar:baz];");
4524  verifyFormat("f([foo bar:baz]);");
4525  verifyFormat("f(2, [foo bar:baz]);");
4526  verifyFormat("f(2, a ? b : c);");
4527  verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
4528
4529  // Unary operators.
4530  verifyFormat("int a = +[foo bar:baz];");
4531  verifyFormat("int a = -[foo bar:baz];");
4532  verifyFormat("int a = ![foo bar:baz];");
4533  verifyFormat("int a = ~[foo bar:baz];");
4534  verifyFormat("int a = ++[foo bar:baz];");
4535  verifyFormat("int a = --[foo bar:baz];");
4536  verifyFormat("int a = sizeof [foo bar:baz];");
4537  verifyFormat("int a = alignof [foo bar:baz];", getGoogleStyle());
4538  verifyFormat("int a = &[foo bar:baz];");
4539  verifyFormat("int a = *[foo bar:baz];");
4540  // FIXME: Make casts work, without breaking f()[4].
4541  //verifyFormat("int a = (int)[foo bar:baz];");
4542  //verifyFormat("return (int)[foo bar:baz];");
4543  //verifyFormat("(void)[foo bar:baz];");
4544  verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
4545
4546  // Binary operators.
4547  verifyFormat("[foo bar:baz], [foo bar:baz];");
4548  verifyFormat("[foo bar:baz] = [foo bar:baz];");
4549  verifyFormat("[foo bar:baz] *= [foo bar:baz];");
4550  verifyFormat("[foo bar:baz] /= [foo bar:baz];");
4551  verifyFormat("[foo bar:baz] %= [foo bar:baz];");
4552  verifyFormat("[foo bar:baz] += [foo bar:baz];");
4553  verifyFormat("[foo bar:baz] -= [foo bar:baz];");
4554  verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
4555  verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
4556  verifyFormat("[foo bar:baz] &= [foo bar:baz];");
4557  verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
4558  verifyFormat("[foo bar:baz] |= [foo bar:baz];");
4559  verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
4560  verifyFormat("[foo bar:baz] || [foo bar:baz];");
4561  verifyFormat("[foo bar:baz] && [foo bar:baz];");
4562  verifyFormat("[foo bar:baz] | [foo bar:baz];");
4563  verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
4564  verifyFormat("[foo bar:baz] & [foo bar:baz];");
4565  verifyFormat("[foo bar:baz] == [foo bar:baz];");
4566  verifyFormat("[foo bar:baz] != [foo bar:baz];");
4567  verifyFormat("[foo bar:baz] >= [foo bar:baz];");
4568  verifyFormat("[foo bar:baz] <= [foo bar:baz];");
4569  verifyFormat("[foo bar:baz] > [foo bar:baz];");
4570  verifyFormat("[foo bar:baz] < [foo bar:baz];");
4571  verifyFormat("[foo bar:baz] >> [foo bar:baz];");
4572  verifyFormat("[foo bar:baz] << [foo bar:baz];");
4573  verifyFormat("[foo bar:baz] - [foo bar:baz];");
4574  verifyFormat("[foo bar:baz] + [foo bar:baz];");
4575  verifyFormat("[foo bar:baz] * [foo bar:baz];");
4576  verifyFormat("[foo bar:baz] / [foo bar:baz];");
4577  verifyFormat("[foo bar:baz] % [foo bar:baz];");
4578  // Whew!
4579
4580  verifyFormat("return in[42];");
4581  verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
4582               "}");
4583
4584  verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
4585  verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
4586  verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
4587  verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
4588  verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
4589  verifyFormat("[button setAction:@selector(zoomOut:)];");
4590  verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
4591
4592  verifyFormat("arr[[self indexForFoo:a]];");
4593  verifyFormat("throw [self errorFor:a];");
4594  verifyFormat("@throw [self errorFor:a];");
4595
4596  verifyFormat("[(id)foo bar:(id)baz quux:(id)snorf];");
4597  verifyFormat("[(id)foo bar:(id) ? baz : quux];");
4598  verifyFormat("4 > 4 ? (id)a : (id)baz;");
4599
4600  // This tests that the formatter doesn't break after "backing" but before ":",
4601  // which would be at 80 columns.
4602  verifyFormat(
4603      "void f() {\n"
4604      "  if ((self = [super initWithContentRect:contentRect\n"
4605      "                               styleMask:styleMask\n"
4606      "                                 backing:NSBackingStoreBuffered\n"
4607      "                                   defer:YES]))");
4608
4609  verifyFormat(
4610      "[foo checkThatBreakingAfterColonWorksOk:\n"
4611      "        [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
4612
4613  verifyFormat("[myObj short:arg1 // Force line break\n"
4614               "          longKeyword:arg2\n"
4615               "    evenLongerKeyword:arg3\n"
4616               "                error:arg4];");
4617  verifyFormat(
4618      "void f() {\n"
4619      "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
4620      "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
4621      "                                     pos.width(), pos.height())\n"
4622      "                styleMask:NSBorderlessWindowMask\n"
4623      "                  backing:NSBackingStoreBuffered\n"
4624      "                    defer:NO]);\n"
4625      "}");
4626  verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
4627               "                             with:contentsNativeView];");
4628
4629  verifyFormat(
4630      "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
4631      "           owner:nillllll];");
4632
4633  verifyFormat(
4634      "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
4635      "        forType:kBookmarkButtonDragType];");
4636
4637  verifyFormat("[defaultCenter addObserver:self\n"
4638               "                  selector:@selector(willEnterFullscreen)\n"
4639               "                      name:kWillEnterFullscreenNotification\n"
4640               "                    object:nil];");
4641  verifyFormat("[image_rep drawInRect:drawRect\n"
4642               "             fromRect:NSZeroRect\n"
4643               "            operation:NSCompositeCopy\n"
4644               "             fraction:1.0\n"
4645               "       respectFlipped:NO\n"
4646               "                hints:nil];");
4647
4648  verifyFormat(
4649      "scoped_nsobject<NSTextField> message(\n"
4650      "    // The frame will be fixed up when |-setMessageText:| is called.\n"
4651      "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
4652}
4653
4654TEST_F(FormatTest, ObjCAt) {
4655  verifyFormat("@autoreleasepool");
4656  verifyFormat("@catch");
4657  verifyFormat("@class");
4658  verifyFormat("@compatibility_alias");
4659  verifyFormat("@defs");
4660  verifyFormat("@dynamic");
4661  verifyFormat("@encode");
4662  verifyFormat("@end");
4663  verifyFormat("@finally");
4664  verifyFormat("@implementation");
4665  verifyFormat("@import");
4666  verifyFormat("@interface");
4667  verifyFormat("@optional");
4668  verifyFormat("@package");
4669  verifyFormat("@private");
4670  verifyFormat("@property");
4671  verifyFormat("@protected");
4672  verifyFormat("@protocol");
4673  verifyFormat("@public");
4674  verifyFormat("@required");
4675  verifyFormat("@selector");
4676  verifyFormat("@synchronized");
4677  verifyFormat("@synthesize");
4678  verifyFormat("@throw");
4679  verifyFormat("@try");
4680
4681  EXPECT_EQ("@interface", format("@ interface"));
4682
4683  // The precise formatting of this doesn't matter, nobody writes code like
4684  // this.
4685  verifyFormat("@ /*foo*/ interface");
4686}
4687
4688TEST_F(FormatTest, ObjCSnippets) {
4689  verifyFormat("@autoreleasepool {\n"
4690               "  foo();\n"
4691               "}");
4692  verifyFormat("@class Foo, Bar;");
4693  verifyFormat("@compatibility_alias AliasName ExistingClass;");
4694  verifyFormat("@dynamic textColor;");
4695  verifyFormat("char *buf1 = @encode(int *);");
4696  verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
4697  verifyFormat("char *buf1 = @encode(int **);");
4698  verifyFormat("Protocol *proto = @protocol(p1);");
4699  verifyFormat("SEL s = @selector(foo:);");
4700  verifyFormat("@synchronized(self) {\n"
4701               "  f();\n"
4702               "}");
4703
4704  verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
4705  verifyGoogleFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
4706
4707  verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
4708  verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
4709  verifyGoogleFormat("@property(assign, getter=isEditable) BOOL editable;");
4710
4711  verifyFormat("@import foo.bar;\n"
4712               "@import baz;");
4713}
4714
4715TEST_F(FormatTest, ObjCLiterals) {
4716  verifyFormat("@\"String\"");
4717  verifyFormat("@1");
4718  verifyFormat("@+4.8");
4719  verifyFormat("@-4");
4720  verifyFormat("@1LL");
4721  verifyFormat("@.5");
4722  verifyFormat("@'c'");
4723  verifyFormat("@true");
4724
4725  verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
4726  verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
4727  verifyFormat("NSNumber *favoriteColor = @(Green);");
4728  verifyFormat("NSString *path = @(getenv(\"PATH\"));");
4729
4730  verifyFormat("@[");
4731  verifyFormat("@[]");
4732  verifyFormat(
4733      "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
4734  verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
4735
4736  verifyFormat("@{");
4737  verifyFormat("@{}");
4738  verifyFormat("@{ @\"one\" : @1 }");
4739  verifyFormat("return @{ @\"one\" : @1 };");
4740  verifyFormat("@{ @\"one\" : @1, }");
4741
4742  verifyFormat("@{ @\"one\" : @{ @2 : @1 } }");
4743  verifyFormat("@{ @\"one\" : @{ @2 : @1 }, }");
4744
4745  verifyFormat("@{ 1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2 }");
4746  verifyFormat("[self setDict:@{}");
4747  verifyFormat("[self setDict:@{ @1 : @2 }");
4748  verifyFormat("NSLog(@\"%@\", @{ @1 : @2, @2 : @3 }[@1]);");
4749  verifyFormat(
4750      "NSDictionary *masses = @{ @\"H\" : @1.0078, @\"He\" : @4.0026 };");
4751  verifyFormat(
4752      "NSDictionary *settings = @{ AVEncoderKey : @(AVAudioQualityMax) };");
4753
4754  // FIXME: Nested and multi-line array and dictionary literals need more work.
4755  verifyFormat(
4756      "NSDictionary *d = @{ @\"nam\" : NSUserNam(), @\"dte\" : [NSDate date],\n"
4757      "                     @\"processInfo\" : [NSProcessInfo processInfo] };");
4758  verifyFormat(
4759      "@{ NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :\n"
4760      "   regularFont, };");
4761
4762}
4763
4764TEST_F(FormatTest, ReformatRegionAdjustsIndent) {
4765  EXPECT_EQ("{\n"
4766            "{\n"
4767            "a;\n"
4768            "b;\n"
4769            "}\n"
4770            "}",
4771            format("{\n"
4772                   "{\n"
4773                   "a;\n"
4774                   "     b;\n"
4775                   "}\n"
4776                   "}",
4777                   13, 2, getLLVMStyle()));
4778  EXPECT_EQ("{\n"
4779            "{\n"
4780            "  a;\n"
4781            "b;\n"
4782            "}\n"
4783            "}",
4784            format("{\n"
4785                   "{\n"
4786                   "     a;\n"
4787                   "b;\n"
4788                   "}\n"
4789                   "}",
4790                   9, 2, getLLVMStyle()));
4791  EXPECT_EQ("{\n"
4792            "{\n"
4793            "public:\n"
4794            "  b;\n"
4795            "}\n"
4796            "}",
4797            format("{\n"
4798                   "{\n"
4799                   "public:\n"
4800                   "     b;\n"
4801                   "}\n"
4802                   "}",
4803                   17, 2, getLLVMStyle()));
4804  EXPECT_EQ("{\n"
4805            "{\n"
4806            "a;\n"
4807            "}\n"
4808            "{\n"
4809            "  b; //\n"
4810            "}\n"
4811            "}",
4812            format("{\n"
4813                   "{\n"
4814                   "a;\n"
4815                   "}\n"
4816                   "{\n"
4817                   "           b; //\n"
4818                   "}\n"
4819                   "}",
4820                   22, 2, getLLVMStyle()));
4821  EXPECT_EQ("  {\n"
4822            "    a; //\n"
4823            "  }",
4824            format("  {\n"
4825                   "a; //\n"
4826                   "  }",
4827                   4, 2, getLLVMStyle()));
4828  EXPECT_EQ("void f() {}\n"
4829            "void g() {}",
4830            format("void f() {}\n"
4831                   "void g() {}",
4832                   13, 0, getLLVMStyle()));
4833  EXPECT_EQ("int a; // comment\n"
4834            "       // line 2\n"
4835            "int b;",
4836            format("int a; // comment\n"
4837                   "       // line 2\n"
4838                   "  int b;",
4839                   35, 0, getLLVMStyle()));
4840  EXPECT_EQ("  int a;\n"
4841            "  void\n"
4842            "  ffffff() {\n"
4843            "  }",
4844            format("  int a;\n"
4845                   "void ffffff() {}",
4846                   11, 0, getLLVMStyleWithColumns(11)));
4847}
4848
4849TEST_F(FormatTest, BreakStringLiterals) {
4850  EXPECT_EQ("\"some text \"\n"
4851            "\"other\";",
4852            format("\"some text other\";", getLLVMStyleWithColumns(12)));
4853  EXPECT_EQ("\"some text \"\n"
4854            "\"other\";",
4855            format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
4856  EXPECT_EQ(
4857      "#define A  \\\n"
4858      "  \"some \"  \\\n"
4859      "  \"text \"  \\\n"
4860      "  \"other\";",
4861      format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
4862  EXPECT_EQ(
4863      "#define A  \\\n"
4864      "  \"so \"    \\\n"
4865      "  \"text \"  \\\n"
4866      "  \"other\";",
4867      format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
4868
4869  EXPECT_EQ("\"some text\"",
4870            format("\"some text\"", getLLVMStyleWithColumns(1)));
4871  EXPECT_EQ("\"some text\"",
4872            format("\"some text\"", getLLVMStyleWithColumns(11)));
4873  EXPECT_EQ("\"some \"\n"
4874            "\"text\"",
4875            format("\"some text\"", getLLVMStyleWithColumns(10)));
4876  EXPECT_EQ("\"some \"\n"
4877            "\"text\"",
4878            format("\"some text\"", getLLVMStyleWithColumns(7)));
4879  EXPECT_EQ("\"some\"\n"
4880            "\" tex\"\n"
4881            "\"t\"",
4882            format("\"some text\"", getLLVMStyleWithColumns(6)));
4883  EXPECT_EQ("\"some\"\n"
4884            "\" tex\"\n"
4885            "\" and\"",
4886            format("\"some tex and\"", getLLVMStyleWithColumns(6)));
4887  EXPECT_EQ("\"some\"\n"
4888            "\"/tex\"\n"
4889            "\"/and\"",
4890            format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
4891
4892  EXPECT_EQ("variable =\n"
4893            "    \"long string \"\n"
4894            "    \"literal\";",
4895            format("variable = \"long string literal\";",
4896                   getLLVMStyleWithColumns(20)));
4897
4898  EXPECT_EQ("variable = f(\n"
4899            "    \"long string \"\n"
4900            "    \"literal\",\n"
4901            "    short,\n"
4902            "    loooooooooooooooooooong);",
4903            format("variable = f(\"long string literal\", short, "
4904                   "loooooooooooooooooooong);",
4905                   getLLVMStyleWithColumns(20)));
4906
4907  EXPECT_EQ("f(g(\"long string \"\n"
4908            "    \"literal\"),\n"
4909            "  b);",
4910            format("f(g(\"long string literal\"), b);",
4911                   getLLVMStyleWithColumns(20)));
4912  EXPECT_EQ("f(g(\"long string \"\n"
4913            "    \"literal\",\n"
4914            "    a),\n"
4915            "  b);",
4916            format("f(g(\"long string literal\", a), b);",
4917                   getLLVMStyleWithColumns(20)));
4918  EXPECT_EQ(
4919      "f(\"one two\".split(\n"
4920      "    variable));",
4921      format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
4922  EXPECT_EQ("f(\"one two three four five six \"\n"
4923            "  \"seven\".split(\n"
4924            "      really_looooong_variable));",
4925            format("f(\"one two three four five six seven\"."
4926                   "split(really_looooong_variable));",
4927                   getLLVMStyleWithColumns(33)));
4928
4929  EXPECT_EQ("f(\"some \"\n"
4930            "  \"text\",\n"
4931            "  other);",
4932            format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
4933
4934  // Only break as a last resort.
4935  verifyFormat(
4936      "aaaaaaaaaaaaaaaaaaaa(\n"
4937      "    aaaaaaaaaaaaaaaaaaaa,\n"
4938      "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
4939
4940  EXPECT_EQ(
4941      "\"splitmea\"\n"
4942      "\"trandomp\"\n"
4943      "\"oint\"",
4944      format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
4945
4946  EXPECT_EQ(
4947      "\"split/\"\n"
4948      "\"pathat/\"\n"
4949      "\"slashes\"",
4950      format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
4951
4952  EXPECT_EQ(
4953      "\"split/\"\n"
4954      "\"pathat/\"\n"
4955      "\"slashes\"",
4956      format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
4957  EXPECT_EQ("\"split at \"\n"
4958            "\"spaces/at/\"\n"
4959            "\"slashes.at.any$\"\n"
4960            "\"non-alphanumeric%\"\n"
4961            "\"1111111111characte\"\n"
4962            "\"rs\"",
4963            format("\"split at "
4964                   "spaces/at/"
4965                   "slashes.at."
4966                   "any$non-"
4967                   "alphanumeric%"
4968                   "1111111111characte"
4969                   "rs\"",
4970                   getLLVMStyleWithColumns(20)));
4971
4972  // Verify that splitting the strings understands
4973  // Style::AlwaysBreakBeforeMultilineStrings.
4974  EXPECT_EQ("aaaaaaaaaaaa(aaaaaaaaaaaaa,\n"
4975            "             \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
4976            "             \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
4977            format("aaaaaaaaaaaa(aaaaaaaaaaaaa, \"aaaaaaaaaaaaaaaaaaaaaa "
4978                   "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa "
4979                   "aaaaaaaaaaaaaaaaaaaaaa\");",
4980                   getGoogleStyle()));
4981
4982  FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
4983  AlignLeft.AlignEscapedNewlinesLeft = true;
4984  EXPECT_EQ(
4985      "#define A \\\n"
4986      "  \"some \" \\\n"
4987      "  \"text \" \\\n"
4988      "  \"other\";",
4989      format("#define A \"some text other\";", AlignLeft));
4990}
4991
4992TEST_F(FormatTest, SkipsUnknownStringLiterals) {
4993  EXPECT_EQ(
4994      "u8\"unsupported literal\";",
4995      format("u8\"unsupported literal\";", getGoogleStyleWithColumns(15)));
4996  EXPECT_EQ("u\"unsupported literal\";",
4997            format("u\"unsupported literal\";", getGoogleStyleWithColumns(15)));
4998  EXPECT_EQ("U\"unsupported literal\";",
4999            format("U\"unsupported literal\";", getGoogleStyleWithColumns(15)));
5000  EXPECT_EQ("L\"unsupported literal\";",
5001            format("L\"unsupported literal\";", getGoogleStyleWithColumns(15)));
5002  EXPECT_EQ("R\"x(raw literal)x\";",
5003            format("R\"x(raw literal)x\";", getGoogleStyleWithColumns(15)));
5004}
5005
5006TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
5007  EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
5008            format("#define x(_a) printf(\"foo\"_a);", getLLVMStyle()));
5009}
5010
5011TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
5012  EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
5013            "             \"ddeeefff\");",
5014            format("someFunction(\"aaabbbcccdddeeefff\");",
5015                   getLLVMStyleWithColumns(25)));
5016  EXPECT_EQ("someFunction1234567890(\n"
5017            "    \"aaabbbcccdddeeefff\");",
5018            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
5019                   getLLVMStyleWithColumns(26)));
5020  EXPECT_EQ("someFunction1234567890(\n"
5021            "    \"aaabbbcccdddeeeff\"\n"
5022            "    \"f\");",
5023            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
5024                   getLLVMStyleWithColumns(25)));
5025  EXPECT_EQ("someFunction1234567890(\n"
5026            "    \"aaabbbcccdddeeeff\"\n"
5027            "    \"f\");",
5028            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
5029                   getLLVMStyleWithColumns(24)));
5030  EXPECT_EQ("someFunction(\n"
5031            "    \"aaabbbcc \"\n"
5032            "    \"dddeeefff\");",
5033            format("someFunction(\"aaabbbcc dddeeefff\");",
5034                   getLLVMStyleWithColumns(25)));
5035  EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
5036            "             \"ddeeefff\");",
5037            format("someFunction(\"aaabbbccc ddeeefff\");",
5038                   getLLVMStyleWithColumns(25)));
5039  EXPECT_EQ("someFunction1234567890(\n"
5040            "    \"aaabb \"\n"
5041            "    \"cccdddeeefff\");",
5042            format("someFunction1234567890(\"aaabb cccdddeeefff\");",
5043                   getLLVMStyleWithColumns(25)));
5044  EXPECT_EQ("#define A          \\\n"
5045            "  string s =       \\\n"
5046            "      \"123456789\"  \\\n"
5047            "      \"0\";         \\\n"
5048            "  int i;",
5049            format("#define A string s = \"1234567890\"; int i;",
5050                   getLLVMStyleWithColumns(20)));
5051}
5052
5053TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
5054  EXPECT_EQ("\"\\a\"",
5055            format("\"\\a\"", getLLVMStyleWithColumns(3)));
5056  EXPECT_EQ("\"\\\"",
5057            format("\"\\\"", getLLVMStyleWithColumns(2)));
5058  EXPECT_EQ("\"test\"\n"
5059            "\"\\n\"",
5060            format("\"test\\n\"", getLLVMStyleWithColumns(7)));
5061  EXPECT_EQ("\"tes\\\\\"\n"
5062            "\"n\"",
5063            format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
5064  EXPECT_EQ("\"\\\\\\\\\"\n"
5065            "\"\\n\"",
5066            format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
5067  EXPECT_EQ("\"\\uff01\"",
5068            format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
5069  EXPECT_EQ("\"\\uff01\"\n"
5070            "\"test\"",
5071            format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
5072  EXPECT_EQ("\"\\Uff01ff02\"",
5073            format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
5074  EXPECT_EQ("\"\\x000000000001\"\n"
5075            "\"next\"",
5076            format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
5077  EXPECT_EQ("\"\\x000000000001next\"",
5078            format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
5079  EXPECT_EQ("\"\\x000000000001\"",
5080            format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
5081  EXPECT_EQ("\"test\"\n"
5082            "\"\\000000\"\n"
5083            "\"000001\"",
5084            format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
5085  EXPECT_EQ("\"test\\000\"\n"
5086            "\"00000000\"\n"
5087            "\"1\"",
5088            format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
5089  EXPECT_EQ("R\"(\\x\\x00)\"\n",
5090            format("R\"(\\x\\x00)\"\n", getGoogleStyleWithColumns(7)));
5091}
5092
5093TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
5094  verifyFormat("void f() {\n"
5095               "  return g() {}\n"
5096               "  void h() {}");
5097  verifyFormat("if (foo)\n"
5098               "  return { forgot_closing_brace();\n"
5099               "test();");
5100  verifyFormat("int a[] = { void forgot_closing_brace() { f();\n"
5101               "g();\n"
5102               "}");
5103}
5104
5105TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
5106  verifyFormat("class X {\n"
5107               "  void f() {\n"
5108               "  }\n"
5109               "};",
5110               getLLVMStyleWithColumns(12));
5111}
5112
5113TEST_F(FormatTest, ConfigurableIndentWidth) {
5114  FormatStyle EightIndent = getLLVMStyleWithColumns(18);
5115  EightIndent.IndentWidth = 8;
5116  verifyFormat("void f() {\n"
5117               "        someFunction();\n"
5118               "        if (true) {\n"
5119               "                f();\n"
5120               "        }\n"
5121               "}",
5122               EightIndent);
5123  verifyFormat("class X {\n"
5124               "        void f() {\n"
5125               "        }\n"
5126               "};",
5127               EightIndent);
5128  verifyFormat("int x[] = {\n"
5129               "        call(),\n"
5130               "        call(),\n"
5131               "};",
5132               EightIndent);
5133}
5134
5135TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
5136  verifyFormat("void\n"
5137               "f();",
5138               getLLVMStyleWithColumns(8));
5139}
5140
5141TEST_F(FormatTest, ConfigurableUseOfTab) {
5142  FormatStyle Tab = getLLVMStyleWithColumns(42);
5143  Tab.IndentWidth = 8;
5144  Tab.UseTab = true;
5145  Tab.AlignEscapedNewlinesLeft = true;
5146  verifyFormat("class X {\n"
5147               "\tvoid f() {\n"
5148               "\t\tsomeFunction(parameter1,\n"
5149               "\t\t\t     parameter2);\n"
5150               "\t}\n"
5151               "};",
5152               Tab);
5153  verifyFormat("#define A                        \\\n"
5154               "\tvoid f() {               \\\n"
5155               "\t\tsomeFunction(    \\\n"
5156               "\t\t    parameter1,  \\\n"
5157               "\t\t    parameter2); \\\n"
5158               "\t}",
5159               Tab);
5160
5161
5162  // FIXME: To correctly count mixed whitespace we need to
5163  // also correctly count mixed whitespace in front of the comment.
5164  //
5165  // EXPECT_EQ("/*\n"
5166  //           "\t      a\t\tcomment\n"
5167  //           "\t      in multiple lines\n"
5168  //           "       */",
5169  //           format("   /*\t \t \n"
5170  //                  " \t \t a\t\tcomment\t \t\n"
5171  //                  " \t \t in multiple lines\t\n"
5172  //                  " \t  */",
5173  //                  Tab));
5174  // Tab.UseTab = false;
5175  // EXPECT_EQ("/*\n"
5176  //           "              a\t\tcomment\n"
5177  //           "              in multiple lines\n"
5178  //           "       */",
5179  //           format("   /*\t \t \n"
5180  //                  " \t \t a\t\tcomment\t \t\n"
5181  //                  " \t \t in multiple lines\t\n"
5182  //                  " \t  */",
5183  //                  Tab));
5184  // EXPECT_EQ("/* some\n"
5185  //           "   comment */",
5186  //          format(" \t \t /* some\n"
5187  //                 " \t \t    comment */",
5188  //                 Tab));
5189
5190  EXPECT_EQ("{\n"
5191            "  /*\n"
5192            "   * Comment\n"
5193            "   */\n"
5194            "  int i;\n"
5195            "}",
5196            format("{\n"
5197                   "\t/*\n"
5198                   "\t * Comment\n"
5199                   "\t */\n"
5200                   "\t int i;\n"
5201                   "}"));
5202}
5203
5204TEST_F(FormatTest, LinuxBraceBreaking) {
5205  FormatStyle BreakBeforeBrace = getLLVMStyle();
5206  BreakBeforeBrace.BreakBeforeBraces = FormatStyle::BS_Linux;
5207  verifyFormat("namespace a\n"
5208               "{\n"
5209               "class A\n"
5210               "{\n"
5211               "  void f()\n"
5212               "  {\n"
5213               "    if (true) {\n"
5214               "      a();\n"
5215               "      b();\n"
5216               "    }\n"
5217               "  }\n"
5218               "  void g()\n"
5219               "  {\n"
5220               "    return;\n"
5221               "  }\n"
5222               "}\n"
5223               "}",
5224               BreakBeforeBrace);
5225}
5226
5227TEST_F(FormatTest, StroustrupBraceBreaking) {
5228  FormatStyle BreakBeforeBrace = getLLVMStyle();
5229  BreakBeforeBrace.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
5230  verifyFormat("namespace a {\n"
5231               "class A {\n"
5232               "  void f()\n"
5233               "  {\n"
5234               "    if (true) {\n"
5235               "      a();\n"
5236               "      b();\n"
5237               "    }\n"
5238               "  }\n"
5239               "  void g()\n"
5240               "  {\n"
5241               "    return;\n"
5242               "  }\n"
5243               "}\n"
5244               "}",
5245               BreakBeforeBrace);
5246}
5247
5248bool allStylesEqual(ArrayRef<FormatStyle> Styles) {
5249  for (size_t i = 1; i < Styles.size(); ++i)
5250    if (!(Styles[0] == Styles[i]))
5251      return false;
5252  return true;
5253}
5254
5255TEST_F(FormatTest, GetsPredefinedStyleByName) {
5256  FormatStyle Styles[3];
5257
5258  Styles[0] = getLLVMStyle();
5259  EXPECT_TRUE(getPredefinedStyle("LLVM", &Styles[1]));
5260  EXPECT_TRUE(getPredefinedStyle("lLvM", &Styles[2]));
5261  EXPECT_TRUE(allStylesEqual(Styles));
5262
5263  Styles[0] = getGoogleStyle();
5264  EXPECT_TRUE(getPredefinedStyle("Google", &Styles[1]));
5265  EXPECT_TRUE(getPredefinedStyle("gOOgle", &Styles[2]));
5266  EXPECT_TRUE(allStylesEqual(Styles));
5267
5268  Styles[0] = getChromiumStyle();
5269  EXPECT_TRUE(getPredefinedStyle("Chromium", &Styles[1]));
5270  EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", &Styles[2]));
5271  EXPECT_TRUE(allStylesEqual(Styles));
5272
5273  Styles[0] = getMozillaStyle();
5274  EXPECT_TRUE(getPredefinedStyle("Mozilla", &Styles[1]));
5275  EXPECT_TRUE(getPredefinedStyle("moZILla", &Styles[2]));
5276  EXPECT_TRUE(allStylesEqual(Styles));
5277
5278  EXPECT_FALSE(getPredefinedStyle("qwerty", &Styles[0]));
5279}
5280
5281TEST_F(FormatTest, ParsesConfiguration) {
5282  FormatStyle Style = {};
5283#define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
5284  EXPECT_NE(VALUE, Style.FIELD);                                               \
5285  EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
5286  EXPECT_EQ(VALUE, Style.FIELD)
5287
5288#define CHECK_PARSE_BOOL(FIELD)                                                \
5289  Style.FIELD = false;                                                         \
5290  EXPECT_EQ(0, parseConfiguration(#FIELD ": true", &Style).value());           \
5291  EXPECT_TRUE(Style.FIELD);                                                    \
5292  EXPECT_EQ(0, parseConfiguration(#FIELD ": false", &Style).value());          \
5293  EXPECT_FALSE(Style.FIELD);
5294
5295  CHECK_PARSE_BOOL(AlignEscapedNewlinesLeft);
5296  CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
5297  CHECK_PARSE_BOOL(AllowShortIfStatementsOnASingleLine);
5298  CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
5299  CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
5300  CHECK_PARSE_BOOL(BinPackParameters);
5301  CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
5302  CHECK_PARSE_BOOL(DerivePointerBinding);
5303  CHECK_PARSE_BOOL(IndentCaseLabels);
5304  CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
5305  CHECK_PARSE_BOOL(PointerBindsToType);
5306  CHECK_PARSE_BOOL(SpacesInBracedLists);
5307  CHECK_PARSE_BOOL(UseTab);
5308  CHECK_PARSE_BOOL(IndentFunctionDeclarationAfterType);
5309
5310  CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
5311  CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
5312  CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
5313  CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
5314  CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
5315              PenaltyReturnTypeOnItsOwnLine, 1234u);
5316  CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
5317              SpacesBeforeTrailingComments, 1234u);
5318  CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
5319
5320  Style.Standard = FormatStyle::LS_Auto;
5321  CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
5322  CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
5323  CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
5324
5325  Style.ColumnLimit = 123;
5326  FormatStyle BaseStyle = getLLVMStyle();
5327  CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
5328  CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
5329
5330  Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
5331  CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
5332              FormatStyle::BS_Attach);
5333  CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
5334              FormatStyle::BS_Linux);
5335  CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
5336              FormatStyle::BS_Stroustrup);
5337
5338#undef CHECK_PARSE
5339#undef CHECK_PARSE_BOOL
5340}
5341
5342TEST_F(FormatTest, ConfigurationRoundTripTest) {
5343  FormatStyle Style = getLLVMStyle();
5344  std::string YAML = configurationAsText(Style);
5345  FormatStyle ParsedStyle = {};
5346  EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
5347  EXPECT_EQ(Style, ParsedStyle);
5348}
5349
5350TEST_F(FormatTest, WorksFor8bitEncodings) {
5351  EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
5352            "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
5353            "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
5354            "\"\xef\xee\xf0\xf3...\"",
5355            format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
5356                   "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
5357                   "\xef\xee\xf0\xf3...\"",
5358                   getLLVMStyleWithColumns(12)));
5359}
5360
5361// FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
5362#if !defined(_MSC_VER)
5363
5364TEST_F(FormatTest, CountsUTF8CharactersProperly) {
5365  verifyFormat("\"Однажды в студёную зимнюю пору...\"",
5366               getLLVMStyleWithColumns(35));
5367  verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
5368               getLLVMStyleWithColumns(21));
5369  verifyFormat("// Однажды в студёную зимнюю пору...",
5370               getLLVMStyleWithColumns(36));
5371  verifyFormat("// 一 二 三 四 五 六 七 八 九 十",
5372               getLLVMStyleWithColumns(22));
5373  verifyFormat("/* Однажды в студёную зимнюю пору... */",
5374               getLLVMStyleWithColumns(39));
5375  verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
5376               getLLVMStyleWithColumns(25));
5377}
5378
5379TEST_F(FormatTest, SplitsUTF8Strings) {
5380  EXPECT_EQ(
5381      "\"Однажды, в \"\n"
5382      "\"студёную \"\n"
5383      "\"зимнюю \"\n"
5384      "\"пору,\"",
5385      format("\"Однажды, в студёную зимнюю пору,\"",
5386             getLLVMStyleWithColumns(13)));
5387  EXPECT_EQ("\"一 二 三 四 \"\n"
5388            "\"五 六 七 八 \"\n"
5389            "\"九 十\"",
5390            format("\"一 二 三 四 五 六 七 八 九 十\"",
5391                   getLLVMStyleWithColumns(10)));
5392}
5393
5394TEST_F(FormatTest, SplitsUTF8LineComments) {
5395  EXPECT_EQ("// Я из лесу\n"
5396            "// вышел; был\n"
5397            "// сильный\n"
5398            "// мороз.",
5399            format("// Я из лесу вышел; был сильный мороз.",
5400                   getLLVMStyleWithColumns(13)));
5401  EXPECT_EQ("// 一二三\n"
5402            "// 四五六七\n"
5403            "// 八\n"
5404            "// 九 十",
5405            format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(6)));
5406}
5407
5408TEST_F(FormatTest, SplitsUTF8BlockComments) {
5409  EXPECT_EQ("/* Гляжу,\n"
5410            " * поднимается\n"
5411            " * медленно в\n"
5412            " * гору\n"
5413            " * Лошадка,\n"
5414            " * везущая\n"
5415            " * хворосту\n"
5416            " * воз. */",
5417            format("/* Гляжу, поднимается медленно в гору\n"
5418                   " * Лошадка, везущая хворосту воз. */",
5419                   getLLVMStyleWithColumns(13)));
5420  EXPECT_EQ("/* 一二三\n"
5421            " * 四五六七\n"
5422            " * 八\n"
5423            " * 九 十\n"
5424            " */",
5425            format("/* 一二三 四五六七 八  九 十 */", getLLVMStyleWithColumns(6)));
5426  EXPECT_EQ("/* �������� ��������\n"
5427            " * ��������\n"
5428            " * ������-�� */",
5429            format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
5430}
5431
5432#endif
5433
5434} // end namespace tooling
5435} // end namespace clang
5436