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