FormatTest.cpp revision 8092a940922f307edb569036a3bb6bb722fb3a3d
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 "../Tooling/RewriterTestContext.h"
14#include "clang/Lex/Lexer.h"
15#include "llvm/Support/Debug.h"
16#include "gtest/gtest.h"
17
18namespace clang {
19namespace format {
20
21class FormatTest : public ::testing::Test {
22protected:
23  std::string format(llvm::StringRef Code, unsigned Offset, unsigned Length,
24                     const FormatStyle &Style) {
25    DEBUG(llvm::errs() << "---\n");
26    RewriterTestContext Context;
27    FileID ID = Context.createInMemoryFile("input.cc", Code);
28    SourceLocation Start =
29        Context.Sources.getLocForStartOfFile(ID).getLocWithOffset(Offset);
30    std::vector<CharSourceRange> Ranges(
31        1,
32        CharSourceRange::getCharRange(Start, Start.getLocWithOffset(Length)));
33    Lexer Lex(ID, Context.Sources.getBuffer(ID), Context.Sources,
34              getFormattingLangOpts());
35    tooling::Replacements Replace = reformat(
36        Style, Lex, Context.Sources, Ranges, new IgnoringDiagConsumer());
37    ReplacementCount = Replace.size();
38    EXPECT_TRUE(applyAllReplacements(Replace, Context.Rewrite));
39    DEBUG(llvm::errs() << "\n" << Context.getRewrittenText(ID) << "\n\n");
40    return Context.getRewrittenText(ID);
41  }
42
43  std::string
44  format(llvm::StringRef Code, const FormatStyle &Style = getLLVMStyle()) {
45    return format(Code, 0, Code.size(), Style);
46  }
47
48  std::string messUp(llvm::StringRef Code) {
49    std::string MessedUp(Code.str());
50    bool InComment = false;
51    bool InPreprocessorDirective = false;
52    bool JustReplacedNewline = false;
53    for (unsigned i = 0, e = MessedUp.size() - 1; i != e; ++i) {
54      if (MessedUp[i] == '/' && MessedUp[i + 1] == '/') {
55        if (JustReplacedNewline)
56          MessedUp[i - 1] = '\n';
57        InComment = true;
58      } else if (MessedUp[i] == '#' && (JustReplacedNewline || i == 0)) {
59        if (i != 0)
60          MessedUp[i - 1] = '\n';
61        InPreprocessorDirective = true;
62      } else if (MessedUp[i] == '\\' && MessedUp[i + 1] == '\n') {
63        MessedUp[i] = ' ';
64        MessedUp[i + 1] = ' ';
65      } else if (MessedUp[i] == '\n') {
66        if (InComment) {
67          InComment = false;
68        } else if (InPreprocessorDirective) {
69          InPreprocessorDirective = false;
70        } else {
71          JustReplacedNewline = true;
72          MessedUp[i] = ' ';
73        }
74      } else if (MessedUp[i] != ' ') {
75        JustReplacedNewline = false;
76      }
77    }
78    return MessedUp;
79  }
80
81  FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
82    FormatStyle Style = getLLVMStyle();
83    Style.ColumnLimit = ColumnLimit;
84    return Style;
85  }
86
87  FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
88    FormatStyle Style = getGoogleStyle();
89    Style.ColumnLimit = ColumnLimit;
90    return Style;
91  }
92
93  void verifyFormat(llvm::StringRef Code,
94                    const FormatStyle &Style = getLLVMStyle()) {
95    EXPECT_EQ(Code.str(), format(messUp(Code), Style));
96  }
97
98  void verifyGoogleFormat(llvm::StringRef Code) {
99    verifyFormat(Code, getGoogleStyle());
100  }
101
102  void verifyIndependentOfContext(llvm::StringRef text) {
103    verifyFormat(text);
104    verifyFormat(llvm::Twine("void f() { " + text + " }").str());
105  }
106
107  int ReplacementCount;
108};
109
110TEST_F(FormatTest, MessUp) {
111  EXPECT_EQ("1 2 3", messUp("1 2 3"));
112  EXPECT_EQ("1 2 3\n", messUp("1\n2\n3\n"));
113  EXPECT_EQ("a\n//b\nc", messUp("a\n//b\nc"));
114  EXPECT_EQ("a\n#b\nc", messUp("a\n#b\nc"));
115  EXPECT_EQ("a\n#b  c  d\ne", messUp("a\n#b\\\nc\\\nd\ne"));
116}
117
118//===----------------------------------------------------------------------===//
119// Basic function tests.
120//===----------------------------------------------------------------------===//
121
122TEST_F(FormatTest, DoesNotChangeCorrectlyFormatedCode) {
123  EXPECT_EQ(";", format(";"));
124}
125
126TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
127  EXPECT_EQ("int i;", format("  int i;"));
128  EXPECT_EQ("\nint i;", format(" \n\t \r  int i;"));
129  EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
130  EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
131}
132
133TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
134  EXPECT_EQ("int i;", format("int\ni;"));
135}
136
137TEST_F(FormatTest, FormatsNestedBlockStatements) {
138  EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
139}
140
141TEST_F(FormatTest, FormatsNestedCall) {
142  verifyFormat("Method(f1, f2(f3));");
143  verifyFormat("Method(f1(f2, f3()));");
144  verifyFormat("Method(f1(f2, (f3())));");
145}
146
147TEST_F(FormatTest, NestedNameSpecifiers) {
148  verifyFormat("vector< ::Type> v;");
149  verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
150}
151
152TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
153  EXPECT_EQ("if (a) {\n"
154            "  f();\n"
155            "}",
156            format("if(a){f();}"));
157  EXPECT_EQ(4, ReplacementCount);
158  EXPECT_EQ("if (a) {\n"
159            "  f();\n"
160            "}",
161            format("if (a) {\n"
162                   "  f();\n"
163                   "}"));
164  EXPECT_EQ(0, ReplacementCount);
165}
166
167TEST_F(FormatTest, RemovesTrailingWhitespaceOfFormattedLine) {
168  EXPECT_EQ("int a;\nint b;", format("int a; \nint b;", 0, 0, getLLVMStyle()));
169}
170
171TEST_F(FormatTest, ReformatsMovedLines) {
172  EXPECT_EQ(
173      "template <typename T> T *getFETokenInfo() const {\n"
174      "  return static_cast<T *>(FETokenInfo);\n"
175      "}\n"
176      "  int a; // <- Should not be formatted",
177      format(
178          "template<typename T>\n"
179          "T *getFETokenInfo() const { return static_cast<T*>(FETokenInfo); }\n"
180          "  int a; // <- Should not be formatted",
181          9, 5, getLLVMStyle()));
182}
183
184//===----------------------------------------------------------------------===//
185// Tests for control statements.
186//===----------------------------------------------------------------------===//
187
188TEST_F(FormatTest, FormatIfWithoutCompountStatement) {
189  verifyFormat("if (true)\n  f();\ng();");
190  verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
191  verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
192
193  FormatStyle AllowsMergedIf = getGoogleStyle();
194  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
195  verifyFormat("if (a)\n"
196               "  // comment\n"
197               "  f();",
198               AllowsMergedIf);
199
200  verifyFormat("if (a)  // Can't merge this\n"
201               "  f();\n",
202               AllowsMergedIf);
203  verifyFormat("if (a) /* still don't merge */\n"
204               "  f();",
205               AllowsMergedIf);
206  verifyFormat("if (a) {  // Never merge this\n"
207               "  f();\n"
208               "}",
209               AllowsMergedIf);
210  verifyFormat("if (a) { /* Never merge this */\n"
211               "  f();\n"
212               "}",
213               AllowsMergedIf);
214
215  AllowsMergedIf.ColumnLimit = 14;
216  verifyFormat("if (a) return;", AllowsMergedIf);
217  verifyFormat("if (aaaaaaaaa)\n"
218               "  return;",
219               AllowsMergedIf);
220
221  AllowsMergedIf.ColumnLimit = 13;
222  verifyFormat("if (a)\n  return;", AllowsMergedIf);
223}
224
225TEST_F(FormatTest, ParseIfElse) {
226  verifyFormat("if (true)\n"
227               "  if (true)\n"
228               "    if (true)\n"
229               "      f();\n"
230               "    else\n"
231               "      g();\n"
232               "  else\n"
233               "    h();\n"
234               "else\n"
235               "  i();");
236  verifyFormat("if (true)\n"
237               "  if (true)\n"
238               "    if (true) {\n"
239               "      if (true)\n"
240               "        f();\n"
241               "    } else {\n"
242               "      g();\n"
243               "    }\n"
244               "  else\n"
245               "    h();\n"
246               "else {\n"
247               "  i();\n"
248               "}");
249}
250
251TEST_F(FormatTest, ElseIf) {
252  verifyFormat("if (a) {\n} else if (b) {\n}");
253  verifyFormat("if (a)\n"
254               "  f();\n"
255               "else if (b)\n"
256               "  g();\n"
257               "else\n"
258               "  h();");
259}
260
261TEST_F(FormatTest, FormatsForLoop) {
262  verifyFormat(
263      "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
264      "     ++VeryVeryLongLoopVariable)\n"
265      "  ;");
266  verifyFormat("for (;;)\n"
267               "  f();");
268  verifyFormat("for (;;) {\n}");
269  verifyFormat("for (;;) {\n"
270               "  f();\n"
271               "}");
272
273  verifyFormat(
274      "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
275      "                                          E = UnwrappedLines.end();\n"
276      "     I != E; ++I) {\n}");
277
278  verifyFormat(
279      "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
280      "     ++IIIII) {\n}");
281  verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
282               "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
283               "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
284
285  // FIXME: Not sure whether we want extra identation in line 3 here:
286  verifyFormat(
287      "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
288      "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
289      "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
290      "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
291      "     ++aaaaaaaaaaa) {\n}");
292
293  verifyGoogleFormat(
294      "for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
295      "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
296      "}");
297  verifyGoogleFormat(
298      "for (int aaaaaaaaaaa = 1;\n"
299      "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
300      "                                           aaaaaaaaaaaaaaaa,\n"
301      "                                           aaaaaaaaaaaaaaaa,\n"
302      "                                           aaaaaaaaaaaaaaaa);\n"
303      "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
304      "}");
305}
306
307TEST_F(FormatTest, RangeBasedForLoops) {
308  verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
309               "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
310  verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
311               "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
312}
313
314TEST_F(FormatTest, FormatsWhileLoop) {
315  verifyFormat("while (true) {\n}");
316  verifyFormat("while (true)\n"
317               "  f();");
318  verifyFormat("while () {\n}");
319  verifyFormat("while () {\n"
320               "  f();\n"
321               "}");
322}
323
324TEST_F(FormatTest, FormatsDoWhile) {
325  verifyFormat("do {\n"
326               "  do_something();\n"
327               "} while (something());");
328  verifyFormat("do\n"
329               "  do_something();\n"
330               "while (something());");
331}
332
333TEST_F(FormatTest, FormatsSwitchStatement) {
334  verifyFormat("switch (x) {\n"
335               "case 1:\n"
336               "  f();\n"
337               "  break;\n"
338               "case kFoo:\n"
339               "case ns::kBar:\n"
340               "case kBaz:\n"
341               "  break;\n"
342               "default:\n"
343               "  g();\n"
344               "  break;\n"
345               "}");
346  verifyFormat("switch (x) {\n"
347               "case 1: {\n"
348               "  f();\n"
349               "  break;\n"
350               "}\n"
351               "}");
352  verifyFormat("switch (x) {\n"
353               "case 1: {\n"
354               "  f();\n"
355               "  {\n"
356               "    g();\n"
357               "    h();\n"
358               "  }\n"
359               "  break;\n"
360               "}\n"
361               "}");
362  verifyFormat("switch (x) {\n"
363               "case 1: {\n"
364               "  f();\n"
365               "  if (foo) {\n"
366               "    g();\n"
367               "    h();\n"
368               "  }\n"
369               "  break;\n"
370               "}\n"
371               "}");
372  verifyFormat("switch (x) {\n"
373               "case 1: {\n"
374               "  f();\n"
375               "  g();\n"
376               "} break;\n"
377               "}");
378  verifyFormat("switch (test)\n"
379               "  ;");
380
381  verifyGoogleFormat("switch (x) {\n"
382                     "  case 1:\n"
383                     "    f();\n"
384                     "    break;\n"
385                     "  case kFoo:\n"
386                     "  case ns::kBar:\n"
387                     "  case kBaz:\n"
388                     "    break;\n"
389                     "  default:\n"
390                     "    g();\n"
391                     "    break;\n"
392                     "}");
393  verifyGoogleFormat("switch (x) {\n"
394                     "  case 1: {\n"
395                     "    f();\n"
396                     "    break;\n"
397                     "  }\n"
398                     "}");
399  verifyGoogleFormat("switch (test)\n"
400                     "    ;");
401}
402
403TEST_F(FormatTest, FormatsLabels) {
404  verifyFormat("void f() {\n"
405               "  some_code();\n"
406               "test_label:\n"
407               "  some_other_code();\n"
408               "  {\n"
409               "    some_more_code();\n"
410               "  another_label:\n"
411               "    some_more_code();\n"
412               "  }\n"
413               "}");
414  verifyFormat("some_code();\n"
415               "test_label:\n"
416               "some_other_code();");
417}
418
419//===----------------------------------------------------------------------===//
420// Tests for comments.
421//===----------------------------------------------------------------------===//
422
423TEST_F(FormatTest, UnderstandsSingleLineComments) {
424  verifyFormat("// line 1\n"
425               "// line 2\n"
426               "void f() {}\n");
427
428  verifyFormat("void f() {\n"
429               "  // Doesn't do anything\n"
430               "}");
431  verifyFormat("void f(int i,  // some comment (probably for i)\n"
432               "       int j,  // some comment (probably for j)\n"
433               "       int k); // some comment (probably for k)");
434  verifyFormat("void f(int i,\n"
435               "       // some comment (probably for j)\n"
436               "       int j,\n"
437               "       // some comment (probably for k)\n"
438               "       int k);");
439
440  verifyFormat("int i    // This is a fancy variable\n"
441               "    = 5; // with nicely aligned comment.");
442
443  verifyFormat("// Leading comment.\n"
444               "int a; // Trailing comment.");
445  verifyFormat("int a; // Trailing comment\n"
446               "       // on 2\n"
447               "       // or 3 lines.\n"
448               "int b;");
449  verifyFormat("int a; // Trailing comment\n"
450               "\n"
451               "// Leading comment.\n"
452               "int b;");
453  verifyFormat("int a;    // Comment.\n"
454               "          // More details.\n"
455               "int bbbb; // Another comment.");
456  verifyFormat(
457      "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
458      "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   // comment\n"
459      "int cccccccccccccccccccccccccccccc;       // comment\n"
460      "int ddd;                     // looooooooooooooooooooooooong comment\n"
461      "int aaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
462      "int bbbbbbbbbbbbbbbbbbbbb;   // comment\n"
463      "int ccccccccccccccccccc;     // comment");
464
465  verifyFormat("#include \"a\"     // comment\n"
466               "#include \"a/b/c\" // comment");
467  verifyFormat("#include <a>     // comment\n"
468               "#include <a/b/c> // comment");
469
470  verifyFormat("enum E {\n"
471               "  // comment\n"
472               "  VAL_A, // comment\n"
473               "  VAL_B\n"
474               "};");
475
476  verifyFormat(
477      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
478      "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // Trailing comment");
479  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
480               "    // Comment inside a statement.\n"
481               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
482  verifyFormat(
483      "bool aaaaaaaaaaaaa = // comment\n"
484      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
485      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
486
487  verifyFormat("int aaaa; // aaaaa\n"
488               "int aa;   // aaaaaaa",
489               getLLVMStyleWithColumns(20));
490
491  EXPECT_EQ("void f() { // This does something ..\n"
492            "}\n"
493            "int a; // This is unrelated",
494            format("void f()    {     // This does something ..\n"
495                   "  }\n"
496                   "int   a;     // This is unrelated"));
497  EXPECT_EQ("void f() { // This does something ..\n"
498            "}          // awesome..\n"
499            "\n"
500            "int a; // This is unrelated",
501            format("void f()    { // This does something ..\n"
502                   "      } // awesome..\n"
503                   " \n"
504                   "int a;    // This is unrelated"));
505
506  EXPECT_EQ("int i; // single line trailing comment",
507            format("int i;\\\n// single line trailing comment"));
508
509  verifyGoogleFormat("int a;  // Trailing comment.");
510
511  verifyFormat("someFunction(anotherFunction( // Force break.\n"
512               "    parameter));");
513
514  verifyGoogleFormat("#endif  // HEADER_GUARD");
515
516  verifyFormat("const char *test[] = {\n"
517               "  // A\n"
518               "  \"aaaa\",\n"
519               "  // B\n"
520               "  \"aaaaa\",\n"
521               "};");
522  verifyGoogleFormat(
523      "aaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
524      "    aaaaaaaaaaaaaaaaaaaaaa);  // 81 cols with this comment");
525}
526
527TEST_F(FormatTest, UnderstandsMultiLineComments) {
528  verifyFormat("f(/*test=*/ true);");
529  EXPECT_EQ(
530      "f(aaaaaaaaaaaaaaaaaaaaaaaaa, /* Trailing comment for aa... */\n"
531      "  bbbbbbbbbbbbbbbbbbbbbbbbb);",
532      format("f(aaaaaaaaaaaaaaaaaaaaaaaaa ,  /* Trailing comment for aa... */\n"
533             "  bbbbbbbbbbbbbbbbbbbbbbbbb);"));
534  EXPECT_EQ(
535      "f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
536      "  /* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);",
537      format("f(aaaaaaaaaaaaaaaaaaaaaaaaa    ,   \n"
538             "/* Leading comment for bb... */   bbbbbbbbbbbbbbbbbbbbbbbbb);"));
539
540  verifyGoogleFormat("aaaaaaaa(/* parameter 1 */ aaaaaa,\n"
541                     "         /* parameter 2 */ aaaaaa,\n"
542                     "         /* parameter 3 */ aaaaaa,\n"
543                     "         /* parameter 4 */ aaaaaa);");
544}
545
546TEST_F(FormatTest, CommentsInStaticInitializers) {
547  EXPECT_EQ(
548      "static SomeType type = { aaaaaaaaaaaaaaaaaaaa, /* comment */\n"
549      "                         aaaaaaaaaaaaaaaaaaaa /* comment */,\n"
550      "                         /* comment */ aaaaaaaaaaaaaaaaaaaa,\n"
551      "                         aaaaaaaaaaaaaaaaaaaa, // comment\n"
552      "                         aaaaaaaaaaaaaaaaaaaa };",
553      format("static SomeType type = { aaaaaaaaaaaaaaaaaaaa  ,  /* comment */\n"
554             "                   aaaaaaaaaaaaaaaaaaaa   /* comment */ ,\n"
555             "                     /* comment */   aaaaaaaaaaaaaaaaaaaa ,\n"
556             "              aaaaaaaaaaaaaaaaaaaa ,   // comment\n"
557             "                  aaaaaaaaaaaaaaaaaaaa };"));
558  verifyFormat("static SomeType type = { aaaaaaaaaaa, // comment for aa...\n"
559               "                         bbbbbbbbbbb, ccccccccccc };");
560  verifyFormat("static SomeType type = { aaaaaaaaaaa,\n"
561               "                         // comment for bb....\n"
562               "                         bbbbbbbbbbb, ccccccccccc };");
563  verifyGoogleFormat(
564      "static SomeType type = { aaaaaaaaaaa,  // comment for aa...\n"
565      "                         bbbbbbbbbbb, ccccccccccc };");
566  verifyGoogleFormat("static SomeType type = { aaaaaaaaaaa,\n"
567                     "                         // comment for bb....\n"
568                     "                         bbbbbbbbbbb, ccccccccccc };");
569
570  verifyFormat("S s = { { a, b, c },   // Group #1\n"
571               "        { d, e, f },   // Group #2\n"
572               "        { g, h, i } }; // Group #3");
573  verifyFormat("S s = { { // Group #1\n"
574               "          a, b, c },\n"
575               "        { // Group #2\n"
576               "          d, e, f },\n"
577               "        { // Group #3\n"
578               "          g, h, i } };");
579}
580
581//===----------------------------------------------------------------------===//
582// Tests for classes, namespaces, etc.
583//===----------------------------------------------------------------------===//
584
585TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
586  verifyFormat("class A {\n};");
587}
588
589TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
590  verifyFormat("class A {\n"
591               "public:\n"
592               "protected:\n"
593               "private:\n"
594               "  void f() {}\n"
595               "};");
596  verifyGoogleFormat("class A {\n"
597                     " public:\n"
598                     " protected:\n"
599                     " private:\n"
600                     "  void f() {}\n"
601                     "};");
602}
603
604TEST_F(FormatTest, FormatsDerivedClass) {
605  verifyFormat("class A : public B {\n};");
606  verifyFormat("class A : public ::B {\n};");
607
608  verifyFormat(
609      "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
610      "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {\n"
611      "};\n");
612  verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA :\n"
613               "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
614               "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {\n"
615               "};\n");
616  verifyFormat(
617      "class A : public B, public C, public D, public E, public F, public G {\n"
618      "};");
619  verifyFormat("class AAAAAAAAAAAA : public B,\n"
620               "                     public C,\n"
621               "                     public D,\n"
622               "                     public E,\n"
623               "                     public F,\n"
624               "                     public G {\n"
625               "};");
626}
627
628TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
629  verifyFormat("class A {\n} a, b;");
630  verifyFormat("struct A {\n} a, b;");
631  verifyFormat("union A {\n} a;");
632}
633
634TEST_F(FormatTest, FormatsEnum) {
635  verifyFormat("enum {\n"
636               "  Zero,\n"
637               "  One = 1,\n"
638               "  Two = One + 1,\n"
639               "  Three = (One + Two),\n"
640               "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
641               "  Five = (One, Two, Three, Four, 5)\n"
642               "};");
643  verifyFormat("enum Enum {\n"
644               "};");
645  verifyFormat("enum {\n"
646               "};");
647  verifyFormat("enum X E {\n} d;");
648  verifyFormat("enum __attribute__((...)) E {\n} d;");
649  verifyFormat("enum __declspec__((...)) E {\n} d;");
650  verifyFormat("enum X f() {\n  a();\n  return 42;\n}");
651}
652
653TEST_F(FormatTest, FormatsBitfields) {
654  verifyFormat("struct Bitfields {\n"
655               "  unsigned sClass : 8;\n"
656               "  unsigned ValueKind : 2;\n"
657               "};");
658}
659
660TEST_F(FormatTest, FormatsNamespaces) {
661  verifyFormat("namespace some_namespace {\n"
662               "class A {\n};\n"
663               "void f() { f(); }\n"
664               "}");
665  verifyFormat("namespace {\n"
666               "class A {\n};\n"
667               "void f() { f(); }\n"
668               "}");
669  verifyFormat("inline namespace X {\n"
670               "class A {\n};\n"
671               "void f() { f(); }\n"
672               "}");
673  verifyFormat("using namespace some_namespace;\n"
674               "class A {\n};\n"
675               "void f() { f(); }");
676
677  // This code is more common than we thought; if we
678  // layout this correctly the semicolon will go into
679  // its own line, which is undesireable.
680  verifyFormat("namespace {\n};");
681  verifyFormat("namespace {\n"
682               "class A {\n"
683               "};\n"
684               "};");
685}
686
687TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
688
689TEST_F(FormatTest, FormatTryCatch) {
690  // FIXME: Handle try-catch explicitly in the UnwrappedLineParser, then we'll
691  // also not create single-line-blocks.
692  verifyFormat("try {\n"
693               "  throw a * b;\n"
694               "}\n"
695               "catch (int a) {\n"
696               "  // Do nothing.\n"
697               "}\n"
698               "catch (...) {\n"
699               "  exit(42);\n"
700               "}");
701
702  // Function-level try statements.
703  verifyFormat("int f() try { return 4; }\n"
704               "catch (...) {\n"
705               "  return 5;\n"
706               "}");
707  verifyFormat("class A {\n"
708               "  int a;\n"
709               "  A() try : a(0) {}\n"
710               "  catch (...) {\n"
711               "    throw;\n"
712               "  }\n"
713               "};\n");
714}
715
716TEST_F(FormatTest, FormatObjCTryCatch) {
717  verifyFormat("@try {\n"
718               "  f();\n"
719               "}\n"
720               "@catch (NSException e) {\n"
721               "  @throw;\n"
722               "}\n"
723               "@finally {\n"
724               "  exit(42);\n"
725               "}");
726}
727
728TEST_F(FormatTest, StaticInitializers) {
729  verifyFormat("static SomeClass SC = { 1, 'a' };");
730
731  // FIXME: Format like enums if the static initializer does not fit on a line.
732  verifyFormat(
733      "static SomeClass WithALoooooooooooooooooooongName = {\n"
734      "  100000000, \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
735      "};");
736
737  verifyFormat(
738      "static SomeClass = { a, b, c, d, e, f, g, h, i, j,\n"
739      "                     looooooooooooooooooooooooooooooooooongname,\n"
740      "                     looooooooooooooooooooooooooooooong };");
741  // Allow bin-packing in static initializers as this would often lead to
742  // terrible results, e.g.:
743  verifyGoogleFormat(
744      "static SomeClass = { a, b, c, d, e, f, g, h, i, j,\n"
745      "                     looooooooooooooooooooooooooooooooooongname,\n"
746      "                     looooooooooooooooooooooooooooooong };");
747}
748
749TEST_F(FormatTest, NestedStaticInitializers) {
750  verifyFormat("static A x = { { {} } };\n");
751  verifyFormat("static A x = { { { init1, init2, init3, init4 },\n"
752               "                 { init1, init2, init3, init4 } } };");
753
754  verifyFormat("somes Status::global_reps[3] = {\n"
755               "  { kGlobalRef, OK_CODE, NULL, NULL, NULL },\n"
756               "  { kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL },\n"
757               "  { kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL }\n"
758               "};");
759  verifyGoogleFormat("somes Status::global_reps[3] = {\n"
760                     "  { kGlobalRef, OK_CODE, NULL, NULL, NULL },\n"
761                     "  { kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL },\n"
762                     "  { kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL }\n"
763                     "};");
764  verifyFormat(
765      "CGRect cg_rect = { { rect.fLeft, rect.fTop },\n"
766      "                   { rect.fRight - rect.fLeft, rect.fBottom - rect.fTop"
767      " } };");
768
769  verifyFormat(
770      "SomeArrayOfSomeType a = { { { 1, 2, 3 }, { 1, 2, 3 },\n"
771      "                            { 111111111111111111111111111111,\n"
772      "                              222222222222222222222222222222,\n"
773      "                              333333333333333333333333333333 },\n"
774      "                            { 1, 2, 3 }, { 1, 2, 3 } } };");
775  verifyFormat(
776      "SomeArrayOfSomeType a = { { { 1, 2, 3 } }, { { 1, 2, 3 } },\n"
777      "                          { { 111111111111111111111111111111,\n"
778      "                              222222222222222222222222222222,\n"
779      "                              333333333333333333333333333333 } },\n"
780      "                          { { 1, 2, 3 } }, { { 1, 2, 3 } } };");
781
782  // FIXME: We might at some point want to handle this similar to parameter
783  // lists, where we have an option to put each on a single line.
784  verifyFormat(
785      "struct {\n"
786      "  unsigned bit;\n"
787      "  const char *const name;\n"
788      "} kBitsToOs[] = { { kOsMac, \"Mac\" }, { kOsWin, \"Windows\" },\n"
789      "                  { kOsLinux, \"Linux\" }, { kOsCrOS, \"Chrome OS\" } };");
790}
791
792TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
793  verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
794               "                      \\\n"
795               "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
796}
797
798TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
799  verifyFormat("virtual void write(ELFWriter *writerrr,\n"
800               "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
801}
802
803TEST_F(FormatTest, LayoutUnknownPPDirective) {
804  EXPECT_EQ("#123 \"A string literal\"",
805            format("   #     123    \"A string literal\""));
806  EXPECT_EQ("#;", format("#;"));
807  verifyFormat("#\n;\n;\n;");
808}
809
810TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
811  EXPECT_EQ("#line 42 \"test\"\n",
812            format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
813  EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
814                                    getLLVMStyleWithColumns(12)));
815}
816
817TEST_F(FormatTest, EndOfFileEndsPPDirective) {
818  EXPECT_EQ("#line 42 \"test\"",
819            format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
820  EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
821}
822
823TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
824  // If the macro fits in one line, we still do not get the full
825  // line, as only the next line decides whether we need an escaped newline and
826  // thus use the last column.
827  verifyFormat("#define A(B)", getLLVMStyleWithColumns(13));
828
829  verifyFormat("#define A( \\\n    B)", getLLVMStyleWithColumns(12));
830  verifyFormat("#define AA(\\\n    B)", getLLVMStyleWithColumns(12));
831  verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
832
833  verifyFormat("#define A A\n#define A A");
834  verifyFormat("#define A(X) A\n#define A A");
835
836  verifyFormat("#define Something Other", getLLVMStyleWithColumns(24));
837  verifyFormat("#define Something     \\\n"
838               "  Other",
839               getLLVMStyleWithColumns(23));
840}
841
842TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
843  EXPECT_EQ("// some comment\n"
844            "#include \"a.h\"\n"
845            "#define A(A,\\\n"
846            "          B)\n"
847            "#include \"b.h\"\n"
848            "// some comment\n",
849            format("  // some comment\n"
850                   "  #include \"a.h\"\n"
851                   "#define A(A,\\\n"
852                   "    B)\n"
853                   "    #include \"b.h\"\n"
854                   " // some comment\n",
855                   getLLVMStyleWithColumns(13)));
856}
857
858TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
859
860TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
861  EXPECT_EQ("#define A    \\\n"
862            "  c;         \\\n"
863            "  e;\n"
864            "f;",
865            format("#define A c; e;\n"
866                   "f;",
867                   getLLVMStyleWithColumns(14)));
868}
869
870TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
871
872TEST_F(FormatTest, LayoutSingleUnwrappedLineInMacro) {
873  EXPECT_EQ("# define A\\\n  b;",
874            format("# define A b;", 11, 2, getLLVMStyleWithColumns(11)));
875}
876
877TEST_F(FormatTest, MacroDefinitionInsideStatement) {
878  EXPECT_EQ("int x,\n"
879            "#define A\n"
880            "    y;",
881            format("int x,\n#define A\ny;"));
882}
883
884TEST_F(FormatTest, HashInMacroDefinition) {
885  verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
886  verifyFormat("#define A \\\n"
887               "  {       \\\n"
888               "    f(#c);\\\n"
889               "  }",
890               getLLVMStyleWithColumns(11));
891
892  verifyFormat("#define A(X)         \\\n"
893               "  void function##X()",
894               getLLVMStyleWithColumns(22));
895
896  verifyFormat("#define A(a, b, c)   \\\n"
897               "  void a##b##c()",
898               getLLVMStyleWithColumns(22));
899
900  verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
901}
902
903TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
904  verifyFormat("#define A (1)");
905}
906
907TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
908  EXPECT_EQ("#define A b;", format("#define A \\\n"
909                                   "          \\\n"
910                                   "  b;",
911                                   getLLVMStyleWithColumns(25)));
912  EXPECT_EQ("#define A \\\n"
913            "          \\\n"
914            "  a;      \\\n"
915            "  b;",
916            format("#define A \\\n"
917                   "          \\\n"
918                   "  a;      \\\n"
919                   "  b;",
920                   getLLVMStyleWithColumns(11)));
921  EXPECT_EQ("#define A \\\n"
922            "  a;      \\\n"
923            "          \\\n"
924            "  b;",
925            format("#define A \\\n"
926                   "  a;      \\\n"
927                   "          \\\n"
928                   "  b;",
929                   getLLVMStyleWithColumns(11)));
930}
931
932TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
933  // FIXME: Improve formatting of case labels in macros.
934  verifyFormat("#define SOMECASES  \\\n"
935               "case 1:            \\\n"
936               "  case 2\n",
937               getLLVMStyleWithColumns(20));
938
939  verifyFormat("#define A template <typename T>");
940  verifyFormat("#define STR(x) #x\n"
941               "f(STR(this_is_a_string_literal{));");
942}
943
944TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
945  EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
946}
947
948TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
949  verifyFormat("{\n  { a #c; }\n}");
950}
951
952TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
953  EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
954            format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
955  EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
956            format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
957}
958
959TEST_F(FormatTest, EscapedNewlineAtStartOfTokenInMacroDefinition) {
960  EXPECT_EQ(
961      "#define A \\\n  int i;  \\\n  int j;",
962      format("#define A \\\nint i;\\\n  int j;", getLLVMStyleWithColumns(11)));
963}
964
965TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
966  verifyFormat("#define A \\\n"
967               "  int v(  \\\n"
968               "      a); \\\n"
969               "  int i;",
970               getLLVMStyleWithColumns(11));
971}
972
973TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
974  EXPECT_EQ(
975      "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
976      "                      \\\n"
977      "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
978      "\n"
979      "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
980      "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
981      format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
982             "\\\n"
983             "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
984             "  \n"
985             "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
986             "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
987}
988
989TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
990  EXPECT_EQ("int\n"
991            "#define A\n"
992            "    a;",
993            format("int\n#define A\na;"));
994  verifyFormat("functionCallTo(\n"
995               "    someOtherFunction(\n"
996               "        withSomeParameters, whichInSequence,\n"
997               "        areLongerThanALine(andAnotherCall,\n"
998               "#define A B\n"
999               "                           withMoreParamters,\n"
1000               "                           whichStronglyInfluenceTheLayout),\n"
1001               "        andMoreParameters), trailing);",
1002               getLLVMStyleWithColumns(69));
1003}
1004
1005TEST_F(FormatTest, LayoutBlockInsideParens) {
1006  EXPECT_EQ("functionCall({\n"
1007            "  int i;\n"
1008            "});",
1009            format(" functionCall ( {int i;} );"));
1010}
1011
1012TEST_F(FormatTest, LayoutBlockInsideStatement) {
1013  EXPECT_EQ("SOME_MACRO { int i; }\n"
1014            "int i;",
1015            format("  SOME_MACRO  {int i;}  int i;"));
1016}
1017
1018TEST_F(FormatTest, LayoutNestedBlocks) {
1019  verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
1020               "  struct s {\n"
1021               "    int i;\n"
1022               "  };\n"
1023               "  s kBitsToOs[] = { { 10 } };\n"
1024               "  for (int i = 0; i < 10; ++i)\n"
1025               "    return;\n"
1026               "}");
1027}
1028
1029TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
1030  EXPECT_EQ("{}", format("{}"));
1031
1032  // Negative test for enum.
1033  verifyFormat("enum E {\n};");
1034
1035  // Note that when there's a missing ';', we still join...
1036  verifyFormat("enum E {}");
1037}
1038
1039//===----------------------------------------------------------------------===//
1040// Line break tests.
1041//===----------------------------------------------------------------------===//
1042
1043TEST_F(FormatTest, FormatsFunctionDefinition) {
1044  verifyFormat("void f(int a, int b, int c, int d, int e, int f, int g,"
1045               " int h, int j, int f,\n"
1046               "       int c, int ddddddddddddd) {\n}");
1047}
1048
1049TEST_F(FormatTest, FormatsAwesomeMethodCall) {
1050  verifyFormat(
1051      "SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
1052      "                       parameter, parameter, parameter)),\n"
1053      "                   SecondLongCall(parameter));");
1054}
1055
1056TEST_F(FormatTest, PreventConfusingIndents) {
1057  verifyFormat(
1058      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1059      "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
1060      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
1061      "    aaaaaaaaaaaaaaaaaaaaaaaa);");
1062  verifyFormat(
1063      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[\n"
1064      "    aaaaaaaaaaaaaaaaaaaaaaaa[\n"
1065      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa],\n"
1066      "    aaaaaaaaaaaaaaaaaaaaaaaa];");
1067  verifyFormat(
1068      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
1069      "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
1070      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
1071      "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
1072  verifyFormat("int a = bbbb && ccc && fffff(\n"
1073               "#define A Just forcing a new line\n"
1074               "                           ddd);");
1075}
1076
1077TEST_F(FormatTest, ConstructorInitializers) {
1078  verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
1079  verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
1080               getLLVMStyleWithColumns(45));
1081  verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {\n}",
1082               getLLVMStyleWithColumns(44));
1083  verifyFormat("Constructor()\n"
1084               "    : Inttializer(FitsOnTheLine) {\n}",
1085               getLLVMStyleWithColumns(43));
1086
1087  verifyFormat(
1088      "SomeClass::Constructor()\n"
1089      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {\n}");
1090
1091  verifyFormat(
1092      "SomeClass::Constructor()\n"
1093      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
1094      "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {\n}");
1095  verifyFormat(
1096      "SomeClass::Constructor()\n"
1097      "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
1098      "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {\n}");
1099
1100  verifyFormat("Constructor()\n"
1101               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
1102               "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1103               "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
1104               "      aaaaaaaaaaaaaaaaaaaaaaa() {\n}");
1105
1106  verifyFormat("Constructor()\n"
1107               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1108               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
1109
1110  // Here a line could be saved by splitting the second initializer onto two
1111  // lines, but that is not desireable.
1112  verifyFormat(
1113      "Constructor()\n"
1114      "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
1115      "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
1116      "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
1117
1118  FormatStyle OnePerLine = getLLVMStyle();
1119  OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
1120  verifyFormat("SomeClass::Constructor()\n"
1121               "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
1122               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
1123               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {\n}",
1124               OnePerLine);
1125  verifyFormat("SomeClass::Constructor()\n"
1126               "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
1127               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
1128               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {\n}",
1129               OnePerLine);
1130  verifyFormat("MyClass::MyClass(int var)\n"
1131               "    : some_var_(var),            // 4 space indent\n"
1132               "      some_other_var_(var + 1) { // lined up\n"
1133               "}",
1134               OnePerLine);
1135
1136  // This test takes VERY long when memoization is broken.
1137  std::string input = "Constructor()\n"
1138                      "    : aaaa(a,\n";
1139  for (unsigned i = 0, e = 80; i != e; ++i) {
1140    input += "           a,\n";
1141  }
1142  input += "           a) {\n}";
1143  verifyGoogleFormat(input);
1144}
1145
1146TEST_F(FormatTest, BreaksAsHighAsPossible) {
1147  verifyFormat(
1148      "if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
1149      "    (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
1150      "  f();");
1151}
1152
1153TEST_F(FormatTest, BreaksDesireably) {
1154  verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
1155               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
1156               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
1157  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1158               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1159               "}");
1160
1161  verifyFormat(
1162      "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1163      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
1164
1165  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1166               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1167               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
1168
1169  verifyFormat(
1170      "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1171      "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
1172      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1173      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
1174
1175  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
1176               "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1177
1178  verifyFormat(
1179      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
1180      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1181  verifyFormat(
1182      "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1183      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
1184  verifyFormat(
1185      "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1186      "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
1187
1188  // This test case breaks on an incorrect memoization, i.e. an optimization not
1189  // taking into account the StopAt value.
1190  verifyFormat(
1191      "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
1192      "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
1193      "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
1194      "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1195
1196  verifyFormat("{\n  {\n    {\n"
1197               "      Annotation.SpaceRequiredBefore =\n"
1198               "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
1199               "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
1200               "    }\n  }\n}");
1201}
1202
1203TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
1204  verifyGoogleFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
1205                     "  aaaaaaaaaaaaaaaaaaaa,\n"
1206                     "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);");
1207  verifyGoogleFormat(
1208      "aaaaaaa(aaaaaaaaaaaaa,\n"
1209      "        aaaaaaaaaaaaa,\n"
1210      "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));");
1211  verifyGoogleFormat(
1212      "aaaaaaaa(aaaaaaaaaaaaa,\n"
1213      "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1214      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
1215      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1216      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
1217  verifyGoogleFormat(
1218      "aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
1219      "    .aaaaaaaaaaaaaaaaaa();");
1220  verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1221                     "    aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);");
1222
1223  verifyGoogleFormat(
1224      "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1225      "             aaaaaaaaaaaa,\n"
1226      "             aaaaaaaaaaaa);");
1227  verifyGoogleFormat(
1228      "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
1229      "                               ddddddddddddddddddddddddddddd),\n"
1230      "             test);");
1231
1232  verifyGoogleFormat(
1233      "std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
1234      "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
1235      "            aaaaaaaaaaaaaaaaaaaaaaa> aaaaaaaaaaaaaaaaaa;");
1236  verifyGoogleFormat("a(\"a\"\n"
1237                     "  \"a\",\n"
1238                     "  a);");
1239
1240  FormatStyle Style = getGoogleStyle();
1241  Style.AllowAllParametersOfDeclarationOnNextLine = false;
1242  verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
1243               "                aaaaaaaaa,\n"
1244               "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
1245               Style);
1246  verifyFormat(
1247      "void f() {\n"
1248      "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
1249      "      .aaaaaaa();\n"
1250      "}",
1251      Style);
1252}
1253
1254TEST_F(FormatTest, FormatsBuilderPattern) {
1255  verifyFormat(
1256      "return llvm::StringSwitch<Reference::Kind>(name)\n"
1257      "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
1258      "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME).StartsWith(\".init\", ORDER_INIT)\n"
1259      "    .StartsWith(\".fini\", ORDER_FINI).StartsWith(\".hash\", ORDER_HASH)\n"
1260      "    .Default(ORDER_TEXT);\n");
1261
1262  verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
1263               "       aaaaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
1264  verifyFormat(
1265      "aaaaaaa->aaaaaaa\n"
1266      "    ->aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
1267      "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
1268  verifyFormat(
1269      "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
1270      "                                        aaaaaaaaaaaaaa);");
1271  verifyFormat(
1272      "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa = aaaaaa->aaaaaaaaaaaa()\n"
1273      "    ->aaaaaaaaaaaaaaaa(\n"
1274      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
1275      "    ->aaaaaaaaaaaaaaaaa();");
1276}
1277
1278TEST_F(FormatTest, DoesNotBreakTrailingAnnotation) {
1279  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
1280               "    GUARDED_BY(aaaaaaaaaaaaa);");
1281  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
1282               "    GUARDED_BY(aaaaaaaaaaaaa);");
1283  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
1284               "    GUARDED_BY(aaaaaaaaaaaaa) {\n}");
1285}
1286
1287TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
1288  verifyFormat(
1289      "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
1290      "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
1291  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
1292               "    ccccccccccccccccccccccccc) {\n}");
1293  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
1294               "    ccccccccccccccccccccccccc) {\n}");
1295  verifyFormat(
1296      "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
1297      "    ccccccccccccccccccccccccc) {\n}");
1298  verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
1299               "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
1300               "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
1301               "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
1302  verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
1303               "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
1304               "    aaaaaaaaaaaaaaa != aa) {\n}");
1305}
1306
1307TEST_F(FormatTest, BreaksAfterAssignments) {
1308  verifyFormat(
1309      "unsigned Cost =\n"
1310      "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
1311      "                        SI->getPointerAddressSpaceee());\n");
1312  verifyFormat(
1313      "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
1314      "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
1315
1316  verifyFormat(
1317      "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa()\n"
1318      "    .aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
1319}
1320
1321TEST_F(FormatTest, AlignsAfterAssignments) {
1322  verifyFormat(
1323      "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
1324      "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
1325  verifyFormat(
1326      "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
1327      "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
1328  verifyFormat(
1329      "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
1330      "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
1331  verifyFormat(
1332      "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
1333      "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
1334  verifyFormat("double LooooooooooooooooooooooooongResult =\n"
1335               "    aaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaa +\n"
1336               "    aaaaaaaaaaaaaaaaaaaaaaaa;");
1337}
1338
1339TEST_F(FormatTest, AlignsAfterReturn) {
1340  verifyFormat(
1341      "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
1342      "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
1343  verifyFormat(
1344      "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
1345      "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
1346}
1347
1348TEST_F(FormatTest, BreaksConditionalExpressions) {
1349  verifyFormat(
1350      "aaaa(aaaaaaaaaaaaaaaaaaaa,\n"
1351      "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1352      "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1353  verifyFormat(
1354      "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1355      "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1356  verifyFormat(
1357      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
1358      "                                                    : aaaaaaaaaaaaa);");
1359  verifyFormat(
1360      "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1361      "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaa\n"
1362      "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1363      "                   aaaaaaaaaaaaa);");
1364  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1365               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1366               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
1367               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1368               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1369  verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1370               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1371               "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1372               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
1373               "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1374               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
1375               "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1376
1377  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1378               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1379               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
1380
1381  // FIXME: The trailing third parameter here is kind of hidden. Prefer putting
1382  // it on the next line.
1383  verifyFormat(
1384      "unsigned Indent =\n"
1385      "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0\n"
1386      "                              ? IndentForLevel[TheLine.Level]\n"
1387      "                              : TheLine * 2, TheLine.InPPDirective,\n"
1388      "           PreviousEndOfLineColumn);",
1389      getLLVMStyleWithColumns(70));
1390
1391}
1392
1393TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
1394  verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
1395               "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
1396  verifyFormat("bool a = true, b = false;");
1397
1398  // FIXME: Indentation looks weird.
1399  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
1400               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
1401               "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
1402               "     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
1403
1404  // FIXME: This is bad as we hide "d".
1405  verifyFormat(
1406      "bool aaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
1407      "                             cccccccccccccccccccccccccccc, d = e && f;");
1408
1409}
1410
1411TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
1412  verifyFormat("arr[foo ? bar : baz];");
1413  verifyFormat("f()[foo ? bar : baz];");
1414  verifyFormat("(a + b)[foo ? bar : baz];");
1415  verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
1416}
1417
1418TEST_F(FormatTest, AlignsStringLiterals) {
1419  verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
1420               "                                      \"short literal\");");
1421  verifyFormat(
1422      "looooooooooooooooooooooooongFunction(\n"
1423      "    \"short literal\"\n"
1424      "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
1425  verifyFormat("someFunction(\"Always break between multi-line\"\n"
1426               "             \" string literals\",\n"
1427               "             and, other, parameters);");
1428}
1429
1430TEST_F(FormatTest, AlignsPipes) {
1431  verifyFormat(
1432      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1433      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1434      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
1435  verifyFormat(
1436      "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
1437      "                     << aaaaaaaaaaaaaaaaaaaa;");
1438  verifyFormat(
1439      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1440      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
1441  verifyFormat(
1442      "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
1443      "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
1444      "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
1445  verifyFormat(
1446      "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1447      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
1448      "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
1449
1450  verifyFormat("return out << \"somepacket = {\\n\"\n"
1451               "           << \"  aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
1452               "           << \"  bbbb = \" << pkt.bbbb << \"\\n\"\n"
1453               "           << \"  cccccc = \" << pkt.cccccc << \"\\n\"\n"
1454               "           << \"  ddd = [\" << pkt.ddd << \"]\\n\"\n"
1455               "           << \"}\";");
1456
1457  verifyFormat(
1458      "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
1459      "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
1460      "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
1461      "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
1462      "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
1463}
1464
1465TEST_F(FormatTest, UnderstandsEquals) {
1466  verifyFormat(
1467      "aaaaaaaaaaaaaaaaa =\n"
1468      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
1469  verifyFormat(
1470      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
1471      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
1472  verifyFormat(
1473      "if (a) {\n"
1474      "  f();\n"
1475      "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
1476      "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1477      "}");
1478
1479  verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
1480               "        100000000 + 10000000) {\n}");
1481}
1482
1483TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
1484  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
1485               "    .looooooooooooooooooooooooooooooooooooooongFunction();");
1486
1487  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
1488               "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
1489
1490  verifyFormat(
1491      "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
1492      "                                                          Parameter2);");
1493
1494  verifyFormat(
1495      "ShortObject->shortFunction(\n"
1496      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
1497      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
1498
1499  verifyFormat("loooooooooooooongFunction(\n"
1500               "    LoooooooooooooongObject->looooooooooooooooongFunction());");
1501
1502  verifyFormat(
1503      "function(LoooooooooooooooooooooooooooooooooooongObject\n"
1504      "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
1505
1506  verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
1507               "    .WillRepeatedly(Return(SomeValue));");
1508  verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)]\n"
1509               "    .insert(ccccccccccccccccccccccc);");
1510
1511  verifyGoogleFormat(
1512      "aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
1513      "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
1514      "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
1515      "                         aaaaaaaaaaaaaaaaaaa,\n"
1516      "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1517
1518  // Here, it is not necessary to wrap at "." or "->".
1519  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
1520               "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
1521  verifyFormat(
1522      "aaaaaaaaaaa->aaaaaaaaa(\n"
1523      "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1524      "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
1525
1526  verifyFormat(
1527      "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1528      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
1529}
1530
1531TEST_F(FormatTest, WrapsTemplateDeclarations) {
1532  verifyFormat("template <typename T>\n"
1533               "virtual void loooooooooooongFunction(int Param1, int Param2);");
1534  verifyFormat(
1535      "template <typename T>\n"
1536      "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
1537  verifyFormat("template <typename T>\n"
1538               "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
1539               "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
1540  verifyFormat(
1541      "template <typename T>\n"
1542      "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
1543      "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
1544  verifyFormat(
1545      "template <typename T>\n"
1546      "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
1547      "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
1548      "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1549  verifyFormat("template <typename T>\n"
1550               "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1551               "    int aaaaaaaaaaaaaaaaa);");
1552  verifyFormat(
1553      "template <typename T1, typename T2 = char, typename T3 = char,\n"
1554      "          typename T4 = char>\n"
1555      "void f();");
1556  verifyFormat(
1557      "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
1558      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1559
1560  verifyFormat("a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
1561               "    a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));");
1562}
1563
1564TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
1565  verifyFormat(
1566      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
1567      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
1568  verifyFormat(
1569      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
1570      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1571      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
1572
1573  // FIXME: Should we have an extra indent after the second break?
1574  verifyFormat(
1575      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
1576      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
1577      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
1578
1579  // FIXME: Look into whether we should indent 4 from the start or 4 from
1580  // "bbbbb..." here instead of what we are doing now.
1581  verifyFormat(
1582      "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
1583      "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
1584
1585  // Breaking at nested name specifiers is generally not desirable.
1586  verifyFormat(
1587      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1588      "    aaaaaaaaaaaaaaaaaaaaaaa);");
1589
1590  verifyFormat(
1591      "aaaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
1592      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1593      "                   aaaaaaaaaaaaaaaaaaaaa);",
1594      getLLVMStyleWithColumns(74));
1595}
1596
1597TEST_F(FormatTest, UnderstandsTemplateParameters) {
1598  verifyFormat("A<int> a;");
1599  verifyFormat("A<A<A<int> > > a;");
1600  verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
1601  verifyFormat("bool x = a < 1 || 2 > a;");
1602  verifyFormat("bool x = 5 < f<int>();");
1603  verifyFormat("bool x = f<int>() > 5;");
1604  verifyFormat("bool x = 5 < a<int>::x;");
1605  verifyFormat("bool x = a < 4 ? a > 2 : false;");
1606  verifyFormat("bool x = f() ? a < 2 : a > 2;");
1607
1608  verifyGoogleFormat("A<A<int>> a;");
1609  verifyGoogleFormat("A<A<A<int>>> a;");
1610  verifyGoogleFormat("A<A<A<A<int>>>> a;");
1611  verifyGoogleFormat("A<A<int> > a;");
1612  verifyGoogleFormat("A<A<A<int> > > a;");
1613  verifyGoogleFormat("A<A<A<A<int> > > > a;");
1614  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
1615  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
1616
1617  verifyFormat("test >> a >> b;");
1618  verifyFormat("test << a >> b;");
1619
1620  verifyFormat("f<int>();");
1621  verifyFormat("template <typename T> void f() {}");
1622}
1623
1624TEST_F(FormatTest, UnderstandsUnaryOperators) {
1625  verifyFormat("int a = -2;");
1626  verifyFormat("f(-1, -2, -3);");
1627  verifyFormat("a[-1] = 5;");
1628  verifyFormat("int a = 5 + -2;");
1629  verifyFormat("if (i == -1) {\n}");
1630  verifyFormat("if (i != -1) {\n}");
1631  verifyFormat("if (i > -1) {\n}");
1632  verifyFormat("if (i < -1) {\n}");
1633  verifyFormat("++(a->f());");
1634  verifyFormat("--(a->f());");
1635  verifyFormat("(a->f())++;");
1636  verifyFormat("a[42]++;");
1637  verifyFormat("if (!(a->f())) {\n}");
1638
1639  verifyFormat("a-- > b;");
1640  verifyFormat("b ? -a : c;");
1641  verifyFormat("n * sizeof char16;");
1642  verifyFormat("n * alignof char16;");
1643  verifyFormat("sizeof(char);");
1644  verifyFormat("alignof(char);");
1645
1646  verifyFormat("return -1;");
1647  verifyFormat("switch (a) {\n"
1648               "case -1:\n"
1649               "  break;\n"
1650               "}");
1651
1652  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { -5, +3 };");
1653  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { +5, -3 };");
1654
1655  verifyFormat("int a = /* confusing comment */ -1;");
1656  // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
1657  verifyFormat("int a = i /* confusing comment */++;");
1658}
1659
1660TEST_F(FormatTest, UndestandsOverloadedOperators) {
1661  verifyFormat("bool operator<();");
1662  verifyFormat("bool operator>();");
1663  verifyFormat("bool operator=();");
1664  verifyFormat("bool operator==();");
1665  verifyFormat("bool operator!=();");
1666  verifyFormat("int operator+();");
1667  verifyFormat("int operator++();");
1668  verifyFormat("bool operator();");
1669  verifyFormat("bool operator()();");
1670  verifyFormat("bool operator[]();");
1671  verifyFormat("operator bool();");
1672  verifyFormat("operator int();");
1673  verifyFormat("operator void *();");
1674  verifyFormat("operator SomeType<int>();");
1675  verifyFormat("operator SomeType<int, int>();");
1676  verifyFormat("operator SomeType<SomeType<int> >();");
1677  verifyFormat("void *operator new(std::size_t size);");
1678  verifyFormat("void *operator new[](std::size_t size);");
1679  verifyFormat("void operator delete(void *ptr);");
1680  verifyFormat("void operator delete[](void *ptr);");
1681
1682  verifyFormat(
1683      "ostream &operator<<(ostream &OutputStream,\n"
1684      "                    SomeReallyLongType WithSomeReallyLongValue);");
1685
1686  verifyGoogleFormat("operator void*();");
1687  verifyGoogleFormat("operator SomeType<SomeType<int>>();");
1688}
1689
1690TEST_F(FormatTest, UnderstandsNewAndDelete) {
1691  verifyFormat("A *a = new A;");
1692  verifyFormat("A *a = new (placement) A;");
1693  verifyFormat("delete a;");
1694  verifyFormat("delete (A *)a;");
1695}
1696
1697TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
1698  verifyFormat("int *f(int *a) {}");
1699  verifyFormat("int main(int argc, char **argv) {}");
1700  verifyFormat("Test::Test(int b) : a(b * b) {}");
1701  verifyIndependentOfContext("f(a, *a);");
1702  verifyIndependentOfContext("f(*a);");
1703  verifyIndependentOfContext("int a = b * 10;");
1704  verifyIndependentOfContext("int a = 10 * b;");
1705  verifyIndependentOfContext("int a = b * c;");
1706  verifyIndependentOfContext("int a += b * c;");
1707  verifyIndependentOfContext("int a -= b * c;");
1708  verifyIndependentOfContext("int a *= b * c;");
1709  verifyIndependentOfContext("int a /= b * c;");
1710  verifyIndependentOfContext("int a = *b;");
1711  verifyIndependentOfContext("int a = *b * c;");
1712  verifyIndependentOfContext("int a = b * *c;");
1713  verifyIndependentOfContext("return 10 * b;");
1714  verifyIndependentOfContext("return *b * *c;");
1715  verifyIndependentOfContext("return a & ~b;");
1716  verifyIndependentOfContext("f(b ? *c : *d);");
1717  verifyIndependentOfContext("int a = b ? *c : *d;");
1718  verifyIndependentOfContext("*b = a;");
1719  verifyIndependentOfContext("a * ~b;");
1720  verifyIndependentOfContext("a * !b;");
1721  verifyIndependentOfContext("a * +b;");
1722  verifyIndependentOfContext("a * -b;");
1723  verifyIndependentOfContext("a * ++b;");
1724  verifyIndependentOfContext("a * --b;");
1725  verifyIndependentOfContext("a[4] * b;");
1726  verifyIndependentOfContext("f() * b;");
1727  verifyIndependentOfContext("a * [self dostuff];");
1728  verifyIndependentOfContext("a * (a + b);");
1729  verifyIndependentOfContext("(a *)(a + b);");
1730  verifyIndependentOfContext("int *pa = (int *)&a;");
1731  verifyIndependentOfContext("return sizeof(int **);");
1732  verifyIndependentOfContext("return sizeof(int ******);");
1733  verifyIndependentOfContext("return (int **&)a;");
1734  verifyGoogleFormat("return sizeof(int**);");
1735  verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
1736  verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
1737  // FIXME: The newline is wrong.
1738  verifyFormat("auto a = [](int **&, int ***) {}\n;");
1739
1740  verifyIndependentOfContext("InvalidRegions[*R] = 0;");
1741
1742  verifyIndependentOfContext("A<int *> a;");
1743  verifyIndependentOfContext("A<int **> a;");
1744  verifyIndependentOfContext("A<int *, int *> a;");
1745  verifyIndependentOfContext(
1746      "const char *const p = reinterpret_cast<const char *const>(q);");
1747  verifyIndependentOfContext("A<int **, int **> a;");
1748  verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
1749
1750  verifyFormat(
1751      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1752      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1753
1754  verifyGoogleFormat("int main(int argc, char** argv) {}");
1755  verifyGoogleFormat("A<int*> a;");
1756  verifyGoogleFormat("A<int**> a;");
1757  verifyGoogleFormat("A<int*, int*> a;");
1758  verifyGoogleFormat("A<int**, int**> a;");
1759  verifyGoogleFormat("f(b ? *c : *d);");
1760  verifyGoogleFormat("int a = b ? *c : *d;");
1761  verifyGoogleFormat("Type* t = **x;");
1762  verifyGoogleFormat("Type* t = *++*x;");
1763  verifyGoogleFormat("*++*x;");
1764  verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
1765  verifyGoogleFormat("Type* t = x++ * y;");
1766  verifyGoogleFormat(
1767      "const char* const p = reinterpret_cast<const char* const>(q);");
1768
1769  verifyIndependentOfContext("a = *(x + y);");
1770  verifyIndependentOfContext("a = &(x + y);");
1771  verifyIndependentOfContext("*(x + y).call();");
1772  verifyIndependentOfContext("&(x + y)->call();");
1773  verifyIndependentOfContext("&(*I).first");
1774
1775  verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
1776  verifyFormat(
1777      "int *MyValues = {\n"
1778      "  *A, // Operator detection might be confused by the '{'\n"
1779      "  *BB // Operator detection might be confused by previous comment\n"
1780      "};");
1781
1782  verifyIndependentOfContext("if (int *a = &b)");
1783  verifyIndependentOfContext("if (int &a = *b)");
1784  verifyIndependentOfContext("if (a & b[i])");
1785  verifyIndependentOfContext("if (a::b::c::d & b[i])");
1786  verifyIndependentOfContext("if (*b[i])");
1787  verifyIndependentOfContext("if (int *a = (&b))");
1788  verifyIndependentOfContext("while (int *a = &b)");
1789  verifyFormat("void f() {\n"
1790               "  for (const int &v : Values) {\n"
1791               "  }\n"
1792               "}");
1793  verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
1794  verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
1795
1796  verifyIndependentOfContext("A = new SomeType *[Length]();");
1797  verifyGoogleFormat("A = new SomeType* [Length]();");
1798
1799  EXPECT_EQ("int *a;\n"
1800            "int *a;\n"
1801            "int *a;",
1802            format("int *a;\n"
1803                   "int* a;\n"
1804                   "int *a;",
1805                   getGoogleStyle()));
1806  EXPECT_EQ("int* a;\n"
1807            "int* a;\n"
1808            "int* a;",
1809            format("int* a;\n"
1810                   "int* a;\n"
1811                   "int *a;",
1812                   getGoogleStyle()));
1813  EXPECT_EQ("int *a;\n"
1814            "int *a;\n"
1815            "int *a;",
1816            format("int *a;\n"
1817                   "int * a;\n"
1818                   "int *  a;",
1819                   getGoogleStyle()));
1820}
1821
1822TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
1823  verifyFormat("void f() {\n"
1824               "  x[aaaaaaaaa -\n"
1825               "      b] = 23;\n"
1826               "}",
1827               getLLVMStyleWithColumns(15));
1828}
1829
1830TEST_F(FormatTest, FormatsCasts) {
1831  verifyFormat("Type *A = static_cast<Type *>(P);");
1832  verifyFormat("Type *A = (Type *)P;");
1833  verifyFormat("Type *A = (vector<Type *, int *>)P;");
1834  verifyFormat("int a = (int)(2.0f);");
1835
1836  // FIXME: These also need to be identified.
1837  verifyFormat("int a = (int) 2.0f;");
1838  verifyFormat("int a = (int) * b;");
1839
1840  // These are not casts.
1841  verifyFormat("void f(int *) {}");
1842  verifyFormat("f(foo)->b;");
1843  verifyFormat("f(foo).b;");
1844  verifyFormat("f(foo)(b);");
1845  verifyFormat("f(foo)[b];");
1846  verifyFormat("[](foo) { return 4; }(bar)];");
1847  verifyFormat("(*funptr)(foo)[4];");
1848  verifyFormat("funptrs[4](foo)[4];");
1849  verifyFormat("void f(int *);");
1850  verifyFormat("void f(int *) = 0;");
1851  verifyFormat("void f(SmallVector<int>) {}");
1852  verifyFormat("void f(SmallVector<int>);");
1853  verifyFormat("void f(SmallVector<int>) = 0;");
1854  verifyFormat("void f(int i = (kValue) * kMask) {}");
1855  verifyFormat("void f(int i = (kA * kB) & kMask) {}");
1856  verifyFormat("int a = sizeof(int) * b;");
1857  verifyFormat("int a = alignof(int) * b;");
1858}
1859
1860TEST_F(FormatTest, FormatsFunctionTypes) {
1861  // FIXME: Determine the cases that need a space after the return type and fix.
1862  verifyFormat("A<bool()> a;");
1863  verifyFormat("A<SomeType()> a;");
1864  verifyFormat("A<void(*)(int, std::string)> a;");
1865
1866  verifyFormat("int(*func)(void *);");
1867}
1868
1869TEST_F(FormatTest, BreaksFunctionDeclarations) {
1870  verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
1871               "                  int LoooooooooooooooooooongParam2) {\n}");
1872  verifyFormat(
1873      "TypeSpecDecl *\n"
1874      "TypeSpecDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,\n"
1875      "                     IdentifierIn *II, Type *T) {\n}");
1876  verifyGoogleFormat(
1877      "TypeSpecDecl* TypeSpecDecl::Create(\n"
1878      "    ASTContext& C, DeclContext* DC, SourceLocation L) {\n}");
1879  verifyGoogleFormat(
1880      "some_namespace::LongReturnType\n"
1881      "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
1882      "    int first_long_parameter, int second_parameter) {\n}");
1883
1884  verifyGoogleFormat("template <typename T>\n"
1885                     "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
1886                     "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {\n}");
1887}
1888
1889TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
1890  verifyFormat("(a)->b();");
1891  verifyFormat("--a;");
1892}
1893
1894TEST_F(FormatTest, HandlesIncludeDirectives) {
1895  verifyFormat("#include <string>\n"
1896               "#include <a/b/c.h>\n"
1897               "#include \"a/b/string\"\n"
1898               "#include \"string.h\"\n"
1899               "#include \"string.h\"\n"
1900               "#include <a-a>\n"
1901               "#include < path with space >\n");
1902
1903  verifyFormat("#import <string>");
1904  verifyFormat("#import <a/b/c.h>");
1905  verifyFormat("#import \"a/b/string\"");
1906  verifyFormat("#import \"string.h\"");
1907  verifyFormat("#import \"string.h\"");
1908}
1909
1910//===----------------------------------------------------------------------===//
1911// Error recovery tests.
1912//===----------------------------------------------------------------------===//
1913
1914TEST_F(FormatTest, IncompleteParameterLists) {
1915  verifyGoogleFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
1916                     "                        double *min_x,\n"
1917                     "                        double *max_x,\n"
1918                     "                        double *min_y,\n"
1919                     "                        double *max_y,\n"
1920                     "                        double *min_z,\n"
1921                     "                        double *max_z, ) {\n"
1922                     "}");
1923}
1924
1925TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
1926  verifyFormat("void f() { return; }\n42");
1927  verifyFormat("void f() {\n"
1928               "  if (0)\n"
1929               "    return;\n"
1930               "}\n"
1931               "42");
1932  verifyFormat("void f() { return }\n42");
1933  verifyFormat("void f() {\n"
1934               "  if (0)\n"
1935               "    return\n"
1936               "}\n"
1937               "42");
1938}
1939
1940TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
1941  EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
1942  EXPECT_EQ("void f() {\n"
1943            "  if (a)\n"
1944            "    return\n"
1945            "}",
1946            format("void  f  (  )  {  if  ( a )  return  }"));
1947  EXPECT_EQ("namespace N { void f() }", format("namespace  N  {  void f()  }"));
1948  EXPECT_EQ("namespace N {\n"
1949            "void f() {}\n"
1950            "void g()\n"
1951            "}",
1952            format("namespace N  { void f( ) { } void g( ) }"));
1953}
1954
1955TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
1956  verifyFormat("int aaaaaaaa =\n"
1957               "    // Overly long comment\n"
1958               "    b;",
1959               getLLVMStyleWithColumns(20));
1960  verifyFormat("function(\n"
1961               "    ShortArgument,\n"
1962               "    LoooooooooooongArgument);\n",
1963               getLLVMStyleWithColumns(20));
1964}
1965
1966TEST_F(FormatTest, IncorrectAccessSpecifier) {
1967  verifyFormat("public:");
1968  verifyFormat("class A {\n"
1969               "public\n"
1970               "  void f() {}\n"
1971               "};");
1972  verifyFormat("public\n"
1973               "int qwerty;");
1974  verifyFormat("public\n"
1975               "B {}");
1976  verifyFormat("public\n"
1977               "{}");
1978  verifyFormat("public\n"
1979               "B { int x; }");
1980}
1981
1982TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) { verifyFormat("{"); }
1983
1984TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
1985  verifyFormat("do {\n}");
1986  verifyFormat("do {\n}\n"
1987               "f();");
1988  verifyFormat("do {\n}\n"
1989               "wheeee(fun);");
1990  verifyFormat("do {\n"
1991               "  f();\n"
1992               "}");
1993}
1994
1995TEST_F(FormatTest, IncorrectCodeMissingParens) {
1996  verifyFormat("if {\n  foo;\n  foo();\n}");
1997  verifyFormat("switch {\n  foo;\n  foo();\n}");
1998  verifyFormat("for {\n  foo;\n  foo();\n}");
1999  verifyFormat("while {\n  foo;\n  foo();\n}");
2000  verifyFormat("do {\n  foo;\n  foo();\n} while;");
2001}
2002
2003TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
2004  verifyFormat("namespace {\n"
2005               "class Foo {  Foo  ( }; }  // comment");
2006}
2007
2008TEST_F(FormatTest, IncorrectCodeErrorDetection) {
2009  EXPECT_EQ("{\n{}\n", format("{\n{\n}\n"));
2010  EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
2011  EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
2012  EXPECT_EQ("{\n  {}\n  }\n}\n", format("{\n  {\n    }\n  }\n}\n"));
2013
2014  EXPECT_EQ("{\n"
2015            "    {\n"
2016            " breakme(\n"
2017            "     qwe);\n"
2018            "}\n",
2019            format("{\n"
2020                   "    {\n"
2021                   " breakme(qwe);\n"
2022                   "}\n",
2023                   getLLVMStyleWithColumns(10)));
2024}
2025
2026TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
2027  verifyFormat("int x = {\n"
2028               "  avariable,\n"
2029               "  b(alongervariable)\n"
2030               "};",
2031               getLLVMStyleWithColumns(25));
2032}
2033
2034TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
2035  verifyFormat("return (a)(b) { 1, 2, 3 };");
2036}
2037
2038TEST_F(FormatTest, LayoutTokensFollowingBlockInParentheses) {
2039  verifyFormat(
2040      "Aaa({\n"
2041      "  int i;\n"
2042      "}, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
2043      "                                    ccccccccccccccccc));");
2044}
2045
2046TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
2047  verifyFormat("void f() { return 42; }");
2048  verifyFormat("void f() {\n"
2049               "  // Comment\n"
2050               "}");
2051  verifyFormat("{\n"
2052               "#error {\n"
2053               "  int a;\n"
2054               "}");
2055  verifyFormat("{\n"
2056               "  int a;\n"
2057               "#error {\n"
2058               "}");
2059
2060  verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
2061  verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
2062
2063  verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
2064  verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
2065}
2066
2067TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
2068  // Elaborate type variable declarations.
2069  verifyFormat("struct foo a = { bar };\nint n;");
2070  verifyFormat("class foo a = { bar };\nint n;");
2071  verifyFormat("union foo a = { bar };\nint n;");
2072
2073  // Elaborate types inside function definitions.
2074  verifyFormat("struct foo f() {}\nint n;");
2075  verifyFormat("class foo f() {}\nint n;");
2076  verifyFormat("union foo f() {}\nint n;");
2077
2078  // Templates.
2079  verifyFormat("template <class X> void f() {}\nint n;");
2080  verifyFormat("template <struct X> void f() {}\nint n;");
2081  verifyFormat("template <union X> void f() {}\nint n;");
2082
2083  // Actual definitions...
2084  verifyFormat("struct {\n} n;");
2085  verifyFormat(
2086      "template <template <class T, class Y>, class Z> class X {\n} n;");
2087  verifyFormat("union Z {\n  int n;\n} x;");
2088  verifyFormat("class MACRO Z {\n} n;");
2089  verifyFormat("class MACRO(X) Z {\n} n;");
2090  verifyFormat("class __attribute__(X) Z {\n} n;");
2091  verifyFormat("class __declspec(X) Z {\n} n;");
2092  verifyFormat("class A##B##C {\n} n;");
2093
2094  // Redefinition from nested context:
2095  verifyFormat("class A::B::C {\n} n;");
2096
2097  // Template definitions.
2098  // FIXME: This is still incorrectly handled at the formatter side.
2099  verifyFormat("template <> struct X < 15, i < 3 && 42 < 50 && 33<28> {\n};");
2100
2101  // FIXME:
2102  // This now gets parsed incorrectly as class definition.
2103  // verifyFormat("class A<int> f() {\n}\nint n;");
2104
2105  // Elaborate types where incorrectly parsing the structural element would
2106  // break the indent.
2107  verifyFormat("if (true)\n"
2108               "  class X x;\n"
2109               "else\n"
2110               "  f();\n");
2111}
2112
2113TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
2114  verifyFormat("#error Leave     all         white!!!!! space* alone!\n");
2115  verifyFormat("#warning Leave     all         white!!!!! space* alone!\n");
2116  EXPECT_EQ("#error 1", format("  #  error   1"));
2117  EXPECT_EQ("#warning 1", format("  #  warning 1"));
2118}
2119
2120TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
2121  FormatStyle AllowsMergedIf = getGoogleStyle();
2122  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
2123  verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
2124  verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
2125  verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
2126  EXPECT_EQ("if (true) return 42;",
2127            format("if (true)\nreturn 42;", AllowsMergedIf));
2128  FormatStyle ShortMergedIf = AllowsMergedIf;
2129  ShortMergedIf.ColumnLimit = 25;
2130  verifyFormat("#define A               \\\n"
2131               "  if (true) return 42;",
2132               ShortMergedIf);
2133  verifyFormat("#define A               \\\n"
2134               "  f();                  \\\n"
2135               "  if (true)\n"
2136               "#define B",
2137               ShortMergedIf);
2138  verifyFormat("#define A               \\\n"
2139               "  f();                  \\\n"
2140               "  if (true)\n"
2141               "g();",
2142               ShortMergedIf);
2143  verifyFormat("{\n"
2144               "#ifdef A\n"
2145               "  // Comment\n"
2146               "  if (true) continue;\n"
2147               "#endif\n"
2148               "  // Comment\n"
2149               "  if (true) continue;",
2150               ShortMergedIf);
2151}
2152
2153TEST_F(FormatTest, BlockCommentsInControlLoops) {
2154  verifyFormat("if (0) /* a comment in a strange place */ {\n"
2155               "  f();\n"
2156               "}");
2157  verifyFormat("if (0) /* a comment in a strange place */ {\n"
2158               "  f();\n"
2159               "} /* another comment */ else /* comment #3 */ {\n"
2160               "  g();\n"
2161               "}");
2162  verifyFormat("while (0) /* a comment in a strange place */ {\n"
2163               "  f();\n"
2164               "}");
2165  verifyFormat("for (;;) /* a comment in a strange place */ {\n"
2166               "  f();\n"
2167               "}");
2168  verifyFormat("do /* a comment in a strange place */ {\n"
2169               "  f();\n"
2170               "} /* another comment */ while (0);");
2171}
2172
2173TEST_F(FormatTest, BlockComments) {
2174  EXPECT_EQ("/* */ /* */ /* */\n/* */ /* */ /* */",
2175            format("/* *//* */  /* */\n/* *//* */  /* */"));
2176  EXPECT_EQ("/* */ a /* */ b;", format("  /* */  a/* */  b;"));
2177  EXPECT_EQ("#define A /*   */\\\n"
2178            "  b\n"
2179            "/* */\n"
2180            "someCall(\n"
2181            "    parameter);",
2182            format("#define A /*   */ b\n"
2183                   "/* */\n"
2184                   "someCall(parameter);",
2185                   getLLVMStyleWithColumns(15)));
2186
2187  EXPECT_EQ("#define A\n"
2188            "/* */ someCall(\n"
2189            "    parameter);",
2190            format("#define A\n"
2191                   "/* */someCall(parameter);",
2192                   getLLVMStyleWithColumns(15)));
2193
2194  EXPECT_EQ("someFunction(1, /* comment 1 */\n"
2195            "             2, /* comment 2 */\n"
2196            "             3, /* comment 3 */\n"
2197            "             aaaa,\n"
2198            "             bbbb);",
2199            format("someFunction (1,   /* comment 1 */\n"
2200                   "                2, /* comment 2 */  \n"
2201                   "               3,   /* comment 3 */\n"
2202                   "aaaa, bbbb );",
2203                   getGoogleStyle()));
2204  verifyFormat(
2205      "bool aaaaaaaaaaaaa = /* comment: */ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2206      "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2207  EXPECT_EQ(
2208      "bool aaaaaaaaaaaaa = /* trailing comment */\n"
2209      "    aaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2210      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;",
2211      format(
2212          "bool       aaaaaaaaaaaaa =       /* trailing comment */\n"
2213          "    aaaaaaaaaaaaaaaaaaaaaaaaaaa||aaaaaaaaaaaaaaaaaaaaaaaaa    ||\n"
2214          "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa   || aaaaaaaaaaaaaaaaaaaaaaaaaa;"));
2215  EXPECT_EQ(
2216      "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
2217      "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   /* comment */\n"
2218      "int cccccccccccccccccccccccccccccc;       /* comment */\n",
2219      format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
2220             "int      bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n"
2221             "int    cccccccccccccccccccccccccccccc;  /* comment */\n"));
2222}
2223
2224TEST_F(FormatTest, BlockCommentsInMacros) {
2225  EXPECT_EQ("#define A          \\\n"
2226            "  {                \\\n"
2227            "    /* one line */ \\\n"
2228            "    someCall();",
2229            format("#define A {        \\\n"
2230                   "  /* one line */   \\\n"
2231                   "  someCall();",
2232                   getLLVMStyleWithColumns(20)));
2233  EXPECT_EQ("#define A          \\\n"
2234            "  {                \\\n"
2235            "    /* previous */ \\\n"
2236            "    /* one line */ \\\n"
2237            "    someCall();",
2238            format("#define A {        \\\n"
2239                   "  /* previous */   \\\n"
2240                   "  /* one line */   \\\n"
2241                   "  someCall();",
2242                   getLLVMStyleWithColumns(20)));
2243}
2244
2245TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
2246  // FIXME: This is not what we want...
2247  verifyFormat("{\n"
2248               "// a"
2249               "// b");
2250}
2251
2252TEST_F(FormatTest, FormatStarDependingOnContext) {
2253  verifyFormat("void f(int *a);");
2254  verifyFormat("void f() { f(fint * b); }");
2255  verifyFormat("class A {\n  void f(int *a);\n};");
2256  verifyFormat("class A {\n  int *a;\n};");
2257  verifyFormat("namespace a {\n"
2258               "namespace b {\n"
2259               "class A {\n"
2260               "  void f() {}\n"
2261               "  int *a;\n"
2262               "};\n"
2263               "}\n"
2264               "}");
2265}
2266
2267TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
2268  verifyFormat("while");
2269  verifyFormat("operator");
2270}
2271
2272//===----------------------------------------------------------------------===//
2273// Objective-C tests.
2274//===----------------------------------------------------------------------===//
2275
2276TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
2277  verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
2278  EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
2279            format("-(NSUInteger)indexOfObject:(id)anObject;"));
2280  EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
2281  EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
2282  EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
2283            format("-(NSInteger)Method3:(id)anObject;"));
2284  EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
2285            format("-(NSInteger)Method4:(id)anObject;"));
2286  EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
2287            format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
2288  EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
2289            format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
2290  EXPECT_EQ(
2291      "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;",
2292      format(
2293          "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;"));
2294
2295  // Very long objectiveC method declaration.
2296  verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
2297               "                    inRange:(NSRange)range\n"
2298               "                   outRange:(NSRange)out_range\n"
2299               "                  outRange1:(NSRange)out_range1\n"
2300               "                  outRange2:(NSRange)out_range2\n"
2301               "                  outRange3:(NSRange)out_range3\n"
2302               "                  outRange4:(NSRange)out_range4\n"
2303               "                  outRange5:(NSRange)out_range5\n"
2304               "                  outRange6:(NSRange)out_range6\n"
2305               "                  outRange7:(NSRange)out_range7\n"
2306               "                  outRange8:(NSRange)out_range8\n"
2307               "                  outRange9:(NSRange)out_range9;");
2308
2309  verifyFormat("- (int)sum:(vector<int>)numbers;");
2310  verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
2311  // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
2312  // protocol lists (but not for template classes):
2313  //verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
2314
2315  verifyFormat("- (int(*)())foo:(int(*)())f;");
2316  verifyGoogleFormat("- (int(*)())foo:(int(*)())foo;");
2317
2318  // If there's no return type (very rare in practice!), LLVM and Google style
2319  // agree.
2320  verifyFormat("- foo:(int)f;");
2321  verifyGoogleFormat("- foo:(int)foo;");
2322}
2323
2324TEST_F(FormatTest, FormatObjCBlocks) {
2325  verifyFormat("int (^Block)(int, int);");
2326  verifyFormat("int (^Block1)(int, int) = ^(int i, int j)");
2327}
2328
2329TEST_F(FormatTest, FormatObjCInterface) {
2330  verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
2331               "@public\n"
2332               "  int field1;\n"
2333               "@protected\n"
2334               "  int field2;\n"
2335               "@private\n"
2336               "  int field3;\n"
2337               "@package\n"
2338               "  int field4;\n"
2339               "}\n"
2340               "+ (id)init;\n"
2341               "@end");
2342
2343  verifyGoogleFormat("@interface Foo : NSObject<NSSomeDelegate> {\n"
2344                     " @public\n"
2345                     "  int field1;\n"
2346                     " @protected\n"
2347                     "  int field2;\n"
2348                     " @private\n"
2349                     "  int field3;\n"
2350                     " @package\n"
2351                     "  int field4;\n"
2352                     "}\n"
2353                     "+ (id)init;\n"
2354                     "@end");
2355
2356  verifyFormat("@interface /* wait for it */ Foo\n"
2357               "+ (id)init;\n"
2358               "// Look, a comment!\n"
2359               "- (int)answerWith:(int)i;\n"
2360               "@end");
2361
2362  verifyFormat("@interface Foo\n"
2363               "@end\n"
2364               "@interface Bar\n"
2365               "@end");
2366
2367  verifyFormat("@interface Foo : Bar\n"
2368               "+ (id)init;\n"
2369               "@end");
2370
2371  verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
2372               "+ (id)init;\n"
2373               "@end");
2374
2375  verifyGoogleFormat("@interface Foo : Bar<Baz, Quux>\n"
2376                     "+ (id)init;\n"
2377                     "@end");
2378
2379  verifyFormat("@interface Foo (HackStuff)\n"
2380               "+ (id)init;\n"
2381               "@end");
2382
2383  verifyFormat("@interface Foo ()\n"
2384               "+ (id)init;\n"
2385               "@end");
2386
2387  verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
2388               "+ (id)init;\n"
2389               "@end");
2390
2391  verifyGoogleFormat("@interface Foo (HackStuff)<MyProtocol>\n"
2392                     "+ (id)init;\n"
2393                     "@end");
2394
2395  verifyFormat("@interface Foo {\n"
2396               "  int _i;\n"
2397               "}\n"
2398               "+ (id)init;\n"
2399               "@end");
2400
2401  verifyFormat("@interface Foo : Bar {\n"
2402               "  int _i;\n"
2403               "}\n"
2404               "+ (id)init;\n"
2405               "@end");
2406
2407  verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
2408               "  int _i;\n"
2409               "}\n"
2410               "+ (id)init;\n"
2411               "@end");
2412
2413  verifyFormat("@interface Foo (HackStuff) {\n"
2414               "  int _i;\n"
2415               "}\n"
2416               "+ (id)init;\n"
2417               "@end");
2418
2419  verifyFormat("@interface Foo () {\n"
2420               "  int _i;\n"
2421               "}\n"
2422               "+ (id)init;\n"
2423               "@end");
2424
2425  verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
2426               "  int _i;\n"
2427               "}\n"
2428               "+ (id)init;\n"
2429               "@end");
2430}
2431
2432TEST_F(FormatTest, FormatObjCImplementation) {
2433  verifyFormat("@implementation Foo : NSObject {\n"
2434               "@public\n"
2435               "  int field1;\n"
2436               "@protected\n"
2437               "  int field2;\n"
2438               "@private\n"
2439               "  int field3;\n"
2440               "@package\n"
2441               "  int field4;\n"
2442               "}\n"
2443               "+ (id)init {\n}\n"
2444               "@end");
2445
2446  verifyGoogleFormat("@implementation Foo : NSObject {\n"
2447                     " @public\n"
2448                     "  int field1;\n"
2449                     " @protected\n"
2450                     "  int field2;\n"
2451                     " @private\n"
2452                     "  int field3;\n"
2453                     " @package\n"
2454                     "  int field4;\n"
2455                     "}\n"
2456                     "+ (id)init {\n}\n"
2457                     "@end");
2458
2459  verifyFormat("@implementation Foo\n"
2460               "+ (id)init {\n"
2461               "  if (true)\n"
2462               "    return nil;\n"
2463               "}\n"
2464               "// Look, a comment!\n"
2465               "- (int)answerWith:(int)i {\n"
2466               "  return i;\n"
2467               "}\n"
2468               "+ (int)answerWith:(int)i {\n"
2469               "  return i;\n"
2470               "}\n"
2471               "@end");
2472
2473  verifyFormat("@implementation Foo\n"
2474               "@end\n"
2475               "@implementation Bar\n"
2476               "@end");
2477
2478  verifyFormat("@implementation Foo : Bar\n"
2479               "+ (id)init {\n}\n"
2480               "- (void)foo {\n}\n"
2481               "@end");
2482
2483  verifyFormat("@implementation Foo {\n"
2484               "  int _i;\n"
2485               "}\n"
2486               "+ (id)init {\n}\n"
2487               "@end");
2488
2489  verifyFormat("@implementation Foo : Bar {\n"
2490               "  int _i;\n"
2491               "}\n"
2492               "+ (id)init {\n}\n"
2493               "@end");
2494
2495  verifyFormat("@implementation Foo (HackStuff)\n"
2496               "+ (id)init {\n}\n"
2497               "@end");
2498}
2499
2500TEST_F(FormatTest, FormatObjCProtocol) {
2501  verifyFormat("@protocol Foo\n"
2502               "@property(weak) id delegate;\n"
2503               "- (NSUInteger)numberOfThings;\n"
2504               "@end");
2505
2506  verifyFormat("@protocol MyProtocol <NSObject>\n"
2507               "- (NSUInteger)numberOfThings;\n"
2508               "@end");
2509
2510  verifyGoogleFormat("@protocol MyProtocol<NSObject>\n"
2511                     "- (NSUInteger)numberOfThings;\n"
2512                     "@end");
2513
2514  verifyFormat("@protocol Foo;\n"
2515               "@protocol Bar;\n");
2516
2517  verifyFormat("@protocol Foo\n"
2518               "@end\n"
2519               "@protocol Bar\n"
2520               "@end");
2521
2522  verifyFormat("@protocol myProtocol\n"
2523               "- (void)mandatoryWithInt:(int)i;\n"
2524               "@optional\n"
2525               "- (void)optional;\n"
2526               "@required\n"
2527               "- (void)required;\n"
2528               "@optional\n"
2529               "@property(assign) int madProp;\n"
2530               "@end\n");
2531}
2532
2533TEST_F(FormatTest, FormatObjCMethodDeclarations) {
2534  verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
2535               "                   rect:(NSRect)theRect\n"
2536               "               interval:(float)theInterval {\n"
2537               "}");
2538  verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
2539               "          longKeyword:(NSRect)theRect\n"
2540               "    evenLongerKeyword:(float)theInterval\n"
2541               "                error:(NSError **)theError {\n"
2542               "}");
2543}
2544
2545TEST_F(FormatTest, FormatObjCMethodExpr) {
2546  verifyFormat("[foo bar:baz];");
2547  verifyFormat("return [foo bar:baz];");
2548  verifyFormat("f([foo bar:baz]);");
2549  verifyFormat("f(2, [foo bar:baz]);");
2550  verifyFormat("f(2, a ? b : c);");
2551  verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
2552
2553  // Unary operators.
2554  verifyFormat("int a = +[foo bar:baz];");
2555  verifyFormat("int a = -[foo bar:baz];");
2556  verifyFormat("int a = ![foo bar:baz];");
2557  verifyFormat("int a = ~[foo bar:baz];");
2558  verifyFormat("int a = ++[foo bar:baz];");
2559  verifyFormat("int a = --[foo bar:baz];");
2560  verifyFormat("int a = sizeof [foo bar:baz];");
2561  verifyFormat("int a = alignof [foo bar:baz];");
2562  verifyFormat("int a = &[foo bar:baz];");
2563  verifyFormat("int a = *[foo bar:baz];");
2564  // FIXME: Make casts work, without breaking f()[4].
2565  //verifyFormat("int a = (int)[foo bar:baz];");
2566  //verifyFormat("return (int)[foo bar:baz];");
2567  //verifyFormat("(void)[foo bar:baz];");
2568  verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
2569
2570  // Binary operators.
2571  verifyFormat("[foo bar:baz], [foo bar:baz];");
2572  verifyFormat("[foo bar:baz] = [foo bar:baz];");
2573  verifyFormat("[foo bar:baz] *= [foo bar:baz];");
2574  verifyFormat("[foo bar:baz] /= [foo bar:baz];");
2575  verifyFormat("[foo bar:baz] %= [foo bar:baz];");
2576  verifyFormat("[foo bar:baz] += [foo bar:baz];");
2577  verifyFormat("[foo bar:baz] -= [foo bar:baz];");
2578  verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
2579  verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
2580  verifyFormat("[foo bar:baz] &= [foo bar:baz];");
2581  verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
2582  verifyFormat("[foo bar:baz] |= [foo bar:baz];");
2583  verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
2584  verifyFormat("[foo bar:baz] || [foo bar:baz];");
2585  verifyFormat("[foo bar:baz] && [foo bar:baz];");
2586  verifyFormat("[foo bar:baz] | [foo bar:baz];");
2587  verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
2588  verifyFormat("[foo bar:baz] & [foo bar:baz];");
2589  verifyFormat("[foo bar:baz] == [foo bar:baz];");
2590  verifyFormat("[foo bar:baz] != [foo bar:baz];");
2591  verifyFormat("[foo bar:baz] >= [foo bar:baz];");
2592  verifyFormat("[foo bar:baz] <= [foo bar:baz];");
2593  verifyFormat("[foo bar:baz] > [foo bar:baz];");
2594  verifyFormat("[foo bar:baz] < [foo bar:baz];");
2595  verifyFormat("[foo bar:baz] >> [foo bar:baz];");
2596  verifyFormat("[foo bar:baz] << [foo bar:baz];");
2597  verifyFormat("[foo bar:baz] - [foo bar:baz];");
2598  verifyFormat("[foo bar:baz] + [foo bar:baz];");
2599  verifyFormat("[foo bar:baz] * [foo bar:baz];");
2600  verifyFormat("[foo bar:baz] / [foo bar:baz];");
2601  verifyFormat("[foo bar:baz] % [foo bar:baz];");
2602  // Whew!
2603
2604  verifyFormat("return in[42];");
2605  verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
2606               "}");
2607
2608  verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
2609  verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
2610  verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
2611  verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
2612  verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
2613  verifyFormat("[button setAction:@selector(zoomOut:)];");
2614  verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
2615
2616  verifyFormat("arr[[self indexForFoo:a]];");
2617  verifyFormat("throw [self errorFor:a];");
2618  verifyFormat("@throw [self errorFor:a];");
2619
2620  // This tests that the formatter doesn't break after "backing" but before ":",
2621  // which would be at 80 columns.
2622  verifyFormat(
2623      "void f() {\n"
2624      "  if ((self = [super initWithContentRect:contentRect\n"
2625      "                               styleMask:styleMask\n"
2626      "                                 backing:NSBackingStoreBuffered\n"
2627      "                                   defer:YES]))");
2628
2629  verifyFormat(
2630      "[foo checkThatBreakingAfterColonWorksOk:\n"
2631      "        [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
2632
2633  verifyFormat("[myObj short:arg1 // Force line break\n"
2634               "          longKeyword:arg2\n"
2635               "    evenLongerKeyword:arg3\n"
2636               "                error:arg4];");
2637  verifyFormat(
2638      "void f() {\n"
2639      "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
2640      "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
2641      "                                     pos.width(), pos.height())\n"
2642      "                styleMask:NSBorderlessWindowMask\n"
2643      "                  backing:NSBackingStoreBuffered\n"
2644      "                    defer:NO]);\n"
2645      "}");
2646  verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
2647               "                             with:contentsNativeView];");
2648
2649  verifyFormat(
2650      "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
2651      "           owner:nillllll];");
2652
2653  verifyFormat(
2654      "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
2655      "        forType:kBookmarkButtonDragType];");
2656
2657  verifyFormat("[defaultCenter addObserver:self\n"
2658               "                  selector:@selector(willEnterFullscreen)\n"
2659               "                      name:kWillEnterFullscreenNotification\n"
2660               "                    object:nil];");
2661  verifyFormat("[image_rep drawInRect:drawRect\n"
2662               "             fromRect:NSZeroRect\n"
2663               "            operation:NSCompositeCopy\n"
2664               "             fraction:1.0\n"
2665               "       respectFlipped:NO\n"
2666               "                hints:nil];");
2667
2668  verifyFormat(
2669      "scoped_nsobject<NSTextField> message(\n"
2670      "    // The frame will be fixed up when |-setMessageText:| is called.\n"
2671      "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
2672}
2673
2674TEST_F(FormatTest, ObjCAt) {
2675  verifyFormat("@autoreleasepool");
2676  verifyFormat("@catch");
2677  verifyFormat("@class");
2678  verifyFormat("@compatibility_alias");
2679  verifyFormat("@defs");
2680  verifyFormat("@dynamic");
2681  verifyFormat("@encode");
2682  verifyFormat("@end");
2683  verifyFormat("@finally");
2684  verifyFormat("@implementation");
2685  verifyFormat("@import");
2686  verifyFormat("@interface");
2687  verifyFormat("@optional");
2688  verifyFormat("@package");
2689  verifyFormat("@private");
2690  verifyFormat("@property");
2691  verifyFormat("@protected");
2692  verifyFormat("@protocol");
2693  verifyFormat("@public");
2694  verifyFormat("@required");
2695  verifyFormat("@selector");
2696  verifyFormat("@synchronized");
2697  verifyFormat("@synthesize");
2698  verifyFormat("@throw");
2699  verifyFormat("@try");
2700
2701  EXPECT_EQ("@interface", format("@ interface"));
2702
2703  // The precise formatting of this doesn't matter, nobody writes code like
2704  // this.
2705  verifyFormat("@ /*foo*/ interface");
2706}
2707
2708TEST_F(FormatTest, ObjCSnippets) {
2709  verifyFormat("@autoreleasepool {\n"
2710               "  foo();\n"
2711               "}");
2712  verifyFormat("@class Foo, Bar;");
2713  verifyFormat("@compatibility_alias AliasName ExistingClass;");
2714  verifyFormat("@dynamic textColor;");
2715  verifyFormat("char *buf1 = @encode(int *);");
2716  verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
2717  verifyFormat("char *buf1 = @encode(int **);");
2718  verifyFormat("Protocol *proto = @protocol(p1);");
2719  verifyFormat("SEL s = @selector(foo:);");
2720  verifyFormat("@synchronized(self) {\n"
2721               "  f();\n"
2722               "}");
2723
2724  verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
2725  verifyGoogleFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
2726
2727  verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
2728  verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
2729  verifyGoogleFormat("@property(assign, getter=isEditable) BOOL editable;");
2730}
2731
2732TEST_F(FormatTest, ObjCLiterals) {
2733  verifyFormat("@\"String\"");
2734  verifyFormat("@1");
2735  verifyFormat("@+4.8");
2736  verifyFormat("@-4");
2737  verifyFormat("@1LL");
2738  verifyFormat("@.5");
2739  verifyFormat("@'c'");
2740  verifyFormat("@true");
2741
2742  verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
2743  verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
2744  verifyFormat("NSNumber *favoriteColor = @(Green);");
2745  verifyFormat("NSString *path = @(getenv(\"PATH\"));");
2746
2747  verifyFormat("@[");
2748  verifyFormat("@[]");
2749  verifyFormat(
2750      "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
2751  verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
2752
2753  verifyFormat("@{");
2754  verifyFormat("@{}");
2755  verifyFormat("@{ @\"one\" : @1 }");
2756  verifyFormat("return @{ @\"one\" : @1 };");
2757  verifyFormat("@{ @\"one\" : @1, }");
2758  verifyFormat("@{ @\"one\" : @{ @2 : @1 } }");
2759  verifyFormat("@{ @\"one\" : @{ @2 : @1 }, }");
2760  verifyFormat("@{ 1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2 }");
2761  verifyFormat("[self setDict:@{}");
2762  verifyFormat("[self setDict:@{ @1 : @2 }");
2763  verifyFormat("NSLog(@\"%@\", @{ @1 : @2, @2 : @3 }[@1]);");
2764  verifyFormat(
2765      "NSDictionary *masses = @{ @\"H\" : @1.0078, @\"He\" : @4.0026 };");
2766  verifyFormat(
2767      "NSDictionary *settings = @{ AVEncoderKey : @(AVAudioQualityMax) };");
2768
2769  // FIXME: Nested and multi-line array and dictionary literals need more work.
2770  verifyFormat(
2771      "NSDictionary *d = @{ @\"nam\" : NSUserNam(), @\"dte\" : [NSDate date],\n"
2772      "                     @\"processInfo\" : [NSProcessInfo processInfo] };");
2773}
2774
2775TEST_F(FormatTest, ReformatRegionAdjustsIndent) {
2776  EXPECT_EQ("{\n"
2777            "{\n"
2778            "a;\n"
2779            "b;\n"
2780            "}\n"
2781            "}",
2782            format("{\n"
2783                   "{\n"
2784                   "a;\n"
2785                   "     b;\n"
2786                   "}\n"
2787                   "}",
2788                   13, 2, getLLVMStyle()));
2789  EXPECT_EQ("{\n"
2790            "{\n"
2791            "  a;\n"
2792            "b;\n"
2793            "}\n"
2794            "}",
2795            format("{\n"
2796                   "{\n"
2797                   "     a;\n"
2798                   "b;\n"
2799                   "}\n"
2800                   "}",
2801                   9, 2, getLLVMStyle()));
2802  EXPECT_EQ("{\n"
2803            "{\n"
2804            "public:\n"
2805            "  b;\n"
2806            "}\n"
2807            "}",
2808            format("{\n"
2809                   "{\n"
2810                   "public:\n"
2811                   "     b;\n"
2812                   "}\n"
2813                   "}",
2814                   17, 2, getLLVMStyle()));
2815  EXPECT_EQ("{\n"
2816            "{\n"
2817            "a;\n"
2818            "}\n"
2819            "{\n"
2820            "  b;\n"
2821            "}\n"
2822            "}",
2823            format("{\n"
2824                   "{\n"
2825                   "a;\n"
2826                   "}\n"
2827                   "{\n"
2828                   "           b;\n"
2829                   "}\n"
2830                   "}",
2831                   22, 2, getLLVMStyle()));
2832  EXPECT_EQ("  {\n"
2833            "    a;\n"
2834            "  }",
2835            format("  {\n"
2836                   "a;\n"
2837                   "  }",
2838                   4, 2, getLLVMStyle()));
2839  EXPECT_EQ("void f() {}\n"
2840            "void g() {}",
2841            format("void f() {}\n"
2842                   "void g() {}",
2843                   13, 0, getLLVMStyle()));
2844}
2845
2846TEST_F(FormatTest, BreakStringLiterals) {
2847  EXPECT_EQ("\"some text \"\n"
2848            "\"other\";",
2849            format("\"some text other\";", getLLVMStyleWithColumns(12)));
2850  EXPECT_EQ(
2851      "#define A  \\\n"
2852      "  \"some \"  \\\n"
2853      "  \"text \"  \\\n"
2854      "  \"other\";",
2855      format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
2856  EXPECT_EQ(
2857      "#define A  \\\n"
2858      "  \"so \"    \\\n"
2859      "  \"text \"  \\\n"
2860      "  \"other\";",
2861      format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
2862
2863  EXPECT_EQ("\"some text\"",
2864            format("\"some text\"", getLLVMStyleWithColumns(1)));
2865  EXPECT_EQ("\"some text\"",
2866            format("\"some text\"", getLLVMStyleWithColumns(11)));
2867  EXPECT_EQ("\"some \"\n"
2868            "\"text\"",
2869            format("\"some text\"", getLLVMStyleWithColumns(10)));
2870  EXPECT_EQ("\"some \"\n"
2871            "\"text\"",
2872            format("\"some text\"", getLLVMStyleWithColumns(7)));
2873  EXPECT_EQ("\"some text\"",
2874            format("\"some text\"", getLLVMStyleWithColumns(6)));
2875
2876  EXPECT_EQ("variable =\n"
2877            "    \"long string \"\n"
2878            "    \"literal\";",
2879            format("variable = \"long string literal\";",
2880                   getLLVMStyleWithColumns(20)));
2881
2882  EXPECT_EQ("variable = f(\n"
2883            "    \"long string \"\n"
2884            "    \"literal\", short,\n"
2885            "    loooooooooooooooooooong);",
2886            format("variable = f(\"long string literal\", short, "
2887                   "loooooooooooooooooooong);",
2888                   getLLVMStyleWithColumns(20)));
2889  EXPECT_EQ(
2890      "f(\"one two\".split(\n"
2891      "    variable));",
2892      format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
2893  EXPECT_EQ("f(\"one two three four five six \"\n"
2894            "  \"seven\".split(\n"
2895            "      really_looooong_variable));",
2896            format("f(\"one two three four five six seven\"."
2897                   "split(really_looooong_variable));",
2898                   getLLVMStyleWithColumns(33)));
2899
2900  EXPECT_EQ("f(\"some \"\n"
2901            "  \"text\",\n"
2902            "  other);",
2903            format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
2904}
2905
2906} // end namespace tooling
2907} // end namespace clang
2908