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