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