FormatTest.cpp revision e1f9a8e27f553dcb359dfd96a3fe3065de7c4dad
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
2481TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
2482  verifyFormat("void someLongFunction(\n"
2483               "    int someLongParameter) const {}",
2484               getLLVMStyleWithColumns(46));
2485  FormatStyle Style = getGoogleStyle();
2486  Style.ColumnLimit = 47;
2487  verifyFormat("void\n"
2488               "someLongFunction(int someLongParameter) const {\n}",
2489               getLLVMStyleWithColumns(47));
2490  verifyFormat("void someLongFunction(\n"
2491               "    int someLongParameter) const {}",
2492               Style);
2493  verifyFormat("LoooooongReturnType\n"
2494               "someLoooooooongFunction() const {}",
2495               getLLVMStyleWithColumns(47));
2496  verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
2497               "    const {}",
2498               Style);
2499
2500  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2501               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
2502  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
2503               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
2504  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
2505               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
2506
2507  verifyFormat(
2508      "void aaaaaaaaaaaaaaaaaa()\n"
2509      "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
2510      "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
2511  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2512               "    __attribute__((unused));");
2513  verifyFormat(
2514      "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2515      "    GUARDED_BY(aaaaaaaaaaaa);",
2516      getGoogleStyle());
2517  verifyFormat(
2518      "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2519      "    GUARDED_BY(aaaaaaaaaaaa);",
2520      getGoogleStyle());
2521}
2522
2523TEST_F(FormatTest, BreaksDesireably) {
2524  verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
2525               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
2526               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
2527  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2528               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2529               "}");
2530
2531  verifyFormat(
2532      "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2533      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2534
2535  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2536               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2537               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2538
2539  verifyFormat(
2540      "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2541      "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
2542      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2543      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
2544
2545  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2546               "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2547
2548  verifyFormat(
2549      "void f() {\n"
2550      "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
2551      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2552      "}");
2553  verifyFormat(
2554      "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2555      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2556  verifyFormat(
2557      "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2558      "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2559  verifyFormat(
2560      "aaaaaaaaaaaaaaaaa(\n"
2561      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2562      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2563
2564  // This test case breaks on an incorrect memoization, i.e. an optimization not
2565  // taking into account the StopAt value.
2566  verifyFormat(
2567      "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2568      "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2569      "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2570      "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2571
2572  verifyFormat("{\n  {\n    {\n"
2573               "      Annotation.SpaceRequiredBefore =\n"
2574               "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
2575               "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
2576               "    }\n  }\n}");
2577
2578  // Break on an outer level if there was a break on an inner level.
2579  EXPECT_EQ("f(g(h(a, // comment\n"
2580            "      b, c),\n"
2581            "    d, e),\n"
2582            "  x, y);",
2583            format("f(g(h(a, // comment\n"
2584                   "    b, c), d, e), x, y);"));
2585
2586  // Prefer breaking similar line breaks.
2587  verifyFormat(
2588      "const int kTrackingOptions = NSTrackingMouseMoved |\n"
2589      "                             NSTrackingMouseEnteredAndExited |\n"
2590      "                             NSTrackingActiveAlways;");
2591}
2592
2593TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
2594  FormatStyle NoBinPacking = getGoogleStyle();
2595  NoBinPacking.BinPackParameters = false;
2596  verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
2597               "  aaaaaaaaaaaaaaaaaaaa,\n"
2598               "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
2599               NoBinPacking);
2600  verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
2601               "        aaaaaaaaaaaaa,\n"
2602               "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
2603               NoBinPacking);
2604  verifyFormat(
2605      "aaaaaaaa(aaaaaaaaaaaaa,\n"
2606      "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2607      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
2608      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2609      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
2610      NoBinPacking);
2611  verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
2612               "    .aaaaaaaaaaaaaaaaaa();",
2613               NoBinPacking);
2614  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2615               "    aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);",
2616               NoBinPacking);
2617
2618  verifyFormat(
2619      "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2620      "             aaaaaaaaaaaa,\n"
2621      "             aaaaaaaaaaaa);",
2622      NoBinPacking);
2623  verifyFormat(
2624      "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
2625      "                               ddddddddddddddddddddddddddddd),\n"
2626      "             test);",
2627      NoBinPacking);
2628
2629  verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
2630               "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
2631               "            aaaaaaaaaaaaaaaaaaaaaaa> aaaaaaaaaaaaaaaaaa;",
2632               NoBinPacking);
2633  verifyFormat("a(\"a\"\n"
2634               "  \"a\",\n"
2635               "  a);");
2636
2637  NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
2638  verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
2639               "                aaaaaaaaa,\n"
2640               "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
2641               NoBinPacking);
2642  verifyFormat(
2643      "void f() {\n"
2644      "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
2645      "      .aaaaaaa();\n"
2646      "}",
2647      NoBinPacking);
2648  verifyFormat(
2649      "template <class SomeType, class SomeOtherType>\n"
2650      "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
2651      NoBinPacking);
2652}
2653
2654TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
2655  FormatStyle Style = getLLVMStyleWithColumns(15);
2656  Style.ExperimentalAutoDetectBinPacking = true;
2657  EXPECT_EQ("aaa(aaaa,\n"
2658            "    aaaa,\n"
2659            "    aaaa);\n"
2660            "aaa(aaaa,\n"
2661            "    aaaa,\n"
2662            "    aaaa);",
2663            format("aaa(aaaa,\n" // one-per-line
2664                   "  aaaa,\n"
2665                   "    aaaa  );\n"
2666                   "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
2667                   Style));
2668  EXPECT_EQ("aaa(aaaa, aaaa,\n"
2669            "    aaaa);\n"
2670            "aaa(aaaa, aaaa,\n"
2671            "    aaaa);",
2672            format("aaa(aaaa,  aaaa,\n" // bin-packed
2673                   "    aaaa  );\n"
2674                   "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
2675                   Style));
2676}
2677
2678TEST_F(FormatTest, FormatsBuilderPattern) {
2679  verifyFormat(
2680      "return llvm::StringSwitch<Reference::Kind>(name)\n"
2681      "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
2682      "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME).StartsWith(\".init\", ORDER_INIT)\n"
2683      "    .StartsWith(\".fini\", ORDER_FINI).StartsWith(\".hash\", ORDER_HASH)\n"
2684      "    .Default(ORDER_TEXT);\n");
2685
2686  verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
2687               "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
2688  verifyFormat(
2689      "aaaaaaa->aaaaaaa\n"
2690      "    ->aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2691      "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
2692  verifyFormat(
2693      "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
2694      "    aaaaaaaaaaaaaa);");
2695  verifyFormat(
2696      "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa = aaaaaa->aaaaaaaaaaaa()\n"
2697      "    ->aaaaaaaaaaaaaaaa(\n"
2698      "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2699      "    ->aaaaaaaaaaaaaaaaa();");
2700}
2701
2702TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
2703  verifyFormat(
2704      "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2705      "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
2706  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
2707               "    ccccccccccccccccccccccccc) {\n}");
2708  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
2709               "    ccccccccccccccccccccccccc) {\n}");
2710  verifyFormat(
2711      "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
2712      "    ccccccccccccccccccccccccc) {\n}");
2713  verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
2714               "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
2715               "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
2716               "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
2717  verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
2718               "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
2719               "    aaaaaaaaaaaaaaa != aa) {\n}");
2720}
2721
2722TEST_F(FormatTest, BreaksAfterAssignments) {
2723  verifyFormat(
2724      "unsigned Cost =\n"
2725      "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
2726      "                        SI->getPointerAddressSpaceee());\n");
2727  verifyFormat(
2728      "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
2729      "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
2730
2731  verifyFormat(
2732      "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa()\n"
2733      "    .aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
2734  verifyFormat("unsigned OriginalStartColumn =\n"
2735               "    SourceMgr.getSpellingColumnNumber(\n"
2736               "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
2737               "    1;");
2738}
2739
2740TEST_F(FormatTest, AlignsAfterAssignments) {
2741  verifyFormat(
2742      "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2743      "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
2744  verifyFormat(
2745      "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2746      "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
2747  verifyFormat(
2748      "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2749      "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
2750  verifyFormat(
2751      "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2752      "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
2753  verifyFormat(
2754      "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
2755      "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
2756      "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
2757}
2758
2759TEST_F(FormatTest, AlignsAfterReturn) {
2760  verifyFormat(
2761      "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2762      "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
2763  verifyFormat(
2764      "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2765      "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
2766  verifyFormat(
2767      "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
2768      "       aaaaaaaaaaaaaaaaaaaaaa();");
2769  verifyFormat(
2770      "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
2771      "        aaaaaaaaaaaaaaaaaaaaaa());");
2772  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2773               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2774  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2775               "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
2776               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2777}
2778
2779TEST_F(FormatTest, BreaksConditionalExpressions) {
2780  verifyFormat(
2781      "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2782      "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2783      "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2784  verifyFormat(
2785      "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2786      "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2787  verifyFormat(
2788      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
2789      "                                                    : aaaaaaaaaaaaa);");
2790  verifyFormat(
2791      "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2792      "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2793      "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2794      "                   aaaaaaaaaaaaa);");
2795  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2796               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2797               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2798               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2799               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2800  verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2801               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2802               "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2803               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2804               "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2805               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2806               "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2807
2808  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2809               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2810               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2811  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
2812               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2813               "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2814               "        : aaaaaaaaaaaaaaaa;");
2815  verifyFormat(
2816      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2817      "    ? aaaaaaaaaaaaaaa\n"
2818      "    : aaaaaaaaaaaaaaa;");
2819  verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
2820               "          aaaaaaaaa\n"
2821               "      ? b\n"
2822               "      : c);");
2823  verifyFormat(
2824      "unsigned Indent =\n"
2825      "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0\n"
2826      "                              ? IndentForLevel[TheLine.Level]\n"
2827      "                              : TheLine * 2,\n"
2828      "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
2829      getLLVMStyleWithColumns(70));
2830  verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
2831               "                  ? aaaaaaaaaaaaaaa\n"
2832               "                  : bbbbbbbbbbbbbbb //\n"
2833               "                        ? ccccccccccccccc\n"
2834               "                        : ddddddddddddddd;");
2835  verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
2836               "                  ? aaaaaaaaaaaaaaa\n"
2837               "                  : (bbbbbbbbbbbbbbb //\n"
2838               "                         ? ccccccccccccccc\n"
2839               "                         : ddddddddddddddd);");
2840
2841  FormatStyle NoBinPacking = getLLVMStyle();
2842  NoBinPacking.BinPackParameters = false;
2843  verifyFormat(
2844      "void f() {\n"
2845      "  g(aaa,\n"
2846      "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
2847      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2848      "        ? aaaaaaaaaaaaaaa\n"
2849      "        : aaaaaaaaaaaaaaa);\n"
2850      "}",
2851      NoBinPacking);
2852}
2853
2854TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
2855  verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
2856               "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
2857  verifyFormat("bool a = true, b = false;");
2858
2859  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
2860               "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
2861               "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
2862               "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
2863  verifyFormat(
2864      "bool aaaaaaaaaaaaaaaaaaaaa =\n"
2865      "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
2866      "     d = e && f;");
2867  verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
2868               "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
2869  verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
2870               "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
2871  verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
2872               "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
2873  // FIXME: If multiple variables are defined, the "*" needs to move to the new
2874  // line. Also fix indent for breaking after the type, this looks bad.
2875  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
2876               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
2877               "    *b = bbbbbbbbbbbbbbbbbbb;",
2878               getGoogleStyle());
2879
2880  // Not ideal, but pointer-with-type does not allow much here.
2881  verifyGoogleFormat(
2882      "aaaaaaaaa* a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
2883      "           *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;");
2884}
2885
2886TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
2887  verifyFormat("arr[foo ? bar : baz];");
2888  verifyFormat("f()[foo ? bar : baz];");
2889  verifyFormat("(a + b)[foo ? bar : baz];");
2890  verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
2891}
2892
2893TEST_F(FormatTest, AlignsStringLiterals) {
2894  verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
2895               "                                      \"short literal\");");
2896  verifyFormat(
2897      "looooooooooooooooooooooooongFunction(\n"
2898      "    \"short literal\"\n"
2899      "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
2900  verifyFormat("someFunction(\"Always break between multi-line\"\n"
2901               "             \" string literals\",\n"
2902               "             and, other, parameters);");
2903  EXPECT_EQ("fun + \"1243\" /* comment */\n"
2904            "      \"5678\";",
2905            format("fun + \"1243\" /* comment */\n"
2906                   "      \"5678\";",
2907                   getLLVMStyleWithColumns(28)));
2908  EXPECT_EQ(
2909      "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
2910      "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
2911      "         \"aaaaaaaaaaaaaaaa\";",
2912      format("aaaaaa ="
2913             "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
2914             "aaaaaaaaaaaaaaaaaaaaa\" "
2915             "\"aaaaaaaaaaaaaaaa\";"));
2916  verifyFormat("a = a + \"a\"\n"
2917               "        \"a\"\n"
2918               "        \"a\";");
2919  verifyFormat("f(\"a\", \"b\"\n"
2920               "       \"c\");");
2921
2922  verifyFormat(
2923      "#define LL_FORMAT \"ll\"\n"
2924      "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
2925      "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
2926
2927  verifyFormat("#define A(X)          \\\n"
2928               "  \"aaaaa\" #X \"bbbbbb\" \\\n"
2929               "  \"ccccc\"",
2930               getLLVMStyleWithColumns(23));
2931  verifyFormat("#define A \"def\"\n"
2932               "f(\"abc\" A \"ghi\"\n"
2933               "  \"jkl\");");
2934}
2935
2936TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
2937  FormatStyle NoBreak = getLLVMStyle();
2938  NoBreak.AlwaysBreakBeforeMultilineStrings = false;
2939  FormatStyle Break = getLLVMStyle();
2940  Break.AlwaysBreakBeforeMultilineStrings = true;
2941  EXPECT_EQ("aaaa = \"bbbb\"\n"
2942            "       \"cccc\";",
2943            format("aaaa=\"bbbb\" \"cccc\";", NoBreak));
2944  EXPECT_EQ("aaaa =\n"
2945            "    \"bbbb\"\n"
2946            "    \"cccc\";",
2947            format("aaaa=\"bbbb\" \"cccc\";", Break));
2948  EXPECT_EQ("aaaa(\"bbbb\"\n"
2949            "     \"cccc\");",
2950            format("aaaa(\"bbbb\" \"cccc\");", NoBreak));
2951  EXPECT_EQ("aaaa(\n"
2952            "    \"bbbb\"\n"
2953            "    \"cccc\");",
2954            format("aaaa(\"bbbb\" \"cccc\");", Break));
2955  EXPECT_EQ("aaaa(qqq, \"bbbb\"\n"
2956            "          \"cccc\");",
2957            format("aaaa(qqq, \"bbbb\" \"cccc\");", NoBreak));
2958  EXPECT_EQ("aaaa(qqq,\n"
2959            "     \"bbbb\"\n"
2960            "     \"cccc\");",
2961            format("aaaa(qqq, \"bbbb\" \"cccc\");", Break));
2962}
2963
2964TEST_F(FormatTest, AlignsPipes) {
2965  verifyFormat(
2966      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2967      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2968      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2969  verifyFormat(
2970      "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
2971      "                     << aaaaaaaaaaaaaaaaaaaa;");
2972  verifyFormat(
2973      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2974      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2975  verifyFormat(
2976      "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
2977      "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
2978      "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
2979  verifyFormat(
2980      "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2981      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2982      "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2983
2984  verifyFormat("return out << \"somepacket = {\\n\"\n"
2985               "           << \"  aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
2986               "           << \"  bbbb = \" << pkt.bbbb << \"\\n\"\n"
2987               "           << \"  cccccc = \" << pkt.cccccc << \"\\n\"\n"
2988               "           << \"  ddd = [\" << pkt.ddd << \"]\\n\"\n"
2989               "           << \"}\";");
2990
2991  verifyFormat(
2992      "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
2993      "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
2994      "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
2995      "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
2996      "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
2997  verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
2998               "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
2999  verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaa: \"\n"
3000               "             << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3001
3002  verifyFormat(
3003      "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3004      "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3005}
3006
3007TEST_F(FormatTest, UnderstandsEquals) {
3008  verifyFormat(
3009      "aaaaaaaaaaaaaaaaa =\n"
3010      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3011  verifyFormat(
3012      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3013      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
3014  verifyFormat(
3015      "if (a) {\n"
3016      "  f();\n"
3017      "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3018      "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
3019      "}");
3020
3021  verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3022               "        100000000 + 10000000) {\n}");
3023}
3024
3025TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
3026  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
3027               "    .looooooooooooooooooooooooooooooooooooooongFunction();");
3028
3029  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
3030               "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
3031
3032  verifyFormat(
3033      "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
3034      "                                                          Parameter2);");
3035
3036  verifyFormat(
3037      "ShortObject->shortFunction(\n"
3038      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
3039      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
3040
3041  verifyFormat("loooooooooooooongFunction(\n"
3042               "    LoooooooooooooongObject->looooooooooooooooongFunction());");
3043
3044  verifyFormat(
3045      "function(LoooooooooooooooooooooooooooooooooooongObject\n"
3046      "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
3047
3048  verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
3049               "    .WillRepeatedly(Return(SomeValue));");
3050  verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)]\n"
3051               "    .insert(ccccccccccccccccccccccc);");
3052  verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3053               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).aaaaa(aaaaa),\n"
3054               "      aaaaaaaaaaaaaaaaaaaaa);");
3055  verifyFormat(
3056      "aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3057      "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3058      "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3059      "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3060      "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
3061  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3062               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3063               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3064               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
3065               "}");
3066
3067  // Here, it is not necessary to wrap at "." or "->".
3068  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
3069               "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
3070  verifyFormat(
3071      "aaaaaaaaaaa->aaaaaaaaa(\n"
3072      "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3073      "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
3074
3075  verifyFormat(
3076      "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3077      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
3078  verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
3079               "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
3080  verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
3081               "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
3082
3083  // FIXME: Should we break before .a()?
3084  verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3085               "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).a();");
3086
3087  FormatStyle NoBinPacking = getLLVMStyle();
3088  NoBinPacking.BinPackParameters = false;
3089  verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
3090               "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
3091               "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
3092               "                         aaaaaaaaaaaaaaaaaaa,\n"
3093               "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
3094               NoBinPacking);
3095
3096  // If there is a subsequent call, change to hanging indentation.
3097  verifyFormat(
3098      "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3099      "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
3100      "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3101  verifyFormat(
3102      "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3103      "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
3104}
3105
3106TEST_F(FormatTest, WrapsTemplateDeclarations) {
3107  verifyFormat("template <typename T>\n"
3108               "virtual void loooooooooooongFunction(int Param1, int Param2);");
3109  verifyFormat(
3110      "template <typename T>\n"
3111      "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
3112  verifyFormat("template <typename T>\n"
3113               "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
3114               "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
3115  verifyFormat(
3116      "template <typename T>\n"
3117      "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
3118      "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
3119  verifyFormat(
3120      "template <typename T>\n"
3121      "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
3122      "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
3123      "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3124  verifyFormat("template <typename T>\n"
3125               "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3126               "    int aaaaaaaaaaaaaaaaaaaaaa);");
3127  verifyFormat(
3128      "template <typename T1, typename T2 = char, typename T3 = char,\n"
3129      "          typename T4 = char>\n"
3130      "void f();");
3131  verifyFormat(
3132      "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
3133      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3134
3135  verifyFormat("a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
3136               "    a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));");
3137
3138  verifyFormat("template <typename T> class C {};");
3139  verifyFormat("template <typename T> void f();");
3140  verifyFormat("template <typename T> void f() {}");
3141
3142  FormatStyle AlwaysBreak = getLLVMStyle();
3143  AlwaysBreak.AlwaysBreakTemplateDeclarations = true;
3144  verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
3145  verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
3146  verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
3147  verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3148               "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
3149               "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
3150  verifyFormat(
3151      "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
3152      "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3153      "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
3154      "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
3155      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3156      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
3157      "        bbbbbbbbbbbbbbbbbbbbbbbb);",
3158      getLLVMStyleWithColumns(72));
3159}
3160
3161TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
3162  verifyFormat(
3163      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3164      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3165  verifyFormat(
3166      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3167      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3168      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
3169
3170  // FIXME: Should we have the extra indent after the second break?
3171  verifyFormat(
3172      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3173      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3174      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3175
3176  verifyFormat(
3177      "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
3178      "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
3179
3180  // Breaking at nested name specifiers is generally not desirable.
3181  verifyFormat(
3182      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3183      "    aaaaaaaaaaaaaaaaaaaaaaa);");
3184
3185  verifyFormat(
3186      "aaaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3187      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3188      "                   aaaaaaaaaaaaaaaaaaaaa);",
3189      getLLVMStyleWithColumns(74));
3190
3191  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3192               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3193               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3194}
3195
3196TEST_F(FormatTest, UnderstandsTemplateParameters) {
3197  verifyFormat("A<int> a;");
3198  verifyFormat("A<A<A<int> > > a;");
3199  verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
3200  verifyFormat("bool x = a < 1 || 2 > a;");
3201  verifyFormat("bool x = 5 < f<int>();");
3202  verifyFormat("bool x = f<int>() > 5;");
3203  verifyFormat("bool x = 5 < a<int>::x;");
3204  verifyFormat("bool x = a < 4 ? a > 2 : false;");
3205  verifyFormat("bool x = f() ? a < 2 : a > 2;");
3206
3207  verifyGoogleFormat("A<A<int>> a;");
3208  verifyGoogleFormat("A<A<A<int>>> a;");
3209  verifyGoogleFormat("A<A<A<A<int>>>> a;");
3210  verifyGoogleFormat("A<A<int> > a;");
3211  verifyGoogleFormat("A<A<A<int> > > a;");
3212  verifyGoogleFormat("A<A<A<A<int> > > > a;");
3213  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
3214  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
3215
3216  verifyFormat("test >> a >> b;");
3217  verifyFormat("test << a >> b;");
3218
3219  verifyFormat("f<int>();");
3220  verifyFormat("template <typename T> void f() {}");
3221
3222  // Not template parameters.
3223  verifyFormat("return a < b && c > d;");
3224  verifyFormat("void f() {\n"
3225               "  while (a < b && c > d) {\n"
3226               "  }\n"
3227               "}");
3228}
3229
3230TEST_F(FormatTest, UnderstandsBinaryOperators) {
3231  verifyFormat("COMPARE(a, ==, b);");
3232}
3233
3234TEST_F(FormatTest, UnderstandsPointersToMembers) {
3235  verifyFormat("int A::*x;");
3236  verifyFormat("int (S::*func)(void *);");
3237  verifyFormat("void f() { int (S::*func)(void *); }");
3238  verifyFormat("typedef bool *(Class::*Member)() const;");
3239  verifyFormat("void f() {\n"
3240               "  (a->*f)();\n"
3241               "  a->*x;\n"
3242               "  (a.*f)();\n"
3243               "  ((*a).*f)();\n"
3244               "  a.*x;\n"
3245               "}");
3246  FormatStyle Style = getLLVMStyle();
3247  Style.PointerBindsToType = true;
3248  verifyFormat("typedef bool* (Class::*Member)() const;", Style);
3249}
3250
3251TEST_F(FormatTest, UnderstandsUnaryOperators) {
3252  verifyFormat("int a = -2;");
3253  verifyFormat("f(-1, -2, -3);");
3254  verifyFormat("a[-1] = 5;");
3255  verifyFormat("int a = 5 + -2;");
3256  verifyFormat("if (i == -1) {\n}");
3257  verifyFormat("if (i != -1) {\n}");
3258  verifyFormat("if (i > -1) {\n}");
3259  verifyFormat("if (i < -1) {\n}");
3260  verifyFormat("++(a->f());");
3261  verifyFormat("--(a->f());");
3262  verifyFormat("(a->f())++;");
3263  verifyFormat("a[42]++;");
3264  verifyFormat("if (!(a->f())) {\n}");
3265
3266  verifyFormat("a-- > b;");
3267  verifyFormat("b ? -a : c;");
3268  verifyFormat("n * sizeof char16;");
3269  verifyFormat("n * alignof char16;", getGoogleStyle());
3270  verifyFormat("sizeof(char);");
3271  verifyFormat("alignof(char);", getGoogleStyle());
3272
3273  verifyFormat("return -1;");
3274  verifyFormat("switch (a) {\n"
3275               "case -1:\n"
3276               "  break;\n"
3277               "}");
3278  verifyFormat("#define X -1");
3279  verifyFormat("#define X -kConstant");
3280
3281  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { -5, +3 };");
3282  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { +5, -3 };");
3283
3284  verifyFormat("int a = /* confusing comment */ -1;");
3285  // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
3286  verifyFormat("int a = i /* confusing comment */++;");
3287}
3288
3289TEST_F(FormatTest, UndestandsOverloadedOperators) {
3290  verifyFormat("bool operator<();");
3291  verifyFormat("bool operator>();");
3292  verifyFormat("bool operator=();");
3293  verifyFormat("bool operator==();");
3294  verifyFormat("bool operator!=();");
3295  verifyFormat("int operator+();");
3296  verifyFormat("int operator++();");
3297  verifyFormat("bool operator();");
3298  verifyFormat("bool operator()();");
3299  verifyFormat("bool operator[]();");
3300  verifyFormat("operator bool();");
3301  verifyFormat("operator int();");
3302  verifyFormat("operator void *();");
3303  verifyFormat("operator SomeType<int>();");
3304  verifyFormat("operator SomeType<int, int>();");
3305  verifyFormat("operator SomeType<SomeType<int> >();");
3306  verifyFormat("void *operator new(std::size_t size);");
3307  verifyFormat("void *operator new[](std::size_t size);");
3308  verifyFormat("void operator delete(void *ptr);");
3309  verifyFormat("void operator delete[](void *ptr);");
3310  verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
3311               "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
3312
3313  verifyFormat(
3314      "ostream &operator<<(ostream &OutputStream,\n"
3315      "                    SomeReallyLongType WithSomeReallyLongValue);");
3316  verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
3317               "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
3318               "  return left.group < right.group;\n"
3319               "}");
3320  verifyFormat("SomeType &operator=(const SomeType &S);");
3321
3322  verifyGoogleFormat("operator void*();");
3323  verifyGoogleFormat("operator SomeType<SomeType<int>>();");
3324}
3325
3326TEST_F(FormatTest, UnderstandsNewAndDelete) {
3327  verifyFormat("void f() {\n"
3328               "  A *a = new A;\n"
3329               "  A *a = new (placement) A;\n"
3330               "  delete a;\n"
3331               "  delete (A *)a;\n"
3332               "}");
3333}
3334
3335TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
3336  verifyFormat("int *f(int *a) {}");
3337  verifyFormat("int main(int argc, char **argv) {}");
3338  verifyFormat("Test::Test(int b) : a(b * b) {}");
3339  verifyIndependentOfContext("f(a, *a);");
3340  verifyFormat("void g() { f(*a); }");
3341  verifyIndependentOfContext("int a = b * 10;");
3342  verifyIndependentOfContext("int a = 10 * b;");
3343  verifyIndependentOfContext("int a = b * c;");
3344  verifyIndependentOfContext("int a += b * c;");
3345  verifyIndependentOfContext("int a -= b * c;");
3346  verifyIndependentOfContext("int a *= b * c;");
3347  verifyIndependentOfContext("int a /= b * c;");
3348  verifyIndependentOfContext("int a = *b;");
3349  verifyIndependentOfContext("int a = *b * c;");
3350  verifyIndependentOfContext("int a = b * *c;");
3351  verifyIndependentOfContext("return 10 * b;");
3352  verifyIndependentOfContext("return *b * *c;");
3353  verifyIndependentOfContext("return a & ~b;");
3354  verifyIndependentOfContext("f(b ? *c : *d);");
3355  verifyIndependentOfContext("int a = b ? *c : *d;");
3356  verifyIndependentOfContext("*b = a;");
3357  verifyIndependentOfContext("a * ~b;");
3358  verifyIndependentOfContext("a * !b;");
3359  verifyIndependentOfContext("a * +b;");
3360  verifyIndependentOfContext("a * -b;");
3361  verifyIndependentOfContext("a * ++b;");
3362  verifyIndependentOfContext("a * --b;");
3363  verifyIndependentOfContext("a[4] * b;");
3364  verifyIndependentOfContext("a[a * a] = 1;");
3365  verifyIndependentOfContext("f() * b;");
3366  verifyIndependentOfContext("a * [self dostuff];");
3367  verifyIndependentOfContext("int x = a * (a + b);");
3368  verifyIndependentOfContext("(a *)(a + b);");
3369  verifyIndependentOfContext("int *pa = (int *)&a;");
3370  verifyIndependentOfContext("return sizeof(int **);");
3371  verifyIndependentOfContext("return sizeof(int ******);");
3372  verifyIndependentOfContext("return (int **&)a;");
3373  verifyIndependentOfContext("f((*PointerToArray)[10]);");
3374  verifyFormat("void f(Type (*parameter)[10]) {}");
3375  verifyGoogleFormat("return sizeof(int**);");
3376  verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
3377  verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
3378  verifyFormat("auto a = [](int **&, int ***) {};");
3379
3380  verifyIndependentOfContext("InvalidRegions[*R] = 0;");
3381
3382  verifyIndependentOfContext("A<int *> a;");
3383  verifyIndependentOfContext("A<int **> a;");
3384  verifyIndependentOfContext("A<int *, int *> a;");
3385  verifyIndependentOfContext(
3386      "const char *const p = reinterpret_cast<const char *const>(q);");
3387  verifyIndependentOfContext("A<int **, int **> a;");
3388  verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
3389  verifyFormat("for (char **a = b; *a; ++a) {\n}");
3390  verifyFormat("for (; a && b;) {\n}");
3391
3392  verifyFormat(
3393      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3394      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3395
3396  verifyGoogleFormat("int main(int argc, char** argv) {}");
3397  verifyGoogleFormat("A<int*> a;");
3398  verifyGoogleFormat("A<int**> a;");
3399  verifyGoogleFormat("A<int*, int*> a;");
3400  verifyGoogleFormat("A<int**, int**> a;");
3401  verifyGoogleFormat("f(b ? *c : *d);");
3402  verifyGoogleFormat("int a = b ? *c : *d;");
3403  verifyGoogleFormat("Type* t = **x;");
3404  verifyGoogleFormat("Type* t = *++*x;");
3405  verifyGoogleFormat("*++*x;");
3406  verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
3407  verifyGoogleFormat("Type* t = x++ * y;");
3408  verifyGoogleFormat(
3409      "const char* const p = reinterpret_cast<const char* const>(q);");
3410
3411  verifyIndependentOfContext("a = *(x + y);");
3412  verifyIndependentOfContext("a = &(x + y);");
3413  verifyIndependentOfContext("*(x + y).call();");
3414  verifyIndependentOfContext("&(x + y)->call();");
3415  verifyFormat("void f() { &(*I).first; }");
3416
3417  verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
3418  verifyFormat(
3419      "int *MyValues = {\n"
3420      "  *A, // Operator detection might be confused by the '{'\n"
3421      "  *BB // Operator detection might be confused by previous comment\n"
3422      "};");
3423
3424  verifyIndependentOfContext("if (int *a = &b)");
3425  verifyIndependentOfContext("if (int &a = *b)");
3426  verifyIndependentOfContext("if (a & b[i])");
3427  verifyIndependentOfContext("if (a::b::c::d & b[i])");
3428  verifyIndependentOfContext("if (*b[i])");
3429  verifyIndependentOfContext("if (int *a = (&b))");
3430  verifyIndependentOfContext("while (int *a = &b)");
3431  verifyFormat("void f() {\n"
3432               "  for (const int &v : Values) {\n"
3433               "  }\n"
3434               "}");
3435  verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
3436  verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
3437
3438  verifyFormat("#define MACRO     \\\n"
3439               "  int *i = a * b; \\\n"
3440               "  void f(a *b);",
3441               getLLVMStyleWithColumns(19));
3442
3443  verifyIndependentOfContext("A = new SomeType *[Length];");
3444  verifyIndependentOfContext("A = new SomeType *[Length]();");
3445  verifyIndependentOfContext("T **t = new T *;");
3446  verifyIndependentOfContext("T **t = new T *();");
3447  verifyGoogleFormat("A = new SomeType* [Length]();");
3448  verifyGoogleFormat("A = new SomeType* [Length];");
3449  verifyGoogleFormat("T** t = new T*;");
3450  verifyGoogleFormat("T** t = new T*();");
3451
3452  FormatStyle PointerLeft = getLLVMStyle();
3453  PointerLeft.PointerBindsToType = true;
3454  verifyFormat("delete *x;", PointerLeft);
3455}
3456
3457TEST_F(FormatTest, UnderstandsEllipsis) {
3458  verifyFormat("int printf(const char *fmt, ...);");
3459  verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
3460  verifyFormat("template <class... Ts> void Foo(Ts *... ts) {}");
3461
3462  FormatStyle PointersLeft = getLLVMStyle();
3463  PointersLeft.PointerBindsToType = true;
3464  verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", PointersLeft);
3465}
3466
3467TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
3468  EXPECT_EQ("int *a;\n"
3469            "int *a;\n"
3470            "int *a;",
3471            format("int *a;\n"
3472                   "int* a;\n"
3473                   "int *a;",
3474                   getGoogleStyle()));
3475  EXPECT_EQ("int* a;\n"
3476            "int* a;\n"
3477            "int* a;",
3478            format("int* a;\n"
3479                   "int* a;\n"
3480                   "int *a;",
3481                   getGoogleStyle()));
3482  EXPECT_EQ("int *a;\n"
3483            "int *a;\n"
3484            "int *a;",
3485            format("int *a;\n"
3486                   "int * a;\n"
3487                   "int *  a;",
3488                   getGoogleStyle()));
3489}
3490
3491TEST_F(FormatTest, UnderstandsRvalueReferences) {
3492  verifyFormat("int f(int &&a) {}");
3493  verifyFormat("int f(int a, char &&b) {}");
3494  verifyFormat("void f() { int &&a = b; }");
3495  verifyGoogleFormat("int f(int a, char&& b) {}");
3496  verifyGoogleFormat("void f() { int&& a = b; }");
3497
3498  verifyIndependentOfContext("A<int &&> a;");
3499  verifyIndependentOfContext("A<int &&, int &&> a;");
3500  verifyGoogleFormat("A<int&&> a;");
3501  verifyGoogleFormat("A<int&&, int&&> a;");
3502}
3503
3504TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
3505  verifyFormat("void f() {\n"
3506               "  x[aaaaaaaaa -\n"
3507               "    b] = 23;\n"
3508               "}",
3509               getLLVMStyleWithColumns(15));
3510}
3511
3512TEST_F(FormatTest, FormatsCasts) {
3513  verifyFormat("Type *A = static_cast<Type *>(P);");
3514  verifyFormat("Type *A = (Type *)P;");
3515  verifyFormat("Type *A = (vector<Type *, int *>)P;");
3516  verifyFormat("int a = (int)(2.0f);");
3517  verifyFormat("int a = (int)2.0f;");
3518  verifyFormat("x[(int32)y];");
3519  verifyFormat("x = (int32)y;");
3520  verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
3521  verifyFormat("int a = (int)*b;");
3522  verifyFormat("int a = (int)2.0f;");
3523  verifyFormat("int a = (int)~0;");
3524  verifyFormat("int a = (int)++a;");
3525  verifyFormat("int a = (int)sizeof(int);");
3526  verifyFormat("int a = (int)+2;");
3527  verifyFormat("my_int a = (my_int)2.0f;");
3528  verifyFormat("my_int a = (my_int)sizeof(int);");
3529  verifyFormat("return (my_int)aaa;");
3530
3531  // FIXME: Without type knowledge, this can still fall apart miserably.
3532  verifyFormat("void f() { my_int a = (my_int) * b; }");
3533  verifyFormat("void f() { return P ? (my_int) * P : (my_int)0; }");
3534  verifyFormat("my_int a = (my_int) ~0;");
3535  verifyFormat("my_int a = (my_int)++ a;");
3536  verifyFormat("my_int a = (my_int) + 2;");
3537
3538  // These are not casts.
3539  verifyFormat("void f(int *) {}");
3540  verifyFormat("f(foo)->b;");
3541  verifyFormat("f(foo).b;");
3542  verifyFormat("f(foo)(b);");
3543  verifyFormat("f(foo)[b];");
3544  verifyFormat("[](foo) { return 4; }(bar)];");
3545  verifyFormat("(*funptr)(foo)[4];");
3546  verifyFormat("funptrs[4](foo)[4];");
3547  verifyFormat("void f(int *);");
3548  verifyFormat("void f(int *) = 0;");
3549  verifyFormat("void f(SmallVector<int>) {}");
3550  verifyFormat("void f(SmallVector<int>);");
3551  verifyFormat("void f(SmallVector<int>) = 0;");
3552  verifyFormat("void f(int i = (kValue) * kMask) {}");
3553  verifyFormat("void f(int i = (kA * kB) & kMask) {}");
3554  verifyFormat("int a = sizeof(int) * b;");
3555  verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
3556  verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
3557  verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
3558  verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
3559
3560  // These are not casts, but at some point were confused with casts.
3561  verifyFormat("virtual void foo(int *) override;");
3562  verifyFormat("virtual void foo(char &) const;");
3563  verifyFormat("virtual void foo(int *a, char *) const;");
3564  verifyFormat("int a = sizeof(int *) + b;");
3565  verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
3566
3567  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
3568               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
3569  verifyFormat(
3570      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[\n"
3571      "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] =\n"
3572      "    (*cccccccccccccccc)[\n"
3573      "        dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
3574}
3575
3576TEST_F(FormatTest, FormatsFunctionTypes) {
3577  verifyFormat("A<bool()> a;");
3578  verifyFormat("A<SomeType()> a;");
3579  verifyFormat("A<void (*)(int, std::string)> a;");
3580  verifyFormat("A<void *(int)>;");
3581  verifyFormat("void *(*a)(int *, SomeType *);");
3582  verifyFormat("int (*func)(void *);");
3583  verifyFormat("void f() { int (*func)(void *); }");
3584
3585  verifyGoogleFormat("A<void*(int*, SomeType*)>;");
3586  verifyGoogleFormat("void* (*a)(int);");
3587
3588  // Other constructs can look somewhat like function types:
3589  verifyFormat("A<sizeof(*x)> a;");
3590  verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
3591}
3592
3593TEST_F(FormatTest, BreaksLongDeclarations) {
3594  verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
3595               "    AnotherNameForTheLongType;",
3596               getGoogleStyle());
3597  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
3598               "    LoooooooooooooooooooooooooooooooooooooooongVariable;",
3599               getGoogleStyle());
3600  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
3601               "    LoooooooooooooooooooooooooooooooooooooooongVariable;",
3602               getGoogleStyle());
3603  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
3604               "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
3605               getGoogleStyle());
3606  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
3607               "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
3608  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
3609               "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
3610
3611  // FIXME: Without the comment, this breaks after "(".
3612  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
3613               "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
3614               getGoogleStyle());
3615
3616  verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
3617               "                  int LoooooooooooooooooooongParam2) {}");
3618  verifyFormat(
3619      "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
3620      "                                   SourceLocation L, IdentifierIn *II,\n"
3621      "                                   Type *T) {}");
3622  verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
3623               "ReallyReallyLongFunctionName(\n"
3624               "    const std::string &SomeParameter,\n"
3625               "    const SomeType<string, SomeOtherTemplateParameter> &\n"
3626               "        ReallyReallyLongParameterName,\n"
3627               "    const SomeType<string, SomeOtherTemplateParameter> &\n"
3628               "        AnotherLongParameterName) {}");
3629  verifyFormat("template <typename A>\n"
3630               "SomeLoooooooooooooooooooooongType<\n"
3631               "    typename some_namespace::SomeOtherType<A>::Type>\n"
3632               "Function() {}");
3633  verifyFormat(
3634      "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
3635      "    aaaaaaaaaaaaaaaaaaaaaaa;",
3636      getGoogleStyle());
3637
3638  verifyGoogleFormat(
3639      "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
3640      "                                   SourceLocation L) {}");
3641  verifyGoogleFormat(
3642      "some_namespace::LongReturnType\n"
3643      "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
3644      "    int first_long_parameter, int second_parameter) {}");
3645
3646  verifyGoogleFormat("template <typename T>\n"
3647                     "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
3648                     "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
3649  verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3650                     "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
3651}
3652
3653TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
3654  verifyFormat("(a)->b();");
3655  verifyFormat("--a;");
3656}
3657
3658TEST_F(FormatTest, HandlesIncludeDirectives) {
3659  verifyFormat("#include <string>\n"
3660               "#include <a/b/c.h>\n"
3661               "#include \"a/b/string\"\n"
3662               "#include \"string.h\"\n"
3663               "#include \"string.h\"\n"
3664               "#include <a-a>\n"
3665               "#include < path with space >\n"
3666               "#include \"abc.h\" // this is included for ABC\n"
3667               "#include \"some long include\" // with a comment\n"
3668               "#include \"some very long include paaaaaaaaaaaaaaaaaaaaaaath\"",
3669               getLLVMStyleWithColumns(35));
3670
3671  verifyFormat("#import <string>");
3672  verifyFormat("#import <a/b/c.h>");
3673  verifyFormat("#import \"a/b/string\"");
3674  verifyFormat("#import \"string.h\"");
3675  verifyFormat("#import \"string.h\"");
3676}
3677
3678//===----------------------------------------------------------------------===//
3679// Error recovery tests.
3680//===----------------------------------------------------------------------===//
3681
3682TEST_F(FormatTest, IncompleteParameterLists) {
3683  FormatStyle NoBinPacking = getLLVMStyle();
3684  NoBinPacking.BinPackParameters = false;
3685  verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
3686               "                        double *min_x,\n"
3687               "                        double *max_x,\n"
3688               "                        double *min_y,\n"
3689               "                        double *max_y,\n"
3690               "                        double *min_z,\n"
3691               "                        double *max_z, ) {}",
3692               NoBinPacking);
3693}
3694
3695TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
3696  verifyFormat("void f() { return; }\n42");
3697  verifyFormat("void f() {\n"
3698               "  if (0)\n"
3699               "    return;\n"
3700               "}\n"
3701               "42");
3702  verifyFormat("void f() { return }\n42");
3703  verifyFormat("void f() {\n"
3704               "  if (0)\n"
3705               "    return\n"
3706               "}\n"
3707               "42");
3708}
3709
3710TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
3711  EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
3712  EXPECT_EQ("void f() {\n"
3713            "  if (a)\n"
3714            "    return\n"
3715            "}",
3716            format("void  f  (  )  {  if  ( a )  return  }"));
3717  EXPECT_EQ("namespace N {\n"
3718            "void f()\n"
3719            "}",
3720            format("namespace  N  {  void f()  }"));
3721  EXPECT_EQ("namespace N {\n"
3722            "void f() {}\n"
3723            "void g()\n"
3724            "}",
3725            format("namespace N  { void f( ) { } void g( ) }"));
3726}
3727
3728TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
3729  verifyFormat("int aaaaaaaa =\n"
3730               "    // Overlylongcomment\n"
3731               "    b;",
3732               getLLVMStyleWithColumns(20));
3733  verifyFormat("function(\n"
3734               "    ShortArgument,\n"
3735               "    LoooooooooooongArgument);\n",
3736               getLLVMStyleWithColumns(20));
3737}
3738
3739TEST_F(FormatTest, IncorrectAccessSpecifier) {
3740  verifyFormat("public:");
3741  verifyFormat("class A {\n"
3742               "public\n"
3743               "  void f() {}\n"
3744               "};");
3745  verifyFormat("public\n"
3746               "int qwerty;");
3747  verifyFormat("public\n"
3748               "B {}");
3749  verifyFormat("public\n"
3750               "{}");
3751  verifyFormat("public\n"
3752               "B { int x; }");
3753}
3754
3755TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
3756  verifyFormat("{");
3757  verifyFormat("#})");
3758}
3759
3760TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
3761  verifyFormat("do {\n}");
3762  verifyFormat("do {\n}\n"
3763               "f();");
3764  verifyFormat("do {\n}\n"
3765               "wheeee(fun);");
3766  verifyFormat("do {\n"
3767               "  f();\n"
3768               "}");
3769}
3770
3771TEST_F(FormatTest, IncorrectCodeMissingParens) {
3772  verifyFormat("if {\n  foo;\n  foo();\n}");
3773  verifyFormat("switch {\n  foo;\n  foo();\n}");
3774  verifyFormat("for {\n  foo;\n  foo();\n}");
3775  verifyFormat("while {\n  foo;\n  foo();\n}");
3776  verifyFormat("do {\n  foo;\n  foo();\n} while;");
3777}
3778
3779TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
3780  verifyFormat("namespace {\n"
3781               "class Foo {  Foo  (\n"
3782               "};\n"
3783               "} // comment");
3784}
3785
3786TEST_F(FormatTest, IncorrectCodeErrorDetection) {
3787  EXPECT_EQ("{\n{}\n", format("{\n{\n}\n"));
3788  EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
3789  EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
3790  EXPECT_EQ("{\n  {}\n  }\n}\n", format("{\n  {\n    }\n  }\n}\n"));
3791
3792  EXPECT_EQ("{\n"
3793            "    {\n"
3794            " breakme(\n"
3795            "     qwe);\n"
3796            "}\n",
3797            format("{\n"
3798                   "    {\n"
3799                   " breakme(qwe);\n"
3800                   "}\n",
3801                   getLLVMStyleWithColumns(10)));
3802}
3803
3804TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
3805  verifyFormat("int x = {\n"
3806               "  avariable,\n"
3807               "  b(alongervariable)\n"
3808               "};",
3809               getLLVMStyleWithColumns(25));
3810}
3811
3812TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
3813  verifyFormat("return (a)(b) { 1, 2, 3 };");
3814}
3815
3816TEST_F(FormatTest, LayoutCxx11ConstructorBraceInitializers) {
3817    verifyFormat("vector<int> x{ 1, 2, 3, 4 };");
3818    verifyFormat("vector<T> x{ {}, {}, {}, {} };");
3819    verifyFormat("f({ 1, 2 });");
3820    verifyFormat("auto v = Foo{ 1 };");
3821    verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });");
3822    verifyFormat("Class::Class : member{ 1, 2, 3 } {}");
3823    verifyFormat("new vector<int>{ 1, 2, 3 };");
3824    verifyFormat("new int[3]{ 1, 2, 3 };");
3825    verifyFormat("return { arg1, arg2 };");
3826    verifyFormat("return { arg1, SomeType{ parameter } };");
3827    verifyFormat("new T{ arg1, arg2 };");
3828    verifyFormat("class Class {\n"
3829                 "  T member = { arg1, arg2 };\n"
3830                 "};");
3831    verifyFormat(
3832        "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3833        "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
3834        "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
3835        "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };");
3836    verifyFormat("DoSomethingWithVector({} /* No data */);");
3837    verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });");
3838    verifyFormat(
3839        "someFunction(OtherParam, BracedList{\n"
3840        "                           // comment 1 (Forcing interesting break)\n"
3841        "                           param1, param2,\n"
3842        "                           // comment 2\n"
3843        "                           param3, param4\n"
3844        "                         });");
3845
3846    FormatStyle NoSpaces = getLLVMStyle();
3847    NoSpaces.SpacesInBracedLists = false;
3848    verifyFormat("vector<int> x{1, 2, 3, 4};", NoSpaces);
3849    verifyFormat("vector<T> x{{}, {}, {}, {}};", NoSpaces);
3850    verifyFormat("f({1, 2});", NoSpaces);
3851    verifyFormat("auto v = Foo{-1};", NoSpaces);
3852    verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});", NoSpaces);
3853    verifyFormat("Class::Class : member{1, 2, 3} {}", NoSpaces);
3854    verifyFormat("new vector<int>{1, 2, 3};", NoSpaces);
3855    verifyFormat("new int[3]{1, 2, 3};", NoSpaces);
3856    verifyFormat("return {arg1, arg2};", NoSpaces);
3857    verifyFormat("return {arg1, SomeType{parameter}};", NoSpaces);
3858    verifyFormat("new T{arg1, arg2};", NoSpaces);
3859    verifyFormat("class Class {\n"
3860                 "  T member = {arg1, arg2};\n"
3861                 "};",
3862                 NoSpaces);
3863}
3864
3865TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
3866  verifyFormat("void f() { return 42; }");
3867  verifyFormat("void f() {\n"
3868               "  // Comment\n"
3869               "}");
3870  verifyFormat("{\n"
3871               "#error {\n"
3872               "  int a;\n"
3873               "}");
3874  verifyFormat("{\n"
3875               "  int a;\n"
3876               "#error {\n"
3877               "}");
3878  verifyFormat("void f() {} // comment");
3879  verifyFormat("void f() { int a; } // comment");
3880  verifyFormat("void f() {\n"
3881               "} // comment",
3882               getLLVMStyleWithColumns(15));
3883
3884  verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
3885  verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
3886
3887  verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
3888  verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
3889}
3890
3891TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
3892  // Elaborate type variable declarations.
3893  verifyFormat("struct foo a = { bar };\nint n;");
3894  verifyFormat("class foo a = { bar };\nint n;");
3895  verifyFormat("union foo a = { bar };\nint n;");
3896
3897  // Elaborate types inside function definitions.
3898  verifyFormat("struct foo f() {}\nint n;");
3899  verifyFormat("class foo f() {}\nint n;");
3900  verifyFormat("union foo f() {}\nint n;");
3901
3902  // Templates.
3903  verifyFormat("template <class X> void f() {}\nint n;");
3904  verifyFormat("template <struct X> void f() {}\nint n;");
3905  verifyFormat("template <union X> void f() {}\nint n;");
3906
3907  // Actual definitions...
3908  verifyFormat("struct {\n} n;");
3909  verifyFormat(
3910      "template <template <class T, class Y>, class Z> class X {\n} n;");
3911  verifyFormat("union Z {\n  int n;\n} x;");
3912  verifyFormat("class MACRO Z {\n} n;");
3913  verifyFormat("class MACRO(X) Z {\n} n;");
3914  verifyFormat("class __attribute__(X) Z {\n} n;");
3915  verifyFormat("class __declspec(X) Z {\n} n;");
3916  verifyFormat("class A##B##C {\n} n;");
3917
3918  // Redefinition from nested context:
3919  verifyFormat("class A::B::C {\n} n;");
3920
3921  // Template definitions.
3922  verifyFormat(
3923      "template <typename F>\n"
3924      "Matcher(const Matcher<F> &Other,\n"
3925      "        typename enable_if_c<is_base_of<F, T>::value &&\n"
3926      "                             !is_same<F, T>::value>::type * = 0)\n"
3927      "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
3928
3929  // FIXME: This is still incorrectly handled at the formatter side.
3930  verifyFormat("template <> struct X < 15, i < 3 && 42 < 50 && 33<28> {};");
3931
3932  // FIXME:
3933  // This now gets parsed incorrectly as class definition.
3934  // verifyFormat("class A<int> f() {\n}\nint n;");
3935
3936  // Elaborate types where incorrectly parsing the structural element would
3937  // break the indent.
3938  verifyFormat("if (true)\n"
3939               "  class X x;\n"
3940               "else\n"
3941               "  f();\n");
3942
3943  // This is simply incomplete. Formatting is not important, but must not crash.
3944  verifyFormat("class A:");
3945}
3946
3947TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
3948  verifyFormat("#error Leave     all         white!!!!! space* alone!\n");
3949  verifyFormat("#warning Leave     all         white!!!!! space* alone!\n");
3950  EXPECT_EQ("#error 1", format("  #  error   1"));
3951  EXPECT_EQ("#warning 1", format("  #  warning 1"));
3952}
3953
3954TEST_F(FormatTest, FormatHashIfExpressions) {
3955  // FIXME: Come up with a better indentation for #elif.
3956  verifyFormat(
3957      "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
3958      "    defined(BBBBBBBB)\n"
3959      "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
3960      "    defined(BBBBBBBB)\n"
3961      "#endif",
3962      getLLVMStyleWithColumns(65));
3963}
3964
3965TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
3966  FormatStyle AllowsMergedIf = getGoogleStyle();
3967  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
3968  verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
3969  verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
3970  verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
3971  EXPECT_EQ("if (true) return 42;",
3972            format("if (true)\nreturn 42;", AllowsMergedIf));
3973  FormatStyle ShortMergedIf = AllowsMergedIf;
3974  ShortMergedIf.ColumnLimit = 25;
3975  verifyFormat("#define A \\\n"
3976               "  if (true) return 42;",
3977               ShortMergedIf);
3978  verifyFormat("#define A \\\n"
3979               "  f();    \\\n"
3980               "  if (true)\n"
3981               "#define B",
3982               ShortMergedIf);
3983  verifyFormat("#define A \\\n"
3984               "  f();    \\\n"
3985               "  if (true)\n"
3986               "g();",
3987               ShortMergedIf);
3988  verifyFormat("{\n"
3989               "#ifdef A\n"
3990               "  // Comment\n"
3991               "  if (true) continue;\n"
3992               "#endif\n"
3993               "  // Comment\n"
3994               "  if (true) continue;",
3995               ShortMergedIf);
3996}
3997
3998TEST_F(FormatTest, BlockCommentsInControlLoops) {
3999  verifyFormat("if (0) /* a comment in a strange place */ {\n"
4000               "  f();\n"
4001               "}");
4002  verifyFormat("if (0) /* a comment in a strange place */ {\n"
4003               "  f();\n"
4004               "} /* another comment */ else /* comment #3 */ {\n"
4005               "  g();\n"
4006               "}");
4007  verifyFormat("while (0) /* a comment in a strange place */ {\n"
4008               "  f();\n"
4009               "}");
4010  verifyFormat("for (;;) /* a comment in a strange place */ {\n"
4011               "  f();\n"
4012               "}");
4013  verifyFormat("do /* a comment in a strange place */ {\n"
4014               "  f();\n"
4015               "} /* another comment */ while (0);");
4016}
4017
4018TEST_F(FormatTest, BlockComments) {
4019  EXPECT_EQ("/* */ /* */ /* */\n/* */ /* */ /* */",
4020            format("/* *//* */  /* */\n/* *//* */  /* */"));
4021  EXPECT_EQ("/* */ a /* */ b;", format("  /* */  a/* */  b;"));
4022  EXPECT_EQ("#define A /*123*/\\\n"
4023            "  b\n"
4024            "/* */\n"
4025            "someCall(\n"
4026            "    parameter);",
4027            format("#define A /*123*/ b\n"
4028                   "/* */\n"
4029                   "someCall(parameter);",
4030                   getLLVMStyleWithColumns(15)));
4031
4032  EXPECT_EQ("#define A\n"
4033            "/* */ someCall(\n"
4034            "    parameter);",
4035            format("#define A\n"
4036                   "/* */someCall(parameter);",
4037                   getLLVMStyleWithColumns(15)));
4038  EXPECT_EQ("/*\n**\n*/", format("/*\n**\n*/"));
4039  EXPECT_EQ("/*\n"
4040            "*\n"
4041            " * aaaaaa\n"
4042            "*aaaaaa\n"
4043            "*/",
4044            format("/*\n"
4045                   "*\n"
4046                   " * aaaaaa aaaaaa\n"
4047                   "*/",
4048                   getLLVMStyleWithColumns(10)));
4049  EXPECT_EQ("/*\n"
4050            "**\n"
4051            "* aaaaaa\n"
4052            "*aaaaaa\n"
4053            "*/",
4054            format("/*\n"
4055                   "**\n"
4056                   "* aaaaaa aaaaaa\n"
4057                   "*/",
4058                   getLLVMStyleWithColumns(10)));
4059
4060  FormatStyle NoBinPacking = getLLVMStyle();
4061  NoBinPacking.BinPackParameters = false;
4062  EXPECT_EQ("someFunction(1, /* comment 1 */\n"
4063            "             2, /* comment 2 */\n"
4064            "             3, /* comment 3 */\n"
4065            "             aaaa,\n"
4066            "             bbbb);",
4067            format("someFunction (1,   /* comment 1 */\n"
4068                   "                2, /* comment 2 */  \n"
4069                   "               3,   /* comment 3 */\n"
4070                   "aaaa, bbbb );",
4071                   NoBinPacking));
4072  verifyFormat(
4073      "bool aaaaaaaaaaaaa = /* comment: */ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4074      "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4075  EXPECT_EQ(
4076      "bool aaaaaaaaaaaaa = /* trailing comment */\n"
4077      "    aaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4078      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;",
4079      format(
4080          "bool       aaaaaaaaaaaaa =       /* trailing comment */\n"
4081          "    aaaaaaaaaaaaaaaaaaaaaaaaaaa||aaaaaaaaaaaaaaaaaaaaaaaaa    ||\n"
4082          "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa   || aaaaaaaaaaaaaaaaaaaaaaaaaa;"));
4083  EXPECT_EQ(
4084      "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
4085      "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   /* comment */\n"
4086      "int cccccccccccccccccccccccccccccc;       /* comment */\n",
4087      format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
4088             "int      bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n"
4089             "int    cccccccccccccccccccccccccccccc;  /* comment */\n"));
4090
4091  verifyFormat("void f(int * /* unused */) {}");
4092
4093  EXPECT_EQ("/*\n"
4094            " **\n"
4095            " */",
4096            format("/*\n"
4097                   " **\n"
4098                   " */"));
4099  EXPECT_EQ("/*\n"
4100            " *q\n"
4101            " */",
4102            format("/*\n"
4103                   " *q\n"
4104                   " */"));
4105  EXPECT_EQ("/*\n"
4106            " * q\n"
4107            " */",
4108            format("/*\n"
4109                   " * q\n"
4110                   " */"));
4111  EXPECT_EQ("/*\n"
4112            " **/",
4113            format("/*\n"
4114                   " **/"));
4115  EXPECT_EQ("/*\n"
4116            " ***/",
4117            format("/*\n"
4118                   " ***/"));
4119}
4120
4121TEST_F(FormatTest, BlockCommentsInMacros) {
4122  EXPECT_EQ("#define A          \\\n"
4123            "  {                \\\n"
4124            "    /* one line */ \\\n"
4125            "    someCall();",
4126            format("#define A {        \\\n"
4127                   "  /* one line */   \\\n"
4128                   "  someCall();",
4129                   getLLVMStyleWithColumns(20)));
4130  EXPECT_EQ("#define A          \\\n"
4131            "  {                \\\n"
4132            "    /* previous */ \\\n"
4133            "    /* one line */ \\\n"
4134            "    someCall();",
4135            format("#define A {        \\\n"
4136                   "  /* previous */   \\\n"
4137                   "  /* one line */   \\\n"
4138                   "  someCall();",
4139                   getLLVMStyleWithColumns(20)));
4140}
4141
4142TEST_F(FormatTest, BlockCommentsAtEndOfLine) {
4143  EXPECT_EQ("a = {\n"
4144            "  1111 /*    */\n"
4145            "};",
4146            format("a = {1111 /*    */\n"
4147                   "};",
4148                   getLLVMStyleWithColumns(15)));
4149  EXPECT_EQ("a = {\n"
4150            "  1111 /*      */\n"
4151            "};",
4152            format("a = {1111 /*      */\n"
4153                   "};",
4154                   getLLVMStyleWithColumns(15)));
4155
4156  // FIXME: The formatting is still wrong here.
4157  EXPECT_EQ("a = {\n"
4158            "  1111 /*      a\n"
4159            "          */\n"
4160            "};",
4161            format("a = {1111 /*      a */\n"
4162                   "};",
4163                   getLLVMStyleWithColumns(15)));
4164}
4165
4166TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
4167  // FIXME: This is not what we want...
4168  verifyFormat("{\n"
4169               "// a"
4170               "// b");
4171}
4172
4173TEST_F(FormatTest, FormatStarDependingOnContext) {
4174  verifyFormat("void f(int *a);");
4175  verifyFormat("void f() { f(fint * b); }");
4176  verifyFormat("class A {\n  void f(int *a);\n};");
4177  verifyFormat("class A {\n  int *a;\n};");
4178  verifyFormat("namespace a {\n"
4179               "namespace b {\n"
4180               "class A {\n"
4181               "  void f() {}\n"
4182               "  int *a;\n"
4183               "};\n"
4184               "}\n"
4185               "}");
4186}
4187
4188TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
4189  verifyFormat("while");
4190  verifyFormat("operator");
4191}
4192
4193//===----------------------------------------------------------------------===//
4194// Objective-C tests.
4195//===----------------------------------------------------------------------===//
4196
4197TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
4198  verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
4199  EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
4200            format("-(NSUInteger)indexOfObject:(id)anObject;"));
4201  EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
4202  EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
4203  EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
4204            format("-(NSInteger)Method3:(id)anObject;"));
4205  EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
4206            format("-(NSInteger)Method4:(id)anObject;"));
4207  EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
4208            format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
4209  EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
4210            format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
4211  EXPECT_EQ(
4212      "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;",
4213      format(
4214          "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;"));
4215
4216  // Very long objectiveC method declaration.
4217  verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
4218               "                    inRange:(NSRange)range\n"
4219               "                   outRange:(NSRange)out_range\n"
4220               "                  outRange1:(NSRange)out_range1\n"
4221               "                  outRange2:(NSRange)out_range2\n"
4222               "                  outRange3:(NSRange)out_range3\n"
4223               "                  outRange4:(NSRange)out_range4\n"
4224               "                  outRange5:(NSRange)out_range5\n"
4225               "                  outRange6:(NSRange)out_range6\n"
4226               "                  outRange7:(NSRange)out_range7\n"
4227               "                  outRange8:(NSRange)out_range8\n"
4228               "                  outRange9:(NSRange)out_range9;");
4229
4230  verifyFormat("- (int)sum:(vector<int>)numbers;");
4231  verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
4232  // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
4233  // protocol lists (but not for template classes):
4234  //verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
4235
4236  verifyFormat("- (int (*)())foo:(int (*)())f;");
4237  verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
4238
4239  // If there's no return type (very rare in practice!), LLVM and Google style
4240  // agree.
4241  verifyFormat("- foo;");
4242  verifyFormat("- foo:(int)f;");
4243  verifyGoogleFormat("- foo:(int)foo;");
4244}
4245
4246TEST_F(FormatTest, FormatObjCBlocks) {
4247  verifyFormat("int (^Block)(int, int);");
4248  verifyFormat("int (^Block1)(int, int) = ^(int i, int j)");
4249}
4250
4251TEST_F(FormatTest, FormatObjCInterface) {
4252  verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
4253               "@public\n"
4254               "  int field1;\n"
4255               "@protected\n"
4256               "  int field2;\n"
4257               "@private\n"
4258               "  int field3;\n"
4259               "@package\n"
4260               "  int field4;\n"
4261               "}\n"
4262               "+ (id)init;\n"
4263               "@end");
4264
4265  verifyGoogleFormat("@interface Foo : NSObject<NSSomeDelegate> {\n"
4266                     " @public\n"
4267                     "  int field1;\n"
4268                     " @protected\n"
4269                     "  int field2;\n"
4270                     " @private\n"
4271                     "  int field3;\n"
4272                     " @package\n"
4273                     "  int field4;\n"
4274                     "}\n"
4275                     "+ (id)init;\n"
4276                     "@end");
4277
4278  verifyFormat("@interface /* wait for it */ Foo\n"
4279               "+ (id)init;\n"
4280               "// Look, a comment!\n"
4281               "- (int)answerWith:(int)i;\n"
4282               "@end");
4283
4284  verifyFormat("@interface Foo\n"
4285               "@end\n"
4286               "@interface Bar\n"
4287               "@end");
4288
4289  verifyFormat("@interface Foo : Bar\n"
4290               "+ (id)init;\n"
4291               "@end");
4292
4293  verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
4294               "+ (id)init;\n"
4295               "@end");
4296
4297  verifyGoogleFormat("@interface Foo : Bar<Baz, Quux>\n"
4298                     "+ (id)init;\n"
4299                     "@end");
4300
4301  verifyFormat("@interface Foo (HackStuff)\n"
4302               "+ (id)init;\n"
4303               "@end");
4304
4305  verifyFormat("@interface Foo ()\n"
4306               "+ (id)init;\n"
4307               "@end");
4308
4309  verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
4310               "+ (id)init;\n"
4311               "@end");
4312
4313  verifyGoogleFormat("@interface Foo (HackStuff)<MyProtocol>\n"
4314                     "+ (id)init;\n"
4315                     "@end");
4316
4317  verifyFormat("@interface Foo {\n"
4318               "  int _i;\n"
4319               "}\n"
4320               "+ (id)init;\n"
4321               "@end");
4322
4323  verifyFormat("@interface Foo : Bar {\n"
4324               "  int _i;\n"
4325               "}\n"
4326               "+ (id)init;\n"
4327               "@end");
4328
4329  verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
4330               "  int _i;\n"
4331               "}\n"
4332               "+ (id)init;\n"
4333               "@end");
4334
4335  verifyFormat("@interface Foo (HackStuff) {\n"
4336               "  int _i;\n"
4337               "}\n"
4338               "+ (id)init;\n"
4339               "@end");
4340
4341  verifyFormat("@interface Foo () {\n"
4342               "  int _i;\n"
4343               "}\n"
4344               "+ (id)init;\n"
4345               "@end");
4346
4347  verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
4348               "  int _i;\n"
4349               "}\n"
4350               "+ (id)init;\n"
4351               "@end");
4352}
4353
4354TEST_F(FormatTest, FormatObjCImplementation) {
4355  verifyFormat("@implementation Foo : NSObject {\n"
4356               "@public\n"
4357               "  int field1;\n"
4358               "@protected\n"
4359               "  int field2;\n"
4360               "@private\n"
4361               "  int field3;\n"
4362               "@package\n"
4363               "  int field4;\n"
4364               "}\n"
4365               "+ (id)init {\n}\n"
4366               "@end");
4367
4368  verifyGoogleFormat("@implementation Foo : NSObject {\n"
4369                     " @public\n"
4370                     "  int field1;\n"
4371                     " @protected\n"
4372                     "  int field2;\n"
4373                     " @private\n"
4374                     "  int field3;\n"
4375                     " @package\n"
4376                     "  int field4;\n"
4377                     "}\n"
4378                     "+ (id)init {\n}\n"
4379                     "@end");
4380
4381  verifyFormat("@implementation Foo\n"
4382               "+ (id)init {\n"
4383               "  if (true)\n"
4384               "    return nil;\n"
4385               "}\n"
4386               "// Look, a comment!\n"
4387               "- (int)answerWith:(int)i {\n"
4388               "  return i;\n"
4389               "}\n"
4390               "+ (int)answerWith:(int)i {\n"
4391               "  return i;\n"
4392               "}\n"
4393               "@end");
4394
4395  verifyFormat("@implementation Foo\n"
4396               "@end\n"
4397               "@implementation Bar\n"
4398               "@end");
4399
4400  verifyFormat("@implementation Foo : Bar\n"
4401               "+ (id)init {\n}\n"
4402               "- (void)foo {\n}\n"
4403               "@end");
4404
4405  verifyFormat("@implementation Foo {\n"
4406               "  int _i;\n"
4407               "}\n"
4408               "+ (id)init {\n}\n"
4409               "@end");
4410
4411  verifyFormat("@implementation Foo : Bar {\n"
4412               "  int _i;\n"
4413               "}\n"
4414               "+ (id)init {\n}\n"
4415               "@end");
4416
4417  verifyFormat("@implementation Foo (HackStuff)\n"
4418               "+ (id)init {\n}\n"
4419               "@end");
4420}
4421
4422TEST_F(FormatTest, FormatObjCProtocol) {
4423  verifyFormat("@protocol Foo\n"
4424               "@property(weak) id delegate;\n"
4425               "- (NSUInteger)numberOfThings;\n"
4426               "@end");
4427
4428  verifyFormat("@protocol MyProtocol <NSObject>\n"
4429               "- (NSUInteger)numberOfThings;\n"
4430               "@end");
4431
4432  verifyGoogleFormat("@protocol MyProtocol<NSObject>\n"
4433                     "- (NSUInteger)numberOfThings;\n"
4434                     "@end");
4435
4436  verifyFormat("@protocol Foo;\n"
4437               "@protocol Bar;\n");
4438
4439  verifyFormat("@protocol Foo\n"
4440               "@end\n"
4441               "@protocol Bar\n"
4442               "@end");
4443
4444  verifyFormat("@protocol myProtocol\n"
4445               "- (void)mandatoryWithInt:(int)i;\n"
4446               "@optional\n"
4447               "- (void)optional;\n"
4448               "@required\n"
4449               "- (void)required;\n"
4450               "@optional\n"
4451               "@property(assign) int madProp;\n"
4452               "@end\n");
4453}
4454
4455TEST_F(FormatTest, FormatObjCMethodDeclarations) {
4456  verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
4457               "                   rect:(NSRect)theRect\n"
4458               "               interval:(float)theInterval {\n"
4459               "}");
4460  verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
4461               "          longKeyword:(NSRect)theRect\n"
4462               "    evenLongerKeyword:(float)theInterval\n"
4463               "                error:(NSError **)theError {\n"
4464               "}");
4465}
4466
4467TEST_F(FormatTest, FormatObjCMethodExpr) {
4468  verifyFormat("[foo bar:baz];");
4469  verifyFormat("return [foo bar:baz];");
4470  verifyFormat("f([foo bar:baz]);");
4471  verifyFormat("f(2, [foo bar:baz]);");
4472  verifyFormat("f(2, a ? b : c);");
4473  verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
4474
4475  // Unary operators.
4476  verifyFormat("int a = +[foo bar:baz];");
4477  verifyFormat("int a = -[foo bar:baz];");
4478  verifyFormat("int a = ![foo bar:baz];");
4479  verifyFormat("int a = ~[foo bar:baz];");
4480  verifyFormat("int a = ++[foo bar:baz];");
4481  verifyFormat("int a = --[foo bar:baz];");
4482  verifyFormat("int a = sizeof [foo bar:baz];");
4483  verifyFormat("int a = alignof [foo bar:baz];", getGoogleStyle());
4484  verifyFormat("int a = &[foo bar:baz];");
4485  verifyFormat("int a = *[foo bar:baz];");
4486  // FIXME: Make casts work, without breaking f()[4].
4487  //verifyFormat("int a = (int)[foo bar:baz];");
4488  //verifyFormat("return (int)[foo bar:baz];");
4489  //verifyFormat("(void)[foo bar:baz];");
4490  verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
4491
4492  // Binary operators.
4493  verifyFormat("[foo bar:baz], [foo bar:baz];");
4494  verifyFormat("[foo bar:baz] = [foo bar:baz];");
4495  verifyFormat("[foo bar:baz] *= [foo bar:baz];");
4496  verifyFormat("[foo bar:baz] /= [foo bar:baz];");
4497  verifyFormat("[foo bar:baz] %= [foo bar:baz];");
4498  verifyFormat("[foo bar:baz] += [foo bar:baz];");
4499  verifyFormat("[foo bar:baz] -= [foo bar:baz];");
4500  verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
4501  verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
4502  verifyFormat("[foo bar:baz] &= [foo bar:baz];");
4503  verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
4504  verifyFormat("[foo bar:baz] |= [foo bar:baz];");
4505  verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
4506  verifyFormat("[foo bar:baz] || [foo bar:baz];");
4507  verifyFormat("[foo bar:baz] && [foo bar:baz];");
4508  verifyFormat("[foo bar:baz] | [foo bar:baz];");
4509  verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
4510  verifyFormat("[foo bar:baz] & [foo bar:baz];");
4511  verifyFormat("[foo bar:baz] == [foo bar:baz];");
4512  verifyFormat("[foo bar:baz] != [foo bar:baz];");
4513  verifyFormat("[foo bar:baz] >= [foo bar:baz];");
4514  verifyFormat("[foo bar:baz] <= [foo bar:baz];");
4515  verifyFormat("[foo bar:baz] > [foo bar:baz];");
4516  verifyFormat("[foo bar:baz] < [foo bar:baz];");
4517  verifyFormat("[foo bar:baz] >> [foo bar:baz];");
4518  verifyFormat("[foo bar:baz] << [foo bar:baz];");
4519  verifyFormat("[foo bar:baz] - [foo bar:baz];");
4520  verifyFormat("[foo bar:baz] + [foo bar:baz];");
4521  verifyFormat("[foo bar:baz] * [foo bar:baz];");
4522  verifyFormat("[foo bar:baz] / [foo bar:baz];");
4523  verifyFormat("[foo bar:baz] % [foo bar:baz];");
4524  // Whew!
4525
4526  verifyFormat("return in[42];");
4527  verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
4528               "}");
4529
4530  verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
4531  verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
4532  verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
4533  verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
4534  verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
4535  verifyFormat("[button setAction:@selector(zoomOut:)];");
4536  verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
4537
4538  verifyFormat("arr[[self indexForFoo:a]];");
4539  verifyFormat("throw [self errorFor:a];");
4540  verifyFormat("@throw [self errorFor:a];");
4541
4542  verifyFormat("[(id)foo bar:(id)baz quux:(id)snorf];");
4543  verifyFormat("[(id)foo bar:(id) ? baz : quux];");
4544  verifyFormat("4 > 4 ? (id)a : (id)baz;");
4545
4546  // This tests that the formatter doesn't break after "backing" but before ":",
4547  // which would be at 80 columns.
4548  verifyFormat(
4549      "void f() {\n"
4550      "  if ((self = [super initWithContentRect:contentRect\n"
4551      "                               styleMask:styleMask\n"
4552      "                                 backing:NSBackingStoreBuffered\n"
4553      "                                   defer:YES]))");
4554
4555  verifyFormat(
4556      "[foo checkThatBreakingAfterColonWorksOk:\n"
4557      "        [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
4558
4559  verifyFormat("[myObj short:arg1 // Force line break\n"
4560               "          longKeyword:arg2\n"
4561               "    evenLongerKeyword:arg3\n"
4562               "                error:arg4];");
4563  verifyFormat(
4564      "void f() {\n"
4565      "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
4566      "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
4567      "                                     pos.width(), pos.height())\n"
4568      "                styleMask:NSBorderlessWindowMask\n"
4569      "                  backing:NSBackingStoreBuffered\n"
4570      "                    defer:NO]);\n"
4571      "}");
4572  verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
4573               "                             with:contentsNativeView];");
4574
4575  verifyFormat(
4576      "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
4577      "           owner:nillllll];");
4578
4579  verifyFormat(
4580      "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
4581      "        forType:kBookmarkButtonDragType];");
4582
4583  verifyFormat("[defaultCenter addObserver:self\n"
4584               "                  selector:@selector(willEnterFullscreen)\n"
4585               "                      name:kWillEnterFullscreenNotification\n"
4586               "                    object:nil];");
4587  verifyFormat("[image_rep drawInRect:drawRect\n"
4588               "             fromRect:NSZeroRect\n"
4589               "            operation:NSCompositeCopy\n"
4590               "             fraction:1.0\n"
4591               "       respectFlipped:NO\n"
4592               "                hints:nil];");
4593
4594  verifyFormat(
4595      "scoped_nsobject<NSTextField> message(\n"
4596      "    // The frame will be fixed up when |-setMessageText:| is called.\n"
4597      "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
4598}
4599
4600TEST_F(FormatTest, ObjCAt) {
4601  verifyFormat("@autoreleasepool");
4602  verifyFormat("@catch");
4603  verifyFormat("@class");
4604  verifyFormat("@compatibility_alias");
4605  verifyFormat("@defs");
4606  verifyFormat("@dynamic");
4607  verifyFormat("@encode");
4608  verifyFormat("@end");
4609  verifyFormat("@finally");
4610  verifyFormat("@implementation");
4611  verifyFormat("@import");
4612  verifyFormat("@interface");
4613  verifyFormat("@optional");
4614  verifyFormat("@package");
4615  verifyFormat("@private");
4616  verifyFormat("@property");
4617  verifyFormat("@protected");
4618  verifyFormat("@protocol");
4619  verifyFormat("@public");
4620  verifyFormat("@required");
4621  verifyFormat("@selector");
4622  verifyFormat("@synchronized");
4623  verifyFormat("@synthesize");
4624  verifyFormat("@throw");
4625  verifyFormat("@try");
4626
4627  EXPECT_EQ("@interface", format("@ interface"));
4628
4629  // The precise formatting of this doesn't matter, nobody writes code like
4630  // this.
4631  verifyFormat("@ /*foo*/ interface");
4632}
4633
4634TEST_F(FormatTest, ObjCSnippets) {
4635  verifyFormat("@autoreleasepool {\n"
4636               "  foo();\n"
4637               "}");
4638  verifyFormat("@class Foo, Bar;");
4639  verifyFormat("@compatibility_alias AliasName ExistingClass;");
4640  verifyFormat("@dynamic textColor;");
4641  verifyFormat("char *buf1 = @encode(int *);");
4642  verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
4643  verifyFormat("char *buf1 = @encode(int **);");
4644  verifyFormat("Protocol *proto = @protocol(p1);");
4645  verifyFormat("SEL s = @selector(foo:);");
4646  verifyFormat("@synchronized(self) {\n"
4647               "  f();\n"
4648               "}");
4649
4650  verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
4651  verifyGoogleFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
4652
4653  verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
4654  verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
4655  verifyGoogleFormat("@property(assign, getter=isEditable) BOOL editable;");
4656
4657  verifyFormat("@import foo.bar;\n"
4658               "@import baz;");
4659}
4660
4661TEST_F(FormatTest, ObjCLiterals) {
4662  verifyFormat("@\"String\"");
4663  verifyFormat("@1");
4664  verifyFormat("@+4.8");
4665  verifyFormat("@-4");
4666  verifyFormat("@1LL");
4667  verifyFormat("@.5");
4668  verifyFormat("@'c'");
4669  verifyFormat("@true");
4670
4671  verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
4672  verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
4673  verifyFormat("NSNumber *favoriteColor = @(Green);");
4674  verifyFormat("NSString *path = @(getenv(\"PATH\"));");
4675
4676  verifyFormat("@[");
4677  verifyFormat("@[]");
4678  verifyFormat(
4679      "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
4680  verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
4681
4682  verifyFormat("@{");
4683  verifyFormat("@{}");
4684  verifyFormat("@{ @\"one\" : @1 }");
4685  verifyFormat("return @{ @\"one\" : @1 };");
4686  verifyFormat("@{ @\"one\" : @1, }");
4687
4688  verifyFormat("@{ @\"one\" : @{ @2 : @1 } }");
4689  verifyFormat("@{ @\"one\" : @{ @2 : @1 }, }");
4690
4691  verifyFormat("@{ 1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2 }");
4692  verifyFormat("[self setDict:@{}");
4693  verifyFormat("[self setDict:@{ @1 : @2 }");
4694  verifyFormat("NSLog(@\"%@\", @{ @1 : @2, @2 : @3 }[@1]);");
4695  verifyFormat(
4696      "NSDictionary *masses = @{ @\"H\" : @1.0078, @\"He\" : @4.0026 };");
4697  verifyFormat(
4698      "NSDictionary *settings = @{ AVEncoderKey : @(AVAudioQualityMax) };");
4699
4700  // FIXME: Nested and multi-line array and dictionary literals need more work.
4701  verifyFormat(
4702      "NSDictionary *d = @{ @\"nam\" : NSUserNam(), @\"dte\" : [NSDate date],\n"
4703      "                     @\"processInfo\" : [NSProcessInfo processInfo] };");
4704  verifyFormat(
4705      "@{ NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :\n"
4706      "   regularFont, };");
4707
4708}
4709
4710TEST_F(FormatTest, ReformatRegionAdjustsIndent) {
4711  EXPECT_EQ("{\n"
4712            "{\n"
4713            "a;\n"
4714            "b;\n"
4715            "}\n"
4716            "}",
4717            format("{\n"
4718                   "{\n"
4719                   "a;\n"
4720                   "     b;\n"
4721                   "}\n"
4722                   "}",
4723                   13, 2, getLLVMStyle()));
4724  EXPECT_EQ("{\n"
4725            "{\n"
4726            "  a;\n"
4727            "b;\n"
4728            "}\n"
4729            "}",
4730            format("{\n"
4731                   "{\n"
4732                   "     a;\n"
4733                   "b;\n"
4734                   "}\n"
4735                   "}",
4736                   9, 2, getLLVMStyle()));
4737  EXPECT_EQ("{\n"
4738            "{\n"
4739            "public:\n"
4740            "  b;\n"
4741            "}\n"
4742            "}",
4743            format("{\n"
4744                   "{\n"
4745                   "public:\n"
4746                   "     b;\n"
4747                   "}\n"
4748                   "}",
4749                   17, 2, getLLVMStyle()));
4750  EXPECT_EQ("{\n"
4751            "{\n"
4752            "a;\n"
4753            "}\n"
4754            "{\n"
4755            "  b; //\n"
4756            "}\n"
4757            "}",
4758            format("{\n"
4759                   "{\n"
4760                   "a;\n"
4761                   "}\n"
4762                   "{\n"
4763                   "           b; //\n"
4764                   "}\n"
4765                   "}",
4766                   22, 2, getLLVMStyle()));
4767  EXPECT_EQ("  {\n"
4768            "    a; //\n"
4769            "  }",
4770            format("  {\n"
4771                   "a; //\n"
4772                   "  }",
4773                   4, 2, getLLVMStyle()));
4774  EXPECT_EQ("void f() {}\n"
4775            "void g() {}",
4776            format("void f() {}\n"
4777                   "void g() {}",
4778                   13, 0, getLLVMStyle()));
4779  EXPECT_EQ("int a; // comment\n"
4780            "       // line 2\n"
4781            "int b;",
4782            format("int a; // comment\n"
4783                   "       // line 2\n"
4784                   "  int b;",
4785                   35, 0, getLLVMStyle()));
4786}
4787
4788TEST_F(FormatTest, BreakStringLiterals) {
4789  EXPECT_EQ("\"some text \"\n"
4790            "\"other\";",
4791            format("\"some text other\";", getLLVMStyleWithColumns(12)));
4792  EXPECT_EQ("\"some text \"\n"
4793            "\"other\";",
4794            format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
4795  EXPECT_EQ(
4796      "#define A  \\\n"
4797      "  \"some \"  \\\n"
4798      "  \"text \"  \\\n"
4799      "  \"other\";",
4800      format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
4801  EXPECT_EQ(
4802      "#define A  \\\n"
4803      "  \"so \"    \\\n"
4804      "  \"text \"  \\\n"
4805      "  \"other\";",
4806      format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
4807
4808  EXPECT_EQ("\"some text\"",
4809            format("\"some text\"", getLLVMStyleWithColumns(1)));
4810  EXPECT_EQ("\"some text\"",
4811            format("\"some text\"", getLLVMStyleWithColumns(11)));
4812  EXPECT_EQ("\"some \"\n"
4813            "\"text\"",
4814            format("\"some text\"", getLLVMStyleWithColumns(10)));
4815  EXPECT_EQ("\"some \"\n"
4816            "\"text\"",
4817            format("\"some text\"", getLLVMStyleWithColumns(7)));
4818  EXPECT_EQ("\"some\"\n"
4819            "\" tex\"\n"
4820            "\"t\"",
4821            format("\"some text\"", getLLVMStyleWithColumns(6)));
4822  EXPECT_EQ("\"some\"\n"
4823            "\" tex\"\n"
4824            "\" and\"",
4825            format("\"some tex and\"", getLLVMStyleWithColumns(6)));
4826  EXPECT_EQ("\"some\"\n"
4827            "\"/tex\"\n"
4828            "\"/and\"",
4829            format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
4830
4831  EXPECT_EQ("variable =\n"
4832            "    \"long string \"\n"
4833            "    \"literal\";",
4834            format("variable = \"long string literal\";",
4835                   getLLVMStyleWithColumns(20)));
4836
4837  EXPECT_EQ("variable = f(\n"
4838            "    \"long string \"\n"
4839            "    \"literal\",\n"
4840            "    short,\n"
4841            "    loooooooooooooooooooong);",
4842            format("variable = f(\"long string literal\", short, "
4843                   "loooooooooooooooooooong);",
4844                   getLLVMStyleWithColumns(20)));
4845
4846  EXPECT_EQ("f(g(\"long string \"\n"
4847            "    \"literal\"),\n"
4848            "  b);",
4849            format("f(g(\"long string literal\"), b);",
4850                   getLLVMStyleWithColumns(20)));
4851  EXPECT_EQ("f(g(\"long string \"\n"
4852            "    \"literal\",\n"
4853            "    a),\n"
4854            "  b);",
4855            format("f(g(\"long string literal\", a), b);",
4856                   getLLVMStyleWithColumns(20)));
4857  EXPECT_EQ(
4858      "f(\"one two\".split(\n"
4859      "    variable));",
4860      format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
4861  EXPECT_EQ("f(\"one two three four five six \"\n"
4862            "  \"seven\".split(\n"
4863            "      really_looooong_variable));",
4864            format("f(\"one two three four five six seven\"."
4865                   "split(really_looooong_variable));",
4866                   getLLVMStyleWithColumns(33)));
4867
4868  EXPECT_EQ("f(\"some \"\n"
4869            "  \"text\",\n"
4870            "  other);",
4871            format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
4872
4873  // Only break as a last resort.
4874  verifyFormat(
4875      "aaaaaaaaaaaaaaaaaaaa(\n"
4876      "    aaaaaaaaaaaaaaaaaaaa,\n"
4877      "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
4878
4879  EXPECT_EQ(
4880      "\"splitmea\"\n"
4881      "\"trandomp\"\n"
4882      "\"oint\"",
4883      format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
4884
4885  EXPECT_EQ(
4886      "\"split/\"\n"
4887      "\"pathat/\"\n"
4888      "\"slashes\"",
4889      format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
4890
4891  EXPECT_EQ(
4892      "\"split/\"\n"
4893      "\"pathat/\"\n"
4894      "\"slashes\"",
4895      format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
4896  EXPECT_EQ("\"split at \"\n"
4897            "\"spaces/at/\"\n"
4898            "\"slashes.at.any$\"\n"
4899            "\"non-alphanumeric%\"\n"
4900            "\"1111111111characte\"\n"
4901            "\"rs\"",
4902            format("\"split at "
4903                   "spaces/at/"
4904                   "slashes.at."
4905                   "any$non-"
4906                   "alphanumeric%"
4907                   "1111111111characte"
4908                   "rs\"",
4909                   getLLVMStyleWithColumns(20)));
4910
4911  FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
4912  AlignLeft.AlignEscapedNewlinesLeft = true;
4913  EXPECT_EQ(
4914      "#define A \\\n"
4915      "  \"some \" \\\n"
4916      "  \"text \" \\\n"
4917      "  \"other\";",
4918      format("#define A \"some text other\";", AlignLeft));
4919}
4920
4921TEST_F(FormatTest, SkipsUnknownStringLiterals) {
4922  EXPECT_EQ(
4923      "u8\"unsupported literal\";",
4924      format("u8\"unsupported literal\";", getGoogleStyleWithColumns(15)));
4925  EXPECT_EQ("u\"unsupported literal\";",
4926            format("u\"unsupported literal\";", getGoogleStyleWithColumns(15)));
4927  EXPECT_EQ("U\"unsupported literal\";",
4928            format("U\"unsupported literal\";", getGoogleStyleWithColumns(15)));
4929  EXPECT_EQ("L\"unsupported literal\";",
4930            format("L\"unsupported literal\";", getGoogleStyleWithColumns(15)));
4931  EXPECT_EQ("R\"x(raw literal)x\";",
4932            format("R\"x(raw literal)x\";", getGoogleStyleWithColumns(15)));
4933}
4934
4935TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
4936  EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
4937            format("#define x(_a) printf(\"foo\"_a);", getLLVMStyle()));
4938}
4939
4940TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
4941  EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
4942            "             \"ddeeefff\");",
4943            format("someFunction(\"aaabbbcccdddeeefff\");",
4944                   getLLVMStyleWithColumns(25)));
4945  EXPECT_EQ("someFunction1234567890(\n"
4946            "    \"aaabbbcccdddeeefff\");",
4947            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
4948                   getLLVMStyleWithColumns(26)));
4949  EXPECT_EQ("someFunction1234567890(\n"
4950            "    \"aaabbbcccdddeeeff\"\n"
4951            "    \"f\");",
4952            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
4953                   getLLVMStyleWithColumns(25)));
4954  EXPECT_EQ("someFunction1234567890(\n"
4955            "    \"aaabbbcccdddeeeff\"\n"
4956            "    \"f\");",
4957            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
4958                   getLLVMStyleWithColumns(24)));
4959  EXPECT_EQ("someFunction(\n"
4960            "    \"aaabbbcc \"\n"
4961            "    \"dddeeefff\");",
4962            format("someFunction(\"aaabbbcc dddeeefff\");",
4963                   getLLVMStyleWithColumns(25)));
4964  EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
4965            "             \"ddeeefff\");",
4966            format("someFunction(\"aaabbbccc ddeeefff\");",
4967                   getLLVMStyleWithColumns(25)));
4968  EXPECT_EQ("someFunction1234567890(\n"
4969            "    \"aaabb \"\n"
4970            "    \"cccdddeeefff\");",
4971            format("someFunction1234567890(\"aaabb cccdddeeefff\");",
4972                   getLLVMStyleWithColumns(25)));
4973  EXPECT_EQ("#define A          \\\n"
4974            "  string s =       \\\n"
4975            "      \"123456789\"  \\\n"
4976            "      \"0\";         \\\n"
4977            "  int i;",
4978            format("#define A string s = \"1234567890\"; int i;",
4979                   getLLVMStyleWithColumns(20)));
4980}
4981
4982TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
4983  EXPECT_EQ("\"\\a\"",
4984            format("\"\\a\"", getLLVMStyleWithColumns(3)));
4985  EXPECT_EQ("\"\\\"",
4986            format("\"\\\"", getLLVMStyleWithColumns(2)));
4987  EXPECT_EQ("\"test\"\n"
4988            "\"\\n\"",
4989            format("\"test\\n\"", getLLVMStyleWithColumns(7)));
4990  EXPECT_EQ("\"tes\\\\\"\n"
4991            "\"n\"",
4992            format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
4993  EXPECT_EQ("\"\\\\\\\\\"\n"
4994            "\"\\n\"",
4995            format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
4996  EXPECT_EQ("\"\\uff01\"",
4997            format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
4998  EXPECT_EQ("\"\\uff01\"\n"
4999            "\"test\"",
5000            format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
5001  EXPECT_EQ("\"\\Uff01ff02\"",
5002            format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
5003  EXPECT_EQ("\"\\x000000000001\"\n"
5004            "\"next\"",
5005            format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
5006  EXPECT_EQ("\"\\x000000000001next\"",
5007            format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
5008  EXPECT_EQ("\"\\x000000000001\"",
5009            format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
5010  EXPECT_EQ("\"test\"\n"
5011            "\"\\000000\"\n"
5012            "\"000001\"",
5013            format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
5014  EXPECT_EQ("\"test\\000\"\n"
5015            "\"00000000\"\n"
5016            "\"1\"",
5017            format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
5018  EXPECT_EQ("R\"(\\x\\x00)\"\n",
5019            format("R\"(\\x\\x00)\"\n", getGoogleStyleWithColumns(7)));
5020}
5021
5022TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
5023  verifyFormat("void f() {\n"
5024               "  return g() {}\n"
5025               "  void h() {}");
5026  verifyFormat("if (foo)\n"
5027               "  return { forgot_closing_brace();\n"
5028               "test();");
5029  verifyFormat("int a[] = { void forgot_closing_brace() { f();\n"
5030               "g();\n"
5031               "}");
5032}
5033
5034TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
5035  verifyFormat("class X {\n"
5036               "  void f() {\n"
5037               "  }\n"
5038               "};",
5039               getLLVMStyleWithColumns(12));
5040}
5041
5042TEST_F(FormatTest, ConfigurableIndentWidth) {
5043  FormatStyle EightIndent = getLLVMStyleWithColumns(18);
5044  EightIndent.IndentWidth = 8;
5045  verifyFormat("void f() {\n"
5046               "        someFunction();\n"
5047               "        if (true) {\n"
5048               "                f();\n"
5049               "        }\n"
5050               "}",
5051               EightIndent);
5052  verifyFormat("class X {\n"
5053               "        void f() {\n"
5054               "        }\n"
5055               "};",
5056               EightIndent);
5057  verifyFormat("int x[] = {\n"
5058               "        call(),\n"
5059               "        call(),\n"
5060               "};",
5061               EightIndent);
5062}
5063
5064TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
5065  verifyFormat("void\n"
5066               "f();",
5067               getLLVMStyleWithColumns(8));
5068}
5069
5070TEST_F(FormatTest, ConfigurableUseOfTab) {
5071  FormatStyle Tab = getLLVMStyleWithColumns(42);
5072  Tab.IndentWidth = 8;
5073  Tab.UseTab = true;
5074  Tab.AlignEscapedNewlinesLeft = true;
5075  verifyFormat("class X {\n"
5076               "\tvoid f() {\n"
5077               "\t\tsomeFunction(parameter1,\n"
5078               "\t\t\t     parameter2);\n"
5079               "\t}\n"
5080               "};",
5081               Tab);
5082  verifyFormat("#define A                        \\\n"
5083               "\tvoid f() {               \\\n"
5084               "\t\tsomeFunction(    \\\n"
5085               "\t\t    parameter1,  \\\n"
5086               "\t\t    parameter2); \\\n"
5087               "\t}",
5088               Tab);
5089
5090
5091  // FIXME: To correctly count mixed whitespace we need to
5092  // also correctly count mixed whitespace in front of the comment.
5093  //
5094  // EXPECT_EQ("/*\n"
5095  //           "\t      a\t\tcomment\n"
5096  //           "\t      in multiple lines\n"
5097  //           "       */",
5098  //           format("   /*\t \t \n"
5099  //                  " \t \t a\t\tcomment\t \t\n"
5100  //                  " \t \t in multiple lines\t\n"
5101  //                  " \t  */",
5102  //                  Tab));
5103  // Tab.UseTab = false;
5104  // EXPECT_EQ("/*\n"
5105  //           "              a\t\tcomment\n"
5106  //           "              in multiple lines\n"
5107  //           "       */",
5108  //           format("   /*\t \t \n"
5109  //                  " \t \t a\t\tcomment\t \t\n"
5110  //                  " \t \t in multiple lines\t\n"
5111  //                  " \t  */",
5112  //                  Tab));
5113  // EXPECT_EQ("/* some\n"
5114  //           "   comment */",
5115  //          format(" \t \t /* some\n"
5116  //                 " \t \t    comment */",
5117  //                 Tab));
5118
5119  EXPECT_EQ("{\n"
5120            "  /*\n"
5121            "   * Comment\n"
5122            "   */\n"
5123            "  int i;\n"
5124            "}",
5125            format("{\n"
5126                   "\t/*\n"
5127                   "\t * Comment\n"
5128                   "\t */\n"
5129                   "\t int i;\n"
5130                   "}"));
5131}
5132
5133TEST_F(FormatTest, LinuxBraceBreaking) {
5134  FormatStyle BreakBeforeBrace = getLLVMStyle();
5135  BreakBeforeBrace.BreakBeforeBraces = FormatStyle::BS_Linux;
5136  verifyFormat("namespace a\n"
5137               "{\n"
5138               "class A\n"
5139               "{\n"
5140               "  void f()\n"
5141               "  {\n"
5142               "    if (true) {\n"
5143               "      a();\n"
5144               "      b();\n"
5145               "    }\n"
5146               "  }\n"
5147               "  void g()\n"
5148               "  {\n"
5149               "    return;\n"
5150               "  }\n"
5151               "}\n"
5152               "}",
5153               BreakBeforeBrace);
5154}
5155
5156TEST_F(FormatTest, StroustrupBraceBreaking) {
5157  FormatStyle BreakBeforeBrace = getLLVMStyle();
5158  BreakBeforeBrace.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
5159  verifyFormat("namespace a {\n"
5160               "class A {\n"
5161               "  void f()\n"
5162               "  {\n"
5163               "    if (true) {\n"
5164               "      a();\n"
5165               "      b();\n"
5166               "    }\n"
5167               "  }\n"
5168               "  void g()\n"
5169               "  {\n"
5170               "    return;\n"
5171               "  }\n"
5172               "}\n"
5173               "}",
5174               BreakBeforeBrace);
5175}
5176
5177bool allStylesEqual(ArrayRef<FormatStyle> Styles) {
5178  for (size_t i = 1; i < Styles.size(); ++i)
5179    if (!(Styles[0] == Styles[i]))
5180      return false;
5181  return true;
5182}
5183
5184TEST_F(FormatTest, GetsPredefinedStyleByName) {
5185  FormatStyle Styles[3];
5186
5187  Styles[0] = getLLVMStyle();
5188  EXPECT_TRUE(getPredefinedStyle("LLVM", &Styles[1]));
5189  EXPECT_TRUE(getPredefinedStyle("lLvM", &Styles[2]));
5190  EXPECT_TRUE(allStylesEqual(Styles));
5191
5192  Styles[0] = getGoogleStyle();
5193  EXPECT_TRUE(getPredefinedStyle("Google", &Styles[1]));
5194  EXPECT_TRUE(getPredefinedStyle("gOOgle", &Styles[2]));
5195  EXPECT_TRUE(allStylesEqual(Styles));
5196
5197  Styles[0] = getChromiumStyle();
5198  EXPECT_TRUE(getPredefinedStyle("Chromium", &Styles[1]));
5199  EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", &Styles[2]));
5200  EXPECT_TRUE(allStylesEqual(Styles));
5201
5202  Styles[0] = getMozillaStyle();
5203  EXPECT_TRUE(getPredefinedStyle("Mozilla", &Styles[1]));
5204  EXPECT_TRUE(getPredefinedStyle("moZILla", &Styles[2]));
5205  EXPECT_TRUE(allStylesEqual(Styles));
5206
5207  EXPECT_FALSE(getPredefinedStyle("qwerty", &Styles[0]));
5208}
5209
5210TEST_F(FormatTest, ParsesConfiguration) {
5211  FormatStyle Style = {};
5212#define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
5213  EXPECT_NE(VALUE, Style.FIELD);                                               \
5214  EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
5215  EXPECT_EQ(VALUE, Style.FIELD)
5216
5217#define CHECK_PARSE_BOOL(FIELD)                                                \
5218  Style.FIELD = false;                                                         \
5219  EXPECT_EQ(0, parseConfiguration(#FIELD ": true", &Style).value());           \
5220  EXPECT_TRUE(Style.FIELD);                                                    \
5221  EXPECT_EQ(0, parseConfiguration(#FIELD ": false", &Style).value());          \
5222  EXPECT_FALSE(Style.FIELD);
5223
5224  CHECK_PARSE_BOOL(AlignEscapedNewlinesLeft);
5225  CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
5226  CHECK_PARSE_BOOL(AllowShortIfStatementsOnASingleLine);
5227  CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
5228  CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
5229  CHECK_PARSE_BOOL(BinPackParameters);
5230  CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
5231  CHECK_PARSE_BOOL(DerivePointerBinding);
5232  CHECK_PARSE_BOOL(IndentCaseLabels);
5233  CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
5234  CHECK_PARSE_BOOL(PointerBindsToType);
5235  CHECK_PARSE_BOOL(SpacesInBracedLists);
5236  CHECK_PARSE_BOOL(UseTab);
5237  CHECK_PARSE_BOOL(IndentFunctionDeclarationAfterType);
5238
5239  CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
5240  CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
5241  CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
5242  CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
5243  CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
5244              PenaltyReturnTypeOnItsOwnLine, 1234u);
5245  CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
5246              SpacesBeforeTrailingComments, 1234u);
5247  CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
5248
5249  Style.Standard = FormatStyle::LS_Auto;
5250  CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
5251  CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
5252  CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
5253
5254  Style.ColumnLimit = 123;
5255  FormatStyle BaseStyle = getLLVMStyle();
5256  CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
5257  CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
5258
5259  Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
5260  CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
5261              FormatStyle::BS_Attach);
5262  CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
5263              FormatStyle::BS_Linux);
5264  CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
5265              FormatStyle::BS_Stroustrup);
5266
5267#undef CHECK_PARSE
5268#undef CHECK_PARSE_BOOL
5269}
5270
5271TEST_F(FormatTest, ConfigurationRoundTripTest) {
5272  FormatStyle Style = getLLVMStyle();
5273  std::string YAML = configurationAsText(Style);
5274  FormatStyle ParsedStyle = {};
5275  EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
5276  EXPECT_EQ(Style, ParsedStyle);
5277}
5278
5279TEST_F(FormatTest, WorksFor8bitEncodings) {
5280  EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
5281            "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
5282            "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
5283            "\"\xef\xee\xf0\xf3...\"",
5284            format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
5285                   "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
5286                   "\xef\xee\xf0\xf3...\"",
5287                   getLLVMStyleWithColumns(12)));
5288}
5289
5290// FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
5291#if !defined(_MSC_VER)
5292
5293TEST_F(FormatTest, CountsUTF8CharactersProperly) {
5294  verifyFormat("\"Однажды в студёную зимнюю пору...\"",
5295               getLLVMStyleWithColumns(35));
5296  verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
5297               getLLVMStyleWithColumns(21));
5298  verifyFormat("// Однажды в студёную зимнюю пору...",
5299               getLLVMStyleWithColumns(36));
5300  verifyFormat("// 一 二 三 四 五 六 七 八 九 十",
5301               getLLVMStyleWithColumns(22));
5302  verifyFormat("/* Однажды в студёную зимнюю пору... */",
5303               getLLVMStyleWithColumns(39));
5304  verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
5305               getLLVMStyleWithColumns(25));
5306}
5307
5308TEST_F(FormatTest, SplitsUTF8Strings) {
5309  EXPECT_EQ(
5310      "\"Однажды, в \"\n"
5311      "\"студёную \"\n"
5312      "\"зимнюю \"\n"
5313      "\"пору,\"",
5314      format("\"Однажды, в студёную зимнюю пору,\"",
5315             getLLVMStyleWithColumns(13)));
5316  EXPECT_EQ("\"一 二 三 四 \"\n"
5317            "\"五 六 七 八 \"\n"
5318            "\"九 十\"",
5319            format("\"一 二 三 四 五 六 七 八 九 十\"",
5320                   getLLVMStyleWithColumns(10)));
5321}
5322
5323TEST_F(FormatTest, SplitsUTF8LineComments) {
5324  EXPECT_EQ("// Я из лесу\n"
5325            "// вышел; был\n"
5326            "// сильный\n"
5327            "// мороз.",
5328            format("// Я из лесу вышел; был сильный мороз.",
5329                   getLLVMStyleWithColumns(13)));
5330  EXPECT_EQ("// 一二三\n"
5331            "// 四五六七\n"
5332            "// 八\n"
5333            "// 九 十",
5334            format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(6)));
5335}
5336
5337TEST_F(FormatTest, SplitsUTF8BlockComments) {
5338  EXPECT_EQ("/* Гляжу,\n"
5339            " * поднимается\n"
5340            " * медленно в\n"
5341            " * гору\n"
5342            " * Лошадка,\n"
5343            " * везущая\n"
5344            " * хворосту\n"
5345            " * воз. */",
5346            format("/* Гляжу, поднимается медленно в гору\n"
5347                   " * Лошадка, везущая хворосту воз. */",
5348                   getLLVMStyleWithColumns(13)));
5349  EXPECT_EQ("/* 一二三\n"
5350            " * 四五六七\n"
5351            " * 八\n"
5352            " * 九 十\n"
5353            " */",
5354            format("/* 一二三 四五六七 八  九 十 */", getLLVMStyleWithColumns(6)));
5355  EXPECT_EQ("/* �������� ��������\n"
5356            " * ��������\n"
5357            " * ������-�� */",
5358            format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
5359}
5360
5361#endif
5362
5363} // end namespace tooling
5364} // end namespace clang
5365