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