FormatTest.cpp revision be9ed776e57fe606b5826a0d37a5a2dbfb927e63
1//===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#define DEBUG_TYPE "format-test"
11
12#include "clang/Format/Format.h"
13#include "clang/Lex/Lexer.h"
14#include "llvm/Support/Debug.h"
15#include "gtest/gtest.h"
16
17namespace clang {
18namespace format {
19
20class FormatTest : public ::testing::Test {
21protected:
22  std::string format(llvm::StringRef Code, unsigned Offset, unsigned Length,
23                     const FormatStyle &Style) {
24    DEBUG(llvm::errs() << "---\n");
25    std::vector<tooling::Range> Ranges(1, tooling::Range(Offset, Length));
26    tooling::Replacements Replaces = reformat(Style, Code, Ranges);
27    ReplacementCount = Replaces.size();
28    std::string Result = applyAllReplacements(Code, Replaces);
29    EXPECT_NE("", Result);
30    DEBUG(llvm::errs() << "\n" << Result << "\n\n");
31    return Result;
32  }
33
34  std::string
35  format(llvm::StringRef Code, const FormatStyle &Style = getLLVMStyle()) {
36    return format(Code, 0, Code.size(), Style);
37  }
38
39  std::string messUp(llvm::StringRef Code) {
40    std::string MessedUp(Code.str());
41    bool InComment = false;
42    bool InPreprocessorDirective = false;
43    bool JustReplacedNewline = false;
44    for (unsigned i = 0, e = MessedUp.size() - 1; i != e; ++i) {
45      if (MessedUp[i] == '/' && MessedUp[i + 1] == '/') {
46        if (JustReplacedNewline)
47          MessedUp[i - 1] = '\n';
48        InComment = true;
49      } else if (MessedUp[i] == '#' && (JustReplacedNewline || i == 0)) {
50        if (i != 0)
51          MessedUp[i - 1] = '\n';
52        InPreprocessorDirective = true;
53      } else if (MessedUp[i] == '\\' && MessedUp[i + 1] == '\n') {
54        MessedUp[i] = ' ';
55        MessedUp[i + 1] = ' ';
56      } else if (MessedUp[i] == '\n') {
57        if (InComment) {
58          InComment = false;
59        } else if (InPreprocessorDirective) {
60          InPreprocessorDirective = false;
61        } else {
62          JustReplacedNewline = true;
63          MessedUp[i] = ' ';
64        }
65      } else if (MessedUp[i] != ' ') {
66        JustReplacedNewline = false;
67      }
68    }
69    return MessedUp;
70  }
71
72  FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
73    FormatStyle Style = getLLVMStyle();
74    Style.ColumnLimit = ColumnLimit;
75    return Style;
76  }
77
78  FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
79    FormatStyle Style = getGoogleStyle();
80    Style.ColumnLimit = ColumnLimit;
81    return Style;
82  }
83
84  void verifyFormat(llvm::StringRef Code,
85                    const FormatStyle &Style = getLLVMStyle()) {
86    EXPECT_EQ(Code.str(), format(messUp(Code), Style));
87  }
88
89  void verifyGoogleFormat(llvm::StringRef Code) {
90    verifyFormat(Code, getGoogleStyle());
91  }
92
93  void verifyIndependentOfContext(llvm::StringRef text) {
94    verifyFormat(text);
95    verifyFormat(llvm::Twine("void f() { " + text + " }").str());
96  }
97
98  int ReplacementCount;
99};
100
101TEST_F(FormatTest, MessUp) {
102  EXPECT_EQ("1 2 3", messUp("1 2 3"));
103  EXPECT_EQ("1 2 3\n", messUp("1\n2\n3\n"));
104  EXPECT_EQ("a\n//b\nc", messUp("a\n//b\nc"));
105  EXPECT_EQ("a\n#b\nc", messUp("a\n#b\nc"));
106  EXPECT_EQ("a\n#b  c  d\ne", messUp("a\n#b\\\nc\\\nd\ne"));
107}
108
109//===----------------------------------------------------------------------===//
110// Basic function tests.
111//===----------------------------------------------------------------------===//
112
113TEST_F(FormatTest, DoesNotChangeCorrectlyFormatedCode) {
114  EXPECT_EQ(";", format(";"));
115}
116
117TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
118  EXPECT_EQ("int i;", format("  int i;"));
119  EXPECT_EQ("\nint i;", format(" \n\t \r  int i;"));
120  EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
121  EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
122}
123
124TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
125  EXPECT_EQ("int i;", format("int\ni;"));
126}
127
128TEST_F(FormatTest, FormatsNestedBlockStatements) {
129  EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
130}
131
132TEST_F(FormatTest, FormatsNestedCall) {
133  verifyFormat("Method(f1, f2(f3));");
134  verifyFormat("Method(f1(f2, f3()));");
135  verifyFormat("Method(f1(f2, (f3())));");
136}
137
138TEST_F(FormatTest, NestedNameSpecifiers) {
139  verifyFormat("vector< ::Type> v;");
140  verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
141}
142
143TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
144  EXPECT_EQ("if (a) {\n"
145            "  f();\n"
146            "}",
147            format("if(a){f();}"));
148  EXPECT_EQ(4, ReplacementCount);
149  EXPECT_EQ("if (a) {\n"
150            "  f();\n"
151            "}",
152            format("if (a) {\n"
153                   "  f();\n"
154                   "}"));
155  EXPECT_EQ(0, ReplacementCount);
156}
157
158TEST_F(FormatTest, RemovesTrailingWhitespaceOfFormattedLine) {
159  EXPECT_EQ("int a;\nint b;", format("int a; \nint b;", 0, 0, getLLVMStyle()));
160  EXPECT_EQ("int a;", format("int a;         "));
161  EXPECT_EQ("int a;\n", format("int a;  \n   \n   \n "));
162  EXPECT_EQ("int a;\nint b;    ",
163            format("int a;  \nint b;    ", 0, 0, getLLVMStyle()));
164}
165
166TEST_F(FormatTest, FormatsCorrectRegionForLeadingWhitespace) {
167  EXPECT_EQ("int b;\nint a;",
168            format("int b;\n   int a;", 7, 0, getLLVMStyle()));
169  EXPECT_EQ("int b;\n   int a;",
170            format("int b;\n   int a;", 6, 0, getLLVMStyle()));
171
172  EXPECT_EQ("#define A  \\\n"
173            "  int a;   \\\n"
174            "  int b;",
175            format("#define A  \\\n"
176                   "  int a;   \\\n"
177                   "    int b;",
178                   26, 0, getLLVMStyleWithColumns(12)));
179  EXPECT_EQ("#define A  \\\n"
180            "  int a;   \\\n"
181            "    int b;",
182            format("#define A  \\\n"
183                   "  int a;   \\\n"
184                   "    int b;",
185                   25, 0, getLLVMStyleWithColumns(12)));
186}
187
188TEST_F(FormatTest, RemovesWhitespaceWhenTriggeredOnEmptyLine) {
189  EXPECT_EQ("int  a;\n\n int b;",
190            format("int  a;\n  \n\n int b;", 7, 0, getLLVMStyle()));
191  EXPECT_EQ("int  a;\n\n int b;",
192            format("int  a;\n  \n\n int b;", 9, 0, getLLVMStyle()));
193}
194
195TEST_F(FormatTest, ReformatsMovedLines) {
196  EXPECT_EQ(
197      "template <typename T> T *getFETokenInfo() const {\n"
198      "  return static_cast<T *>(FETokenInfo);\n"
199      "}\n"
200      "  int a; // <- Should not be formatted",
201      format(
202          "template<typename T>\n"
203          "T *getFETokenInfo() const { return static_cast<T*>(FETokenInfo); }\n"
204          "  int a; // <- Should not be formatted",
205          9, 5, getLLVMStyle()));
206}
207
208//===----------------------------------------------------------------------===//
209// Tests for control statements.
210//===----------------------------------------------------------------------===//
211
212TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
213  verifyFormat("if (true)\n  f();\ng();");
214  verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
215  verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
216
217  FormatStyle AllowsMergedIf = getLLVMStyle();
218  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
219  verifyFormat("if (a)\n"
220               "  // comment\n"
221               "  f();",
222               AllowsMergedIf);
223  verifyFormat("if (a)\n"
224               "  ;",
225               AllowsMergedIf);
226  verifyFormat("if (a)\n"
227               "  if (b) return;",
228               AllowsMergedIf);
229
230  verifyFormat("if (a) // Can't merge this\n"
231               "  f();\n",
232               AllowsMergedIf);
233  verifyFormat("if (a) /* still don't merge */\n"
234               "  f();",
235               AllowsMergedIf);
236  verifyFormat("if (a) { // Never merge this\n"
237               "  f();\n"
238               "}",
239               AllowsMergedIf);
240  verifyFormat("if (a) { /* Never merge this */\n"
241               "  f();\n"
242               "}",
243               AllowsMergedIf);
244
245  EXPECT_EQ("if (a) return;", format("if(a)\nreturn;", 7, 1, AllowsMergedIf));
246  EXPECT_EQ("if (a) return; // comment",
247            format("if(a)\nreturn; // comment", 20, 1, AllowsMergedIf));
248
249  AllowsMergedIf.ColumnLimit = 14;
250  verifyFormat("if (a) return;", AllowsMergedIf);
251  verifyFormat("if (aaaaaaaaa)\n"
252               "  return;",
253               AllowsMergedIf);
254
255  AllowsMergedIf.ColumnLimit = 13;
256  verifyFormat("if (a)\n  return;", AllowsMergedIf);
257}
258
259TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
260  FormatStyle AllowsMergedLoops = getLLVMStyle();
261  AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
262  verifyFormat("while (true) continue;", AllowsMergedLoops);
263  verifyFormat("for (;;) continue;", AllowsMergedLoops);
264  verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
265  verifyFormat("while (true)\n"
266               "  ;",
267               AllowsMergedLoops);
268  verifyFormat("for (;;)\n"
269               "  ;",
270               AllowsMergedLoops);
271  verifyFormat("for (;;)\n"
272               "  for (;;) continue;",
273               AllowsMergedLoops);
274  verifyFormat("for (;;) // Can't merge this\n"
275               "  continue;",
276               AllowsMergedLoops);
277  verifyFormat("for (;;) /* still don't merge */\n"
278               "  continue;",
279               AllowsMergedLoops);
280}
281
282TEST_F(FormatTest, ParseIfElse) {
283  verifyFormat("if (true)\n"
284               "  if (true)\n"
285               "    if (true)\n"
286               "      f();\n"
287               "    else\n"
288               "      g();\n"
289               "  else\n"
290               "    h();\n"
291               "else\n"
292               "  i();");
293  verifyFormat("if (true)\n"
294               "  if (true)\n"
295               "    if (true) {\n"
296               "      if (true)\n"
297               "        f();\n"
298               "    } else {\n"
299               "      g();\n"
300               "    }\n"
301               "  else\n"
302               "    h();\n"
303               "else {\n"
304               "  i();\n"
305               "}");
306}
307
308TEST_F(FormatTest, ElseIf) {
309  verifyFormat("if (a) {\n} else if (b) {\n}");
310  verifyFormat("if (a)\n"
311               "  f();\n"
312               "else if (b)\n"
313               "  g();\n"
314               "else\n"
315               "  h();");
316}
317
318TEST_F(FormatTest, FormatsForLoop) {
319  verifyFormat(
320      "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
321      "     ++VeryVeryLongLoopVariable)\n"
322      "  ;");
323  verifyFormat("for (;;)\n"
324               "  f();");
325  verifyFormat("for (;;) {\n}");
326  verifyFormat("for (;;) {\n"
327               "  f();\n"
328               "}");
329  verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
330
331  verifyFormat(
332      "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
333      "                                          E = UnwrappedLines.end();\n"
334      "     I != E; ++I) {\n}");
335
336  verifyFormat(
337      "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
338      "     ++IIIII) {\n}");
339  verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
340               "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
341               "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
342  verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
343               "         I = FD->getDeclsInPrototypeScope().begin(),\n"
344               "         E = FD->getDeclsInPrototypeScope().end();\n"
345               "     I != E; ++I) {\n}");
346
347  // FIXME: Not sure whether we want extra identation in line 3 here:
348  verifyFormat(
349      "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
350      "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
351      "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
352      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
353      "     ++aaaaaaaaaaa) {\n}");
354  verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
355               "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
356               "}");
357  verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
358               "         aaaaaaaaaa);\n"
359               "     iter; ++iter) {\n"
360               "}");
361
362  FormatStyle NoBinPacking = getLLVMStyle();
363  NoBinPacking.BinPackParameters = false;
364  verifyFormat("for (int aaaaaaaaaaa = 1;\n"
365               "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
366               "                                           aaaaaaaaaaaaaaaa,\n"
367               "                                           aaaaaaaaaaaaaaaa,\n"
368               "                                           aaaaaaaaaaaaaaaa);\n"
369               "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
370               "}",
371               NoBinPacking);
372  verifyFormat(
373      "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
374      "                                          E = UnwrappedLines.end();\n"
375      "     I != E;\n"
376      "     ++I) {\n}",
377      NoBinPacking);
378}
379
380TEST_F(FormatTest, RangeBasedForLoops) {
381  verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
382               "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
383  verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
384               "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
385  verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
386               "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
387}
388
389TEST_F(FormatTest, FormatsWhileLoop) {
390  verifyFormat("while (true) {\n}");
391  verifyFormat("while (true)\n"
392               "  f();");
393  verifyFormat("while () {\n}");
394  verifyFormat("while () {\n"
395               "  f();\n"
396               "}");
397}
398
399TEST_F(FormatTest, FormatsDoWhile) {
400  verifyFormat("do {\n"
401               "  do_something();\n"
402               "} while (something());");
403  verifyFormat("do\n"
404               "  do_something();\n"
405               "while (something());");
406}
407
408TEST_F(FormatTest, FormatsSwitchStatement) {
409  verifyFormat("switch (x) {\n"
410               "case 1:\n"
411               "  f();\n"
412               "  break;\n"
413               "case kFoo:\n"
414               "case ns::kBar:\n"
415               "case kBaz:\n"
416               "  break;\n"
417               "default:\n"
418               "  g();\n"
419               "  break;\n"
420               "}");
421  verifyFormat("switch (x) {\n"
422               "case 1: {\n"
423               "  f();\n"
424               "  break;\n"
425               "}\n"
426               "}");
427  verifyFormat("switch (x) {\n"
428               "case 1: {\n"
429               "  f();\n"
430               "  {\n"
431               "    g();\n"
432               "    h();\n"
433               "  }\n"
434               "  break;\n"
435               "}\n"
436               "}");
437  verifyFormat("switch (x) {\n"
438               "case 1: {\n"
439               "  f();\n"
440               "  if (foo) {\n"
441               "    g();\n"
442               "    h();\n"
443               "  }\n"
444               "  break;\n"
445               "}\n"
446               "}");
447  verifyFormat("switch (x) {\n"
448               "case 1: {\n"
449               "  f();\n"
450               "  g();\n"
451               "} break;\n"
452               "}");
453  verifyFormat("switch (test)\n"
454               "  ;");
455  verifyFormat("switch (x) {\n"
456               "default: {\n"
457               "  // Do nothing.\n"
458               "}\n"
459               "}");
460  verifyFormat("switch (x) {\n"
461               "// comment\n"
462               "// if 1, do f()\n"
463               "case 1:\n"
464               "  f();\n"
465               "}");
466  verifyFormat("switch (x) {\n"
467               "case 1:\n"
468               "  // Do amazing stuff\n"
469               "  {\n"
470               "    f();\n"
471               "    g();\n"
472               "  }\n"
473               "  break;\n"
474               "}");
475  verifyFormat("#define A          \\\n"
476               "  switch (x) {     \\\n"
477               "  case a:          \\\n"
478               "    foo = b;       \\\n"
479               "  }", getLLVMStyleWithColumns(20));
480
481  verifyGoogleFormat("switch (x) {\n"
482                     "  case 1:\n"
483                     "    f();\n"
484                     "    break;\n"
485                     "  case kFoo:\n"
486                     "  case ns::kBar:\n"
487                     "  case kBaz:\n"
488                     "    break;\n"
489                     "  default:\n"
490                     "    g();\n"
491                     "    break;\n"
492                     "}");
493  verifyGoogleFormat("switch (x) {\n"
494                     "  case 1: {\n"
495                     "    f();\n"
496                     "    break;\n"
497                     "  }\n"
498                     "}");
499  verifyGoogleFormat("switch (test)\n"
500                     "    ;");
501}
502
503TEST_F(FormatTest, FormatsLabels) {
504  verifyFormat("void f() {\n"
505               "  some_code();\n"
506               "test_label:\n"
507               "  some_other_code();\n"
508               "  {\n"
509               "    some_more_code();\n"
510               "  another_label:\n"
511               "    some_more_code();\n"
512               "  }\n"
513               "}");
514  verifyFormat("some_code();\n"
515               "test_label:\n"
516               "some_other_code();");
517}
518
519//===----------------------------------------------------------------------===//
520// Tests for comments.
521//===----------------------------------------------------------------------===//
522
523TEST_F(FormatTest, UnderstandsSingleLineComments) {
524  verifyFormat("//* */");
525  verifyFormat("// line 1\n"
526               "// line 2\n"
527               "void f() {}\n");
528
529  verifyFormat("void f() {\n"
530               "  // Doesn't do anything\n"
531               "}");
532  verifyFormat("void f(int i,  // some comment (probably for i)\n"
533               "       int j,  // some comment (probably for j)\n"
534               "       int k); // some comment (probably for k)");
535  verifyFormat("void f(int i,\n"
536               "       // some comment (probably for j)\n"
537               "       int j,\n"
538               "       // some comment (probably for k)\n"
539               "       int k);");
540
541  verifyFormat("int i    // This is a fancy variable\n"
542               "    = 5; // with nicely aligned comment.");
543
544  verifyFormat("// Leading comment.\n"
545               "int a; // Trailing comment.");
546  verifyFormat("int a; // Trailing comment\n"
547               "       // on 2\n"
548               "       // or 3 lines.\n"
549               "int b;");
550  verifyFormat("int a; // Trailing comment\n"
551               "\n"
552               "// Leading comment.\n"
553               "int b;");
554  verifyFormat("int a;    // Comment.\n"
555               "          // More details.\n"
556               "int bbbb; // Another comment.");
557  verifyFormat(
558      "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
559      "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   // comment\n"
560      "int cccccccccccccccccccccccccccccc;       // comment\n"
561      "int ddd;                     // looooooooooooooooooooooooong comment\n"
562      "int aaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
563      "int bbbbbbbbbbbbbbbbbbbbb;   // comment\n"
564      "int ccccccccccccccccccc;     // comment");
565
566  verifyFormat("#include \"a\"     // comment\n"
567               "#include \"a/b/c\" // comment");
568  verifyFormat("#include <a>     // comment\n"
569               "#include <a/b/c> // comment");
570  EXPECT_EQ("#include \\\n"
571            "  \"a\"            // comment\n"
572            "#include \"a/b/c\" // comment",
573            format("#include \\\n"
574                   "  \"a\" // comment\n"
575                   "#include \"a/b/c\" // comment"));
576
577  verifyFormat("enum E {\n"
578               "  // comment\n"
579               "  VAL_A, // comment\n"
580               "  VAL_B\n"
581               "};");
582
583  verifyFormat(
584      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
585      "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // Trailing comment");
586  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
587               "    // Comment inside a statement.\n"
588               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
589  verifyFormat(
590      "bool aaaaaaaaaaaaa = // comment\n"
591      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
592      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
593
594  verifyFormat("int aaaa; // aaaaa\n"
595               "int aa;   // aaaaaaa",
596               getLLVMStyleWithColumns(20));
597
598  EXPECT_EQ("void f() { // This does something ..\n"
599            "}\n"
600            "int a; // This is unrelated",
601            format("void f()    {     // This does something ..\n"
602                   "  }\n"
603                   "int   a;     // This is unrelated"));
604  EXPECT_EQ("void f() { // This does something ..\n"
605            "}          // awesome..\n"
606            "\n"
607            "int a; // This is unrelated",
608            format("void f()    { // This does something ..\n"
609                   "      } // awesome..\n"
610                   " \n"
611                   "int a;    // This is unrelated"));
612
613  EXPECT_EQ("int i; // single line trailing comment",
614            format("int i;\\\n// single line trailing comment"));
615
616  verifyGoogleFormat("int a;  // Trailing comment.");
617
618  verifyFormat("someFunction(anotherFunction( // Force break.\n"
619               "    parameter));");
620
621  verifyGoogleFormat("#endif  // HEADER_GUARD");
622
623  verifyFormat("const char *test[] = {\n"
624               "  // A\n"
625               "  \"aaaa\",\n"
626               "  // B\n"
627               "  \"aaaaa\",\n"
628               "};");
629  verifyGoogleFormat(
630      "aaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
631      "    aaaaaaaaaaaaaaaaaaaaaa);  // 81 cols with this comment");
632  EXPECT_EQ("D(a, {\n"
633            "  // test\n"
634            "  int a;\n"
635            "});",
636            format("D(a, {\n"
637                   "// test\n"
638                   "int a;\n"
639                   "});"));
640
641  EXPECT_EQ("lineWith(); // comment\n"
642            "// at start\n"
643            "otherLine();",
644            format("lineWith();   // comment\n"
645                   "// at start\n"
646                   "otherLine();"));
647  EXPECT_EQ("lineWith(); // comment\n"
648            "            // at start\n"
649            "otherLine();",
650            format("lineWith();   // comment\n"
651                   " // at start\n"
652                   "otherLine();"));
653
654  EXPECT_EQ("lineWith(); // comment\n"
655            "// at start\n"
656            "otherLine(); // comment",
657            format("lineWith();   // comment\n"
658                   "// at start\n"
659                   "otherLine();   // comment"));
660  EXPECT_EQ("lineWith();\n"
661            "// at start\n"
662            "otherLine(); // comment",
663            format("lineWith();\n"
664                   " // at start\n"
665                   "otherLine();   // comment"));
666  EXPECT_EQ("// first\n"
667            "// at start\n"
668            "otherLine(); // comment",
669            format("// first\n"
670                   " // at start\n"
671                   "otherLine();   // comment"));
672  EXPECT_EQ("f();\n"
673            "// first\n"
674            "// at start\n"
675            "otherLine(); // comment",
676            format("f();\n"
677                   "// first\n"
678                   " // at start\n"
679                   "otherLine();   // comment"));
680}
681
682TEST_F(FormatTest, CanFormatCommentsLocally) {
683  EXPECT_EQ("int a;    // comment\n"
684            "int    b; // comment",
685            format("int   a; // comment\n"
686                   "int    b; // comment",
687                   0, 0, getLLVMStyle()));
688  EXPECT_EQ("int   a; // comment\n"
689            "         // line 2\n"
690            "int b;",
691            format("int   a; // comment\n"
692                   "            // line 2\n"
693                   "int b;",
694                   28, 0, getLLVMStyle()));
695  EXPECT_EQ("int aaaaaa; // comment\n"
696            "int b;\n"
697            "int c; // unrelated comment",
698            format("int aaaaaa; // comment\n"
699                   "int b;\n"
700                   "int   c; // unrelated comment",
701                   31, 0, getLLVMStyle()));
702}
703
704TEST_F(FormatTest, RemovesTrailingWhitespaceOfComments) {
705  EXPECT_EQ("// comment", format("// comment  "));
706  EXPECT_EQ("int aaaaaaa, bbbbbbb; // comment",
707            format("int aaaaaaa, bbbbbbb; // comment                   ",
708                   getLLVMStyleWithColumns(33)));
709}
710
711TEST_F(FormatTest, UnderstandsMultiLineComments) {
712  verifyFormat("f(/*test=*/ true);");
713  EXPECT_EQ(
714      "f(aaaaaaaaaaaaaaaaaaaaaaaaa, /* Trailing comment for aa... */\n"
715      "  bbbbbbbbbbbbbbbbbbbbbbbbb);",
716      format("f(aaaaaaaaaaaaaaaaaaaaaaaaa ,   \\\n/* Trailing comment for aa... */\n"
717             "  bbbbbbbbbbbbbbbbbbbbbbbbb);"));
718  EXPECT_EQ(
719      "f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
720      "  /* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);",
721      format("f(aaaaaaaaaaaaaaaaaaaaaaaaa    ,   \n"
722             "/* Leading comment for bb... */   bbbbbbbbbbbbbbbbbbbbbbbbb);"));
723
724  FormatStyle NoBinPacking = getLLVMStyle();
725  NoBinPacking.BinPackParameters = false;
726  verifyFormat("aaaaaaaa(/* parameter 1 */ aaaaaa,\n"
727               "         /* parameter 2 */ aaaaaa,\n"
728               "         /* parameter 3 */ aaaaaa,\n"
729               "         /* parameter 4 */ aaaaaa);",
730               NoBinPacking);
731}
732
733TEST_F(FormatTest, AlignsMultiLineComments) {
734  EXPECT_EQ("/*\n"
735            " * Really multi-line\n"
736            " * comment.\n"
737            " */\n"
738            "void f() {}",
739            format("  /*\n"
740                   "   * Really multi-line\n"
741                   "   * comment.\n"
742                   "   */\n"
743                   "  void f() {}"));
744  EXPECT_EQ("class C {\n"
745            "  /*\n"
746            "   * Another multi-line\n"
747            "   * comment.\n"
748            "   */\n"
749            "  void f() {}\n"
750            "};",
751            format("class C {\n"
752                   "/*\n"
753                   " * Another multi-line\n"
754                   " * comment.\n"
755                   " */\n"
756                   "void f() {}\n"
757                   "};"));
758  EXPECT_EQ("/*\n"
759            "  1. This is a comment with non-trivial formatting.\n"
760            "     1.1. We have to indent/outdent all lines equally\n"
761            "         1.1.1. to keep the formatting.\n"
762            " */",
763            format("  /*\n"
764                   "    1. This is a comment with non-trivial formatting.\n"
765                   "       1.1. We have to indent/outdent all lines equally\n"
766                   "           1.1.1. to keep the formatting.\n"
767                   "   */"));
768  EXPECT_EQ("/*\n"
769            "Don't try to outdent if there's not enough inentation.\n"
770            "*/",
771            format("  /*\n"
772                   " Don't try to outdent if there's not enough inentation.\n"
773                   " */"));
774
775  EXPECT_EQ("int i; /* Comment with empty...\n"
776            "        *\n"
777            "        * line. */",
778            format("int i; /* Comment with empty...\n"
779                   "        *\n"
780                   "        * line. */"));
781}
782
783TEST_F(FormatTest, SplitsLongCxxComments) {
784  EXPECT_EQ("// A comment that\n"
785            "// doesn't fit on\n"
786            "// one line",
787            format("// A comment that doesn't fit on one line",
788                   getLLVMStyleWithColumns(20)));
789  EXPECT_EQ("// a b c d\n"
790            "// e f  g\n"
791            "// h i j k",
792            format("// a b c d e f  g h i j k",
793                   getLLVMStyleWithColumns(10)));
794  EXPECT_EQ("// a b c d\n"
795            "// e f  g\n"
796            "// h i j k",
797            format("\\\n// a b c d e f  g h i j k",
798                   getLLVMStyleWithColumns(10)));
799  EXPECT_EQ("if (true) // A comment that\n"
800            "          // doesn't fit on\n"
801            "          // one line",
802            format("if (true) // A comment that doesn't fit on one line   ",
803                   getLLVMStyleWithColumns(30)));
804  EXPECT_EQ("//    Don't_touch_leading_whitespace",
805            format("//    Don't_touch_leading_whitespace",
806                   getLLVMStyleWithColumns(20)));
807  EXPECT_EQ(
808      "//Don't add leading\n"
809      "//whitespace",
810      format("//Don't add leading whitespace", getLLVMStyleWithColumns(20)));
811  EXPECT_EQ("// A comment before\n"
812            "// a macro\n"
813            "// definition\n"
814            "#define a b",
815            format("// A comment before a macro definition\n"
816                   "#define a b",
817                   getLLVMStyleWithColumns(20)));
818
819  EXPECT_EQ("/* A comment before\n"
820            " * a macro\n"
821            " * definition */\n"
822            "#define a b",
823            format("/* A comment before a macro definition */\n"
824                   "#define a b",
825                   getLLVMStyleWithColumns(20)));
826
827  EXPECT_EQ("/* some comment\n"
828            "     *   a comment\n"
829            "* that we break\n"
830            " * another comment\n"
831            "* we have to break\n"
832            "* a left comment\n"
833            " */",
834            format("  /* some comment\n"
835                   "       *   a comment that we break\n"
836                   "   * another comment we have to break\n"
837                   "* a left comment\n"
838                   "   */",
839                   getLLVMStyleWithColumns(20)));
840
841  EXPECT_EQ("/*\n"
842            "\n"
843            "\n"
844            "    */\n",
845            format("  /*       \n"
846                   "      \n"
847                   "               \n"
848                   "      */\n"));
849}
850
851TEST_F(FormatTest, MultiLineCommentsInDefines) {
852  // FIXME: The line breaks are still suboptimal (current guess
853  // is that this is due to the token length being misused), but
854  // the comment handling is correct.
855  EXPECT_EQ("#define A(      \\\n"
856            "    x) /*       \\\n"
857            "a comment       \\\n"
858            "inside */       \\\n"
859            "  f();",
860            format("#define A(x) /* \\\n"
861                   "  a comment     \\\n"
862                   "  inside */     \\\n"
863                   "  f();",
864                   getLLVMStyleWithColumns(17)));
865  EXPECT_EQ("#define A(x) /* \\\n"
866            "        a       \\\n"
867            "        comment \\\n"
868            "        inside  \\\n"
869            "        */      \\\n"
870            "  f();",
871            format("#define A(      \\\n"
872                   "    x) /*       \\\n"
873                   "  a comment     \\\n"
874                   "  inside */     \\\n"
875                   "  f();",
876                   getLLVMStyleWithColumns(17)));
877}
878
879TEST_F(FormatTest, ParsesCommentsAdjacentToPPDirectives) {
880  EXPECT_EQ("namespace {\n}\n// Test\n#define A",
881            format("namespace {}\n   // Test\n#define A"));
882  EXPECT_EQ("namespace {\n}\n/* Test */\n#define A",
883            format("namespace {}\n   /* Test */\n#define A"));
884  EXPECT_EQ("namespace {\n}\n/* Test */ #define A",
885            format("namespace {}\n   /* Test */    #define A"));
886}
887
888TEST_F(FormatTest, SplitsLongLinesInComments) {
889  EXPECT_EQ("/* This is a long\n"
890            " * comment that\n"
891            " * doesn't\n"
892            " * fit on one line.\n"
893            " */",
894            format("/* "
895                   "This is a long                                         "
896                   "comment that "
897                   "doesn't                                    "
898                   "fit on one line.  */",
899                   getLLVMStyleWithColumns(20)));
900  EXPECT_EQ("/* a b c d\n"
901            " * e f  g\n"
902            " * h i j k\n"
903            " */",
904            format("/* a b c d e f  g h i j k */",
905                   getLLVMStyleWithColumns(10)));
906  EXPECT_EQ("/* a b c d\n"
907            " * e f  g\n"
908            " * h i j k\n"
909            " */",
910            format("\\\n/* a b c d e f  g h i j k */",
911                   getLLVMStyleWithColumns(10)));
912  EXPECT_EQ("/*\n"
913            "This is a long\n"
914            "comment that doesn't\n"
915            "fit on one line.\n"
916            "*/",
917            format("/*\n"
918                   "This is a long                                         "
919                   "comment that doesn't                                    "
920                   "fit on one line.                                      \n"
921                   "*/", getLLVMStyleWithColumns(20)));
922  EXPECT_EQ("/*\n"
923            " * This is a long\n"
924            " * comment that\n"
925            " * doesn't fit on\n"
926            " * one line.\n"
927            " */",
928            format("/*      \n"
929                   " * This is a long "
930                   "   comment that     "
931                   "   doesn't fit on   "
932                   "   one line.                                            \n"
933                   " */", getLLVMStyleWithColumns(20)));
934  EXPECT_EQ("/*\n"
935            " * This_is_a_comment_with_words_that_dont_fit_on_one_line\n"
936            " * so_it_should_be_broken\n"
937            " * wherever_a_space_occurs\n"
938            " */",
939            format("/*\n"
940                   " * This_is_a_comment_with_words_that_dont_fit_on_one_line "
941                   "   so_it_should_be_broken "
942                   "   wherever_a_space_occurs                             \n"
943                   " */",
944                   getLLVMStyleWithColumns(20)));
945  EXPECT_EQ("/*\n"
946            " *    This_comment_can_not_be_broken_into_lines\n"
947            " */",
948            format("/*\n"
949                   " *    This_comment_can_not_be_broken_into_lines\n"
950                   " */",
951                   getLLVMStyleWithColumns(20)));
952  EXPECT_EQ("{\n"
953            "  /*\n"
954            "  This is another\n"
955            "  long comment that\n"
956            "  doesn't fit on one\n"
957            "  line    1234567890\n"
958            "  */\n"
959            "}",
960            format("{\n"
961                   "/*\n"
962                   "This is another     "
963                   "  long comment that "
964                   "  doesn't fit on one"
965                   "  line    1234567890\n"
966                   "*/\n"
967                   "}", getLLVMStyleWithColumns(20)));
968  EXPECT_EQ("{\n"
969            "  /*\n"
970            "   * This        i s\n"
971            "   * another comment\n"
972            "   * t hat  doesn' t\n"
973            "   * fit on one l i\n"
974            "   * n e\n"
975            "   */\n"
976            "}",
977            format("{\n"
978                   "/*\n"
979                   " * This        i s"
980                   "   another comment"
981                   "   t hat  doesn' t"
982                   "   fit on one l i"
983                   "   n e\n"
984                   " */\n"
985                   "}", getLLVMStyleWithColumns(20)));
986  EXPECT_EQ("/*\n"
987            " * This is a long\n"
988            " * comment that\n"
989            " * doesn't fit on\n"
990            " * one line\n"
991            " */",
992            format("   /*\n"
993                   "    * This is a long comment that doesn't fit on one line\n"
994                   "    */", getLLVMStyleWithColumns(20)));
995  EXPECT_EQ("{\n"
996            "  if (something) /* This is a\n"
997            "                    long\n"
998            "                    comment */\n"
999            "    ;\n"
1000            "}",
1001            format("{\n"
1002                   "  if (something) /* This is a long comment */\n"
1003                   "    ;\n"
1004                   "}",
1005                   getLLVMStyleWithColumns(30)));
1006}
1007
1008TEST_F(FormatTest, SplitsLongLinesInCommentsInPreprocessor) {
1009  EXPECT_EQ("#define X          \\\n"
1010            "  /*               \\\n"
1011            "   Test            \\\n"
1012            "   Macro comment   \\\n"
1013            "   with a long     \\\n"
1014            "   line            \\\n"
1015            "   */              \\\n"
1016            "  A + B",
1017            format("#define X \\\n"
1018                   "  /*\n"
1019                   "   Test\n"
1020                   "   Macro comment with a long  line\n"
1021                   "   */ \\\n"
1022                   "  A + B",
1023                   getLLVMStyleWithColumns(20)));
1024  EXPECT_EQ("#define X          \\\n"
1025            "  /* Macro comment \\\n"
1026            "     with a long   \\\n"
1027            "     line */       \\\n"
1028            "  A + B",
1029            format("#define X \\\n"
1030                   "  /* Macro comment with a long\n"
1031                   "     line */ \\\n"
1032                   "  A + B",
1033                   getLLVMStyleWithColumns(20)));
1034  EXPECT_EQ("#define X          \\\n"
1035            "  /* Macro comment \\\n"
1036            "   * with a long   \\\n"
1037            "   * line */       \\\n"
1038            "  A + B",
1039            format("#define X \\\n"
1040                   "  /* Macro comment with a long  line */ \\\n"
1041                   "  A + B",
1042                   getLLVMStyleWithColumns(20)));
1043}
1044
1045TEST_F(FormatTest, CommentsInStaticInitializers) {
1046  EXPECT_EQ(
1047      "static SomeType type = { aaaaaaaaaaaaaaaaaaaa, /* comment */\n"
1048      "                         aaaaaaaaaaaaaaaaaaaa /* comment */,\n"
1049      "                         /* comment */ aaaaaaaaaaaaaaaaaaaa,\n"
1050      "                         aaaaaaaaaaaaaaaaaaaa, // comment\n"
1051      "                         aaaaaaaaaaaaaaaaaaaa };",
1052      format("static SomeType type = { aaaaaaaaaaaaaaaaaaaa  ,  /* comment */\n"
1053             "                   aaaaaaaaaaaaaaaaaaaa   /* comment */ ,\n"
1054             "                     /* comment */   aaaaaaaaaaaaaaaaaaaa ,\n"
1055             "              aaaaaaaaaaaaaaaaaaaa ,   // comment\n"
1056             "                  aaaaaaaaaaaaaaaaaaaa };"));
1057  verifyFormat("static SomeType type = { aaaaaaaaaaa, // comment for aa...\n"
1058               "                         bbbbbbbbbbb, ccccccccccc };");
1059  verifyFormat("static SomeType type = { aaaaaaaaaaa,\n"
1060               "                         // comment for bb....\n"
1061               "                         bbbbbbbbbbb, ccccccccccc };");
1062  verifyGoogleFormat(
1063      "static SomeType type = {aaaaaaaaaaa,  // comment for aa...\n"
1064      "                        bbbbbbbbbbb, ccccccccccc};");
1065  verifyGoogleFormat("static SomeType type = {aaaaaaaaaaa,\n"
1066                     "                        // comment for bb....\n"
1067                     "                        bbbbbbbbbbb, ccccccccccc};");
1068
1069  verifyFormat("S s = { { a, b, c },   // Group #1\n"
1070               "        { d, e, f },   // Group #2\n"
1071               "        { g, h, i } }; // Group #3");
1072  verifyFormat("S s = { { // Group #1\n"
1073               "          a, b, c },\n"
1074               "        { // Group #2\n"
1075               "          d, e, f },\n"
1076               "        { // Group #3\n"
1077               "          g, h, i } };");
1078
1079  EXPECT_EQ("S s = {\n"
1080            "  // Some comment\n"
1081            "  a,\n"
1082            "\n"
1083            "  // Comment after empty line\n"
1084            "  b\n"
1085            "}",
1086            format("S s =    {\n"
1087                   "      // Some comment\n"
1088                   "  a,\n"
1089                   "  \n"
1090                   "     // Comment after empty line\n"
1091                   "      b\n"
1092                   "}"));
1093  EXPECT_EQ("S s = { a, b };", format("S s = {\n"
1094                                      "  a,\n"
1095                                      "\n"
1096                                      "  b\n"
1097                                      "};"));
1098  verifyFormat("const uint8_t aaaaaaaaaaaaaaaaaaaaaa[0] = {\n"
1099               "  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1100               "  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1101               "  0x00, 0x00, 0x00, 0x00              // comment\n"
1102               "};");
1103}
1104
1105TEST_F(FormatTest, IgnoresIf0Contents) {
1106  EXPECT_EQ("#if 0\n"
1107            "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1108            "#endif\n"
1109            "void f() {}",
1110            format("#if 0\n"
1111                   "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1112                   "#endif\n"
1113                   "void f(  ) {  }"));
1114  EXPECT_EQ("#if false\n"
1115            "void f(  ) {  }\n"
1116            "#endif\n"
1117            "void g() {}\n",
1118            format("#if false\n"
1119                   "void f(  ) {  }\n"
1120                   "#endif\n"
1121                   "void g(  ) {  }\n"));
1122  EXPECT_EQ("enum E {\n"
1123            "  One,\n"
1124            "  Two,\n"
1125            "#if 0\n"
1126            "Three,\n"
1127            "      Four,\n"
1128            "#endif\n"
1129            "  Five\n"
1130            "};",
1131            format("enum E {\n"
1132                   "  One,Two,\n"
1133                   "#if 0\n"
1134                   "Three,\n"
1135                   "      Four,\n"
1136                   "#endif\n"
1137                   "  Five};"));
1138  EXPECT_EQ("enum F {\n"
1139            "  One,\n"
1140            "#if 1\n"
1141            "  Two,\n"
1142            "#if 0\n"
1143            "Three,\n"
1144            "      Four,\n"
1145            "#endif\n"
1146            "  Five\n"
1147            "#endif\n"
1148            "};",
1149            format("enum F {\n"
1150                   "One,\n"
1151                   "#if 1\n"
1152                   "Two,\n"
1153                   "#if 0\n"
1154                   "Three,\n"
1155                   "      Four,\n"
1156                   "#endif\n"
1157                   "Five\n"
1158                   "#endif\n"
1159                   "};"));
1160  EXPECT_EQ("enum G {\n"
1161            "  One,\n"
1162            "#if 0\n"
1163            "Two,\n"
1164            "#else\n"
1165            "  Three,\n"
1166            "#endif\n"
1167            "  Four\n"
1168            "};",
1169            format("enum G {\n"
1170                   "One,\n"
1171                   "#if 0\n"
1172                   "Two,\n"
1173                   "#else\n"
1174                   "Three,\n"
1175                   "#endif\n"
1176                   "Four\n"
1177                   "};"));
1178  EXPECT_EQ("enum H {\n"
1179            "  One,\n"
1180            "#if 0\n"
1181            "#ifdef Q\n"
1182            "Two,\n"
1183            "#else\n"
1184            "Three,\n"
1185            "#endif\n"
1186            "#endif\n"
1187            "  Four\n"
1188            "};",
1189            format("enum H {\n"
1190                   "One,\n"
1191                   "#if 0\n"
1192                   "#ifdef Q\n"
1193                   "Two,\n"
1194                   "#else\n"
1195                   "Three,\n"
1196                   "#endif\n"
1197                   "#endif\n"
1198                   "Four\n"
1199                   "};"));
1200  EXPECT_EQ("enum I {\n"
1201            "  One,\n"
1202            "#if /* test */ 0 || 1\n"
1203            "Two,\n"
1204            "Three,\n"
1205            "#endif\n"
1206            "  Four\n"
1207            "};",
1208            format("enum I {\n"
1209                   "One,\n"
1210                   "#if /* test */ 0 || 1\n"
1211                   "Two,\n"
1212                   "Three,\n"
1213                   "#endif\n"
1214                   "Four\n"
1215                   "};"));
1216  EXPECT_EQ("enum J {\n"
1217            "  One,\n"
1218            "#if 0\n"
1219            "#if 0\n"
1220            "Two,\n"
1221            "#else\n"
1222            "Three,\n"
1223            "#endif\n"
1224            "Four,\n"
1225            "#endif\n"
1226            "  Five\n"
1227            "};",
1228            format("enum J {\n"
1229                   "One,\n"
1230                   "#if 0\n"
1231                   "#if 0\n"
1232                   "Two,\n"
1233                   "#else\n"
1234                   "Three,\n"
1235                   "#endif\n"
1236                   "Four,\n"
1237                   "#endif\n"
1238                   "Five\n"
1239                   "};"));
1240
1241}
1242
1243//===----------------------------------------------------------------------===//
1244// Tests for classes, namespaces, etc.
1245//===----------------------------------------------------------------------===//
1246
1247TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1248  verifyFormat("class A {\n};");
1249}
1250
1251TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1252  verifyFormat("class A {\n"
1253               "public:\n"
1254               "public: // comment\n"
1255               "protected:\n"
1256               "private:\n"
1257               "  void f() {}\n"
1258               "};");
1259  verifyGoogleFormat("class A {\n"
1260                     " public:\n"
1261                     " protected:\n"
1262                     " private:\n"
1263                     "  void f() {}\n"
1264                     "};");
1265}
1266
1267TEST_F(FormatTest, SeparatesLogicalBlocks) {
1268  EXPECT_EQ("class A {\n"
1269            "public:\n"
1270            "  void f();\n"
1271            "\n"
1272            "private:\n"
1273            "  void g() {}\n"
1274            "  // test\n"
1275            "protected:\n"
1276            "  int h;\n"
1277            "};",
1278            format("class A {\n"
1279                   "public:\n"
1280                   "void f();\n"
1281                   "private:\n"
1282                   "void g() {}\n"
1283                   "// test\n"
1284                   "protected:\n"
1285                   "int h;\n"
1286                   "};"));
1287}
1288
1289TEST_F(FormatTest, FormatsClasses) {
1290  verifyFormat("class A : public B {\n};");
1291  verifyFormat("class A : public ::B {\n};");
1292
1293  verifyFormat(
1294      "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1295      "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {\n"
1296      "};\n");
1297  verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
1298               "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1299               "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {\n"
1300               "};\n");
1301  verifyFormat(
1302      "class A : public B, public C, public D, public E, public F, public G {\n"
1303      "};");
1304  verifyFormat("class AAAAAAAAAAAA : public B,\n"
1305               "                     public C,\n"
1306               "                     public D,\n"
1307               "                     public E,\n"
1308               "                     public F,\n"
1309               "                     public G {\n"
1310               "};");
1311
1312  verifyFormat("class\n"
1313               "    ReallyReallyLongClassName {\n};",
1314               getLLVMStyleWithColumns(32));
1315}
1316
1317TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
1318  verifyFormat("class A {\n} a, b;");
1319  verifyFormat("struct A {\n} a, b;");
1320  verifyFormat("union A {\n} a;");
1321}
1322
1323TEST_F(FormatTest, FormatsEnum) {
1324  verifyFormat("enum {\n"
1325               "  Zero,\n"
1326               "  One = 1,\n"
1327               "  Two = One + 1,\n"
1328               "  Three = (One + Two),\n"
1329               "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1330               "  Five = (One, Two, Three, Four, 5)\n"
1331               "};");
1332  verifyFormat("enum Enum {\n"
1333               "};");
1334  verifyFormat("enum {\n"
1335               "};");
1336  verifyFormat("enum X E {\n} d;");
1337  verifyFormat("enum __attribute__((...)) E {\n} d;");
1338  verifyFormat("enum __declspec__((...)) E {\n} d;");
1339  verifyFormat("enum X f() {\n  a();\n  return 42;\n}");
1340}
1341
1342TEST_F(FormatTest, FormatsBitfields) {
1343  verifyFormat("struct Bitfields {\n"
1344               "  unsigned sClass : 8;\n"
1345               "  unsigned ValueKind : 2;\n"
1346               "};");
1347}
1348
1349TEST_F(FormatTest, FormatsNamespaces) {
1350  verifyFormat("namespace some_namespace {\n"
1351               "class A {\n};\n"
1352               "void f() { f(); }\n"
1353               "}");
1354  verifyFormat("namespace {\n"
1355               "class A {\n};\n"
1356               "void f() { f(); }\n"
1357               "}");
1358  verifyFormat("inline namespace X {\n"
1359               "class A {\n};\n"
1360               "void f() { f(); }\n"
1361               "}");
1362  verifyFormat("using namespace some_namespace;\n"
1363               "class A {\n};\n"
1364               "void f() { f(); }");
1365
1366  // This code is more common than we thought; if we
1367  // layout this correctly the semicolon will go into
1368  // its own line, which is undesireable.
1369  verifyFormat("namespace {\n};");
1370  verifyFormat("namespace {\n"
1371               "class A {\n"
1372               "};\n"
1373               "};");
1374}
1375
1376TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
1377
1378TEST_F(FormatTest, FormatsInlineASM) {
1379  verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
1380  verifyFormat(
1381      "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
1382      "    \"cpuid\\n\\t\"\n"
1383      "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
1384      "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
1385      "    : \"a\"(value));");
1386}
1387
1388TEST_F(FormatTest, FormatTryCatch) {
1389  // FIXME: Handle try-catch explicitly in the UnwrappedLineParser, then we'll
1390  // also not create single-line-blocks.
1391  verifyFormat("try {\n"
1392               "  throw a * b;\n"
1393               "}\n"
1394               "catch (int a) {\n"
1395               "  // Do nothing.\n"
1396               "}\n"
1397               "catch (...) {\n"
1398               "  exit(42);\n"
1399               "}");
1400
1401  // Function-level try statements.
1402  verifyFormat("int f() try { return 4; }\n"
1403               "catch (...) {\n"
1404               "  return 5;\n"
1405               "}");
1406  verifyFormat("class A {\n"
1407               "  int a;\n"
1408               "  A() try : a(0) {}\n"
1409               "  catch (...) {\n"
1410               "    throw;\n"
1411               "  }\n"
1412               "};\n");
1413}
1414
1415TEST_F(FormatTest, FormatObjCTryCatch) {
1416  verifyFormat("@try {\n"
1417               "  f();\n"
1418               "}\n"
1419               "@catch (NSException e) {\n"
1420               "  @throw;\n"
1421               "}\n"
1422               "@finally {\n"
1423               "  exit(42);\n"
1424               "}");
1425}
1426
1427TEST_F(FormatTest, StaticInitializers) {
1428  verifyFormat("static SomeClass SC = { 1, 'a' };");
1429
1430  verifyFormat(
1431      "static SomeClass WithALoooooooooooooooooooongName = {\n"
1432      "  100000000, \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
1433      "};");
1434
1435  verifyFormat(
1436      "static SomeClass = { a, b, c, d, e, f, g, h, i, j,\n"
1437      "                     looooooooooooooooooooooooooooooooooongname,\n"
1438      "                     looooooooooooooooooooooooooooooong };");
1439  // Allow bin-packing in static initializers as this would often lead to
1440  // terrible results, e.g.:
1441  verifyGoogleFormat(
1442      "static SomeClass = {a, b, c, d, e, f, g, h, i, j,\n"
1443      "                    looooooooooooooooooooooooooooooooooongname,\n"
1444      "                    looooooooooooooooooooooooooooooong};");
1445  // Here, everything other than the "}" would fit on a line.
1446  verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
1447               "  100000000000000000000000\n"
1448               "};");
1449
1450  // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
1451  // line. However, the formatting looks a bit off and this probably doesn't
1452  // happen often in practice.
1453  verifyFormat("static int Variable[1] = {\n"
1454               "  { 1000000000000000000000000000000000000 }\n"
1455               "};",
1456               getLLVMStyleWithColumns(40));
1457}
1458
1459TEST_F(FormatTest, DesignatedInitializers) {
1460  verifyFormat("const struct A a = { .a = 1, .b = 2 };");
1461  verifyFormat("const struct A a = { .aaaaaaaaaa = 1,\n"
1462               "                     .bbbbbbbbbb = 2,\n"
1463               "                     .cccccccccc = 3,\n"
1464               "                     .dddddddddd = 4,\n"
1465               "                     .eeeeeeeeee = 5 };");
1466  verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
1467               "  .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
1468               "  .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
1469               "  .ccccccccccccccccccccccccccc = 3,\n"
1470               "  .ddddddddddddddddddddddddddd = 4,\n"
1471               "  .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5\n"
1472               "};");
1473
1474  verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
1475}
1476
1477TEST_F(FormatTest, NestedStaticInitializers) {
1478  verifyFormat("static A x = { { {} } };\n");
1479  verifyFormat("static A x = { { { init1, init2, init3, init4 },\n"
1480               "                 { init1, init2, init3, init4 } } };");
1481
1482  verifyFormat("somes Status::global_reps[3] = {\n"
1483               "  { kGlobalRef, OK_CODE, NULL, NULL, NULL },\n"
1484               "  { kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL },\n"
1485               "  { kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL }\n"
1486               "};");
1487  verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
1488                     "  {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
1489                     "  {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
1490                     "  {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}\n"
1491                     "};");
1492  verifyFormat(
1493      "CGRect cg_rect = { { rect.fLeft, rect.fTop },\n"
1494      "                   { rect.fRight - rect.fLeft, rect.fBottom - rect.fTop"
1495      " } };");
1496
1497  verifyFormat(
1498      "SomeArrayOfSomeType a = { { { 1, 2, 3 }, { 1, 2, 3 },\n"
1499      "                            { 111111111111111111111111111111,\n"
1500      "                              222222222222222222222222222222,\n"
1501      "                              333333333333333333333333333333 },\n"
1502      "                            { 1, 2, 3 }, { 1, 2, 3 } } };");
1503  verifyFormat(
1504      "SomeArrayOfSomeType a = { { { 1, 2, 3 } }, { { 1, 2, 3 } },\n"
1505      "                          { { 111111111111111111111111111111,\n"
1506      "                              222222222222222222222222222222,\n"
1507      "                              333333333333333333333333333333 } },\n"
1508      "                          { { 1, 2, 3 } }, { { 1, 2, 3 } } };");
1509  verifyGoogleFormat(
1510      "SomeArrayOfSomeType a = {{{1, 2, 3}}, {{1, 2, 3}},\n"
1511      "                         {{111111111111111111111111111111,\n"
1512      "                           222222222222222222222222222222,\n"
1513      "                           333333333333333333333333333333}},\n"
1514      "                         {{1, 2, 3}}, {{1, 2, 3}}};");
1515
1516  // FIXME: We might at some point want to handle this similar to parameter
1517  // lists, where we have an option to put each on a single line.
1518  verifyFormat(
1519      "struct {\n"
1520      "  unsigned bit;\n"
1521      "  const char *const name;\n"
1522      "} kBitsToOs[] = { { kOsMac, \"Mac\" }, { kOsWin, \"Windows\" },\n"
1523      "                  { kOsLinux, \"Linux\" }, { kOsCrOS, \"Chrome OS\" } };");
1524}
1525
1526TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
1527  verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
1528               "                      \\\n"
1529               "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
1530}
1531
1532TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
1533  verifyFormat(
1534      "virtual void write(ELFWriter *writerrr,\n"
1535      "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
1536}
1537
1538TEST_F(FormatTest, LayoutUnknownPPDirective) {
1539  EXPECT_EQ("#123 \"A string literal\"",
1540            format("   #     123    \"A string literal\""));
1541  EXPECT_EQ("#;", format("#;"));
1542  verifyFormat("#\n;\n;\n;");
1543}
1544
1545TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
1546  EXPECT_EQ("#line 42 \"test\"\n",
1547            format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
1548  EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
1549                                    getLLVMStyleWithColumns(12)));
1550}
1551
1552TEST_F(FormatTest, EndOfFileEndsPPDirective) {
1553  EXPECT_EQ("#line 42 \"test\"",
1554            format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
1555  EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
1556}
1557
1558TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
1559  verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
1560  verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
1561  verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
1562  // FIXME: We never break before the macro name.
1563  verifyFormat("#define AA(\\\n    B)", getLLVMStyleWithColumns(12));
1564
1565  verifyFormat("#define A A\n#define A A");
1566  verifyFormat("#define A(X) A\n#define A A");
1567
1568  verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
1569  verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
1570}
1571
1572TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
1573  EXPECT_EQ("// somecomment\n"
1574            "#include \"a.h\"\n"
1575            "#define A(  \\\n"
1576            "    A, B)\n"
1577            "#include \"b.h\"\n"
1578            "// somecomment\n",
1579            format("  // somecomment\n"
1580                   "  #include \"a.h\"\n"
1581                   "#define A(A,\\\n"
1582                   "    B)\n"
1583                   "    #include \"b.h\"\n"
1584                   " // somecomment\n",
1585                   getLLVMStyleWithColumns(13)));
1586}
1587
1588TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
1589
1590TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
1591  EXPECT_EQ("#define A    \\\n"
1592            "  c;         \\\n"
1593            "  e;\n"
1594            "f;",
1595            format("#define A c; e;\n"
1596                   "f;",
1597                   getLLVMStyleWithColumns(14)));
1598}
1599
1600TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
1601
1602TEST_F(FormatTest, AlwaysFormatsEntireMacroDefinitions) {
1603  EXPECT_EQ("int  i;\n"
1604            "#define A \\\n"
1605            "  int i;  \\\n"
1606            "  int j\n"
1607            "int  k;",
1608            format("int  i;\n"
1609                   "#define A  \\\n"
1610                   " int   i    ;  \\\n"
1611                   " int   j\n"
1612                   "int  k;",
1613                   8, 0, getGoogleStyle())); // 8: position of "#define".
1614  EXPECT_EQ("int  i;\n"
1615            "#define A \\\n"
1616            "  int i;  \\\n"
1617            "  int j\n"
1618            "int  k;",
1619            format("int  i;\n"
1620                   "#define A  \\\n"
1621                   " int   i    ;  \\\n"
1622                   " int   j\n"
1623                   "int  k;",
1624                   45, 0, getGoogleStyle())); // 45: position of "j".
1625}
1626
1627TEST_F(FormatTest, MacroDefinitionInsideStatement) {
1628  EXPECT_EQ("int x,\n"
1629            "#define A\n"
1630            "    y;",
1631            format("int x,\n#define A\ny;"));
1632}
1633
1634TEST_F(FormatTest, HashInMacroDefinition) {
1635  verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
1636  verifyFormat("#define A \\\n"
1637               "  {       \\\n"
1638               "    f(#c);\\\n"
1639               "  }",
1640               getLLVMStyleWithColumns(11));
1641
1642  verifyFormat("#define A(X)         \\\n"
1643               "  void function##X()",
1644               getLLVMStyleWithColumns(22));
1645
1646  verifyFormat("#define A(a, b, c)   \\\n"
1647               "  void a##b##c()",
1648               getLLVMStyleWithColumns(22));
1649
1650  verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
1651}
1652
1653TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
1654  verifyFormat("#define A (1)");
1655}
1656
1657TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
1658  EXPECT_EQ("#define A b;", format("#define A \\\n"
1659                                   "          \\\n"
1660                                   "  b;",
1661                                   getLLVMStyleWithColumns(25)));
1662  EXPECT_EQ("#define A \\\n"
1663            "          \\\n"
1664            "  a;      \\\n"
1665            "  b;",
1666            format("#define A \\\n"
1667                   "          \\\n"
1668                   "  a;      \\\n"
1669                   "  b;",
1670                   getLLVMStyleWithColumns(11)));
1671  EXPECT_EQ("#define A \\\n"
1672            "  a;      \\\n"
1673            "          \\\n"
1674            "  b;",
1675            format("#define A \\\n"
1676                   "  a;      \\\n"
1677                   "          \\\n"
1678                   "  b;",
1679                   getLLVMStyleWithColumns(11)));
1680}
1681
1682TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
1683  verifyFormat("#define A :");
1684  verifyFormat("#define SOMECASES  \\\n"
1685               "  case 1:          \\\n"
1686               "  case 2\n",
1687               getLLVMStyleWithColumns(20));
1688  verifyFormat("#define A template <typename T>");
1689  verifyFormat("#define STR(x) #x\n"
1690               "f(STR(this_is_a_string_literal{));");
1691}
1692
1693TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
1694  verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
1695  EXPECT_EQ("class A : public QObject {\n"
1696            "  Q_OBJECT\n"
1697            "\n"
1698            "  A() {}\n"
1699            "};",
1700            format("class A  :  public QObject {\n"
1701                   "     Q_OBJECT\n"
1702                   "\n"
1703                   "  A() {\n}\n"
1704                   "}  ;"));
1705  EXPECT_EQ("SOME_MACRO\n"
1706            "namespace {\n"
1707            "void f();\n"
1708            "}",
1709            format("SOME_MACRO\n"
1710                   "  namespace    {\n"
1711                   "void   f(  );\n"
1712                   "}"));
1713  // Only if the identifier contains at least 5 characters.
1714  EXPECT_EQ("HTTP f();",
1715            format("HTTP\nf();"));
1716  EXPECT_EQ("MACRO\nf();",
1717            format("MACRO\nf();"));
1718  // Only if everything is upper case.
1719  EXPECT_EQ("class A : public QObject {\n"
1720            "  Q_Object A() {}\n"
1721            "};",
1722            format("class A  :  public QObject {\n"
1723                   "     Q_Object\n"
1724                   "\n"
1725                   "  A() {\n}\n"
1726                   "}  ;"));
1727}
1728
1729TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
1730  EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
1731            "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
1732            "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
1733            "class X {\n"
1734            "};\n"
1735            "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
1736            "int *createScopDetectionPass() { return 0; }",
1737            format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
1738                   "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
1739                   "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
1740                   "  class X {};\n"
1741                   "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
1742                   "  int *createScopDetectionPass() { return 0; }"));
1743  // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
1744  // braces, so that inner block is indented one level more.
1745  EXPECT_EQ("int q() {\n"
1746            "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
1747            "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
1748            "  IPC_END_MESSAGE_MAP()\n"
1749            "}",
1750            format("int q() {\n"
1751                   "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
1752                   "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
1753                   "  IPC_END_MESSAGE_MAP()\n"
1754                   "}"));
1755  EXPECT_EQ("int q() {\n"
1756            "  f(x);\n"
1757            "  f(x) {}\n"
1758            "  f(x)->g();\n"
1759            "  f(x)->*g();\n"
1760            "  f(x).g();\n"
1761            "  f(x) = x;\n"
1762            "  f(x) += x;\n"
1763            "  f(x) -= x;\n"
1764            "  f(x) *= x;\n"
1765            "  f(x) /= x;\n"
1766            "  f(x) %= x;\n"
1767            "  f(x) &= x;\n"
1768            "  f(x) |= x;\n"
1769            "  f(x) ^= x;\n"
1770            "  f(x) >>= x;\n"
1771            "  f(x) <<= x;\n"
1772            "  f(x)[y].z();\n"
1773            "  LOG(INFO) << x;\n"
1774            "  ifstream(x) >> x;\n"
1775            "}\n",
1776            format("int q() {\n"
1777                   "  f(x)\n;\n"
1778                   "  f(x)\n {}\n"
1779                   "  f(x)\n->g();\n"
1780                   "  f(x)\n->*g();\n"
1781                   "  f(x)\n.g();\n"
1782                   "  f(x)\n = x;\n"
1783                   "  f(x)\n += x;\n"
1784                   "  f(x)\n -= x;\n"
1785                   "  f(x)\n *= x;\n"
1786                   "  f(x)\n /= x;\n"
1787                   "  f(x)\n %= x;\n"
1788                   "  f(x)\n &= x;\n"
1789                   "  f(x)\n |= x;\n"
1790                   "  f(x)\n ^= x;\n"
1791                   "  f(x)\n >>= x;\n"
1792                   "  f(x)\n <<= x;\n"
1793                   "  f(x)\n[y].z();\n"
1794                   "  LOG(INFO)\n << x;\n"
1795                   "  ifstream(x)\n >> x;\n"
1796                   "}\n"));
1797  EXPECT_EQ("int q() {\n"
1798            "  f(x)\n"
1799            "  if (1) {\n"
1800            "  }\n"
1801            "  f(x)\n"
1802            "  while (1) {\n"
1803            "  }\n"
1804            "  f(x)\n"
1805            "  g(x);\n"
1806            "  f(x)\n"
1807            "  try {\n"
1808            "    q();\n"
1809            "  }\n"
1810            "  catch (...) {\n"
1811            "  }\n"
1812            "}\n",
1813            format("int q() {\n"
1814                   "f(x)\n"
1815                   "if (1) {}\n"
1816                   "f(x)\n"
1817                   "while (1) {}\n"
1818                   "f(x)\n"
1819                   "g(x);\n"
1820                   "f(x)\n"
1821                   "try { q(); } catch (...) {}\n"
1822                   "}\n"));
1823  EXPECT_EQ("class A {\n"
1824            "  A() : t(0) {}\n"
1825            "  A(X x)\n" // FIXME: function-level try blocks are broken.
1826            "  try : t(0) {\n"
1827            "  }\n"
1828            "  catch (...) {\n"
1829            "  }\n"
1830            "};",
1831            format("class A {\n"
1832                   "  A()\n : t(0) {}\n"
1833                   "  A(X x)\n"
1834                   "  try : t(0) {} catch (...) {}\n"
1835                   "};"));
1836}
1837
1838TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
1839  verifyFormat("#define A \\\n"
1840               "  f({     \\\n"
1841               "    g();  \\\n"
1842               "  });", getLLVMStyleWithColumns(11));
1843}
1844
1845TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
1846  EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
1847}
1848
1849TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
1850  verifyFormat("{\n  { a #c; }\n}");
1851}
1852
1853TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
1854  EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
1855            format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
1856  EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
1857            format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
1858}
1859
1860TEST_F(FormatTest, EscapedNewlineAtStartOfTokenInMacroDefinition) {
1861  EXPECT_EQ(
1862      "#define A \\\n  int i;  \\\n  int j;",
1863      format("#define A \\\nint i;\\\n  int j;", getLLVMStyleWithColumns(11)));
1864}
1865
1866TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
1867  verifyFormat("#define A \\\n"
1868               "  int v(  \\\n"
1869               "      a); \\\n"
1870               "  int i;",
1871               getLLVMStyleWithColumns(11));
1872}
1873
1874TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
1875  EXPECT_EQ(
1876      "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
1877      "                      \\\n"
1878      "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
1879      "\n"
1880      "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
1881      "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
1882      format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
1883             "\\\n"
1884             "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
1885             "  \n"
1886             "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
1887             "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
1888}
1889
1890TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
1891  EXPECT_EQ("int\n"
1892            "#define A\n"
1893            "    a;",
1894            format("int\n#define A\na;"));
1895  verifyFormat("functionCallTo(\n"
1896               "    someOtherFunction(\n"
1897               "        withSomeParameters, whichInSequence,\n"
1898               "        areLongerThanALine(andAnotherCall,\n"
1899               "#define A B\n"
1900               "                           withMoreParamters,\n"
1901               "                           whichStronglyInfluenceTheLayout),\n"
1902               "        andMoreParameters),\n"
1903               "    trailing);",
1904               getLLVMStyleWithColumns(69));
1905}
1906
1907TEST_F(FormatTest, LayoutBlockInsideParens) {
1908  EXPECT_EQ("functionCall({\n"
1909            "  int i;\n"
1910            "});",
1911            format(" functionCall ( {int i;} );"));
1912}
1913
1914TEST_F(FormatTest, LayoutBlockInsideStatement) {
1915  EXPECT_EQ("SOME_MACRO { int i; }\n"
1916            "int i;",
1917            format("  SOME_MACRO  {int i;}  int i;"));
1918}
1919
1920TEST_F(FormatTest, LayoutNestedBlocks) {
1921  verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
1922               "  struct s {\n"
1923               "    int i;\n"
1924               "  };\n"
1925               "  s kBitsToOs[] = { { 10 } };\n"
1926               "  for (int i = 0; i < 10; ++i)\n"
1927               "    return;\n"
1928               "}");
1929}
1930
1931TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
1932  EXPECT_EQ("{}", format("{}"));
1933
1934  // Negative test for enum.
1935  verifyFormat("enum E {\n};");
1936
1937  // Note that when there's a missing ';', we still join...
1938  verifyFormat("enum E {}");
1939}
1940
1941//===----------------------------------------------------------------------===//
1942// Line break tests.
1943//===----------------------------------------------------------------------===//
1944
1945TEST_F(FormatTest, FormatsAwesomeMethodCall) {
1946  verifyFormat(
1947      "SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
1948      "                       parameter, parameter, parameter)),\n"
1949      "                   SecondLongCall(parameter));");
1950}
1951
1952TEST_F(FormatTest, PreventConfusingIndents) {
1953  verifyFormat(
1954      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1955      "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
1956      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
1957      "    aaaaaaaaaaaaaaaaaaaaaaaa);");
1958  verifyFormat(
1959      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[\n"
1960      "    aaaaaaaaaaaaaaaaaaaaaaaa[\n"
1961      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa],\n"
1962      "    aaaaaaaaaaaaaaaaaaaaaaaa];");
1963  verifyFormat(
1964      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
1965      "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
1966      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
1967      "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
1968  verifyFormat("int a = bbbb && ccc && fffff(\n"
1969               "#define A Just forcing a new line\n"
1970               "                           ddd);");
1971}
1972
1973TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
1974  verifyFormat(
1975      "bool aaaaaaa =\n"
1976      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
1977      "    bbbbbbbb();");
1978  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
1979               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
1980               "    ccccccccc == ddddddddddd;");
1981
1982  verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
1983               "                 aaaaaa) &&\n"
1984               "         bbbbbb && cccccc;");
1985  verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
1986               "                 aaaaaa) >>\n"
1987               "         bbbbbb;");
1988  verifyFormat("Whitespaces.addUntouchableComment(\n"
1989               "    SourceMgr.getSpellingColumnNumber(\n"
1990               "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
1991               "    1);");
1992
1993  FormatStyle OnePerLine = getLLVMStyle();
1994  OnePerLine.BinPackParameters = false;
1995  verifyFormat(
1996      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
1997      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
1998      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
1999      OnePerLine);
2000}
2001
2002TEST_F(FormatTest, ExpressionIndentation) {
2003  verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2004               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2005               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2006               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2007               "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
2008               "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
2009               "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2010               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
2011               "                 ccccccccccccccccccccccccccccccccccccccccc;");
2012  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2013               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2014               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2015               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2016  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2017               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2018               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2019               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2020  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2021               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2022               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2023               "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2024}
2025
2026TEST_F(FormatTest, ConstructorInitializers) {
2027  verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
2028  verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
2029               getLLVMStyleWithColumns(45));
2030  verifyFormat("Constructor()\n"
2031               "    : Inttializer(FitsOnTheLine) {}",
2032               getLLVMStyleWithColumns(44));
2033  verifyFormat("Constructor()\n"
2034               "    : Inttializer(FitsOnTheLine) {}",
2035               getLLVMStyleWithColumns(43));
2036
2037  verifyFormat(
2038      "SomeClass::Constructor()\n"
2039      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
2040
2041  verifyFormat(
2042      "SomeClass::Constructor()\n"
2043      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2044      "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
2045  verifyFormat(
2046      "SomeClass::Constructor()\n"
2047      "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2048      "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
2049
2050  verifyFormat("Constructor()\n"
2051               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2052               "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2053               "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2054               "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
2055
2056  verifyFormat("Constructor()\n"
2057               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2058               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2059
2060  verifyFormat("Constructor(int Parameter = 0)\n"
2061               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
2062               "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
2063
2064  // Here a line could be saved by splitting the second initializer onto two
2065  // lines, but that is not desireable.
2066  verifyFormat("Constructor()\n"
2067               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
2068               "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
2069               "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2070
2071  FormatStyle OnePerLine = getLLVMStyle();
2072  OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
2073  verifyFormat("SomeClass::Constructor()\n"
2074               "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2075               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2076               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
2077               OnePerLine);
2078  verifyFormat("SomeClass::Constructor()\n"
2079               "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
2080               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2081               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
2082               OnePerLine);
2083  verifyFormat("MyClass::MyClass(int var)\n"
2084               "    : some_var_(var),            // 4 space indent\n"
2085               "      some_other_var_(var + 1) { // lined up\n"
2086               "}",
2087               OnePerLine);
2088  verifyFormat("Constructor()\n"
2089               "    : aaaaa(aaaaaa),\n"
2090               "      aaaaa(aaaaaa),\n"
2091               "      aaaaa(aaaaaa),\n"
2092               "      aaaaa(aaaaaa),\n"
2093               "      aaaaa(aaaaaa) {}",
2094               OnePerLine);
2095  verifyFormat("Constructor()\n"
2096               "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
2097               "            aaaaaaaaaaaaaaaaaaaaaa) {}",
2098               OnePerLine);
2099}
2100
2101TEST_F(FormatTest, MemoizationTests) {
2102  // This breaks if the memoization lookup does not take \c Indent and
2103  // \c LastSpace into account.
2104  verifyFormat(
2105      "extern CFRunLoopTimerRef\n"
2106      "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
2107      "                     CFTimeInterval interval, CFOptionFlags flags,\n"
2108      "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
2109      "                     CFRunLoopTimerContext *context) {}");
2110
2111  // Deep nesting somewhat works around our memoization.
2112  verifyFormat(
2113      "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2114      "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2115      "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2116      "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2117      "                aaaaa())))))))))))))))))))))))))))))))))))))));",
2118      getLLVMStyleWithColumns(65));
2119  verifyFormat(
2120      "aaaaa(\n"
2121      "    aaaaa,\n"
2122      "    aaaaa(\n"
2123      "        aaaaa,\n"
2124      "        aaaaa(\n"
2125      "            aaaaa,\n"
2126      "            aaaaa(\n"
2127      "                aaaaa,\n"
2128      "                aaaaa(\n"
2129      "                    aaaaa,\n"
2130      "                    aaaaa(\n"
2131      "                        aaaaa,\n"
2132      "                        aaaaa(\n"
2133      "                            aaaaa,\n"
2134      "                            aaaaa(\n"
2135      "                                aaaaa,\n"
2136      "                                aaaaa(\n"
2137      "                                    aaaaa,\n"
2138      "                                    aaaaa(\n"
2139      "                                        aaaaa,\n"
2140      "                                        aaaaa(\n"
2141      "                                            aaaaa,\n"
2142      "                                            aaaaa(\n"
2143      "                                                aaaaa,\n"
2144      "                                                aaaaa))))))))))));",
2145      getLLVMStyleWithColumns(65));
2146  verifyFormat(
2147      "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n"
2148      "                                  a),\n"
2149      "                                a),\n"
2150      "                              a),\n"
2151      "                            a),\n"
2152      "                          a),\n"
2153      "                        a),\n"
2154      "                      a),\n"
2155      "                    a),\n"
2156      "                  a),\n"
2157      "                a),\n"
2158      "              a),\n"
2159      "            a),\n"
2160      "          a),\n"
2161      "        a),\n"
2162      "      a),\n"
2163      "    a),\n"
2164      "  a)",
2165      getLLVMStyleWithColumns(65));
2166
2167  // This test takes VERY long when memoization is broken.
2168  FormatStyle OnePerLine = getLLVMStyle();
2169  OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
2170  OnePerLine.BinPackParameters = false;
2171  std::string input = "Constructor()\n"
2172                      "    : aaaa(a,\n";
2173  for (unsigned i = 0, e = 80; i != e; ++i) {
2174    input += "           a,\n";
2175  }
2176  input += "           a) {}";
2177  verifyFormat(input, OnePerLine);
2178}
2179
2180TEST_F(FormatTest, BreaksAsHighAsPossible) {
2181  verifyFormat(
2182      "void f() {\n"
2183      "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
2184      "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
2185      "    f();\n"
2186      "}");
2187  verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
2188               "    Intervals[i - 1].getRange().getLast()) {\n}");
2189}
2190
2191TEST_F(FormatTest, BreaksFunctionDeclarations) {
2192  // Principially, we break function declarations in a certain order:
2193  // 1) break amongst arguments.
2194  verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
2195               "                              Cccccccccccccc cccccccccccccc);");
2196
2197  // 2) break after return type.
2198  verifyFormat(
2199      "Aaaaaaaaaaaaaaaaaaaaaaaa\n"
2200      "    bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);");
2201
2202  // 3) break after (.
2203  verifyFormat(
2204      "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
2205      "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);");
2206
2207  // 4) break before after nested name specifiers.
2208  verifyFormat(
2209      "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2210      "    SomeClasssssssssssssssssssssssssssssssssssssss::\n"
2211      "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);");
2212
2213  // However, there are exceptions, if a sufficient amount of lines can be
2214  // saved.
2215  // FIXME: The precise cut-offs wrt. the number of saved lines might need some
2216  // more adjusting.
2217  verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
2218               "                                  Cccccccccccccc cccccccccc,\n"
2219               "                                  Cccccccccccccc cccccccccc,\n"
2220               "                                  Cccccccccccccc cccccccccc,\n"
2221               "                                  Cccccccccccccc cccccccccc);");
2222  verifyFormat(
2223      "Aaaaaaaaaaaaaaaaaa\n"
2224      "    bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2225      "                Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2226      "                Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
2227  verifyFormat(
2228      "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
2229      "                                          Cccccccccccccc cccccccccc,\n"
2230      "                                          Cccccccccccccc cccccccccc,\n"
2231      "                                          Cccccccccccccc cccccccccc,\n"
2232      "                                          Cccccccccccccc cccccccccc,\n"
2233      "                                          Cccccccccccccc cccccccccc,\n"
2234      "                                          Cccccccccccccc cccccccccc);");
2235  verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
2236               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2237               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2238               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2239               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
2240
2241  // Break after multi-line parameters.
2242  verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2243               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2244               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2245               "    bbbb bbbb);");
2246}
2247
2248TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
2249  verifyFormat("void someLongFunction(\n"
2250               "    int someLongParameter) const {}",
2251               getLLVMStyleWithColumns(46));
2252  FormatStyle Style = getGoogleStyle();
2253  Style.ColumnLimit = 47;
2254  verifyFormat("void\n"
2255               "someLongFunction(int someLongParameter) const {\n}",
2256               getLLVMStyleWithColumns(47));
2257  verifyFormat("void someLongFunction(\n"
2258               "    int someLongParameter) const {}",
2259               Style);
2260  verifyFormat("LoooooongReturnType\n"
2261               "someLoooooooongFunction() const {}",
2262               getLLVMStyleWithColumns(47));
2263  verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
2264               "    const {}",
2265               Style);
2266
2267  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2268               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
2269  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
2270               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
2271  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
2272               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
2273
2274  verifyFormat(
2275      "void aaaaaaaaaaaaaaaaaa()\n"
2276      "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
2277      "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
2278  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2279               "    __attribute__((unused));");
2280  verifyFormat(
2281      "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2282      "    GUARDED_BY(aaaaaaaaaaaa);");
2283}
2284
2285
2286TEST_F(FormatTest, BreaksDesireably) {
2287  verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
2288               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
2289               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
2290  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2291               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2292               "}");
2293
2294  verifyFormat(
2295      "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2296      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2297
2298  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2299               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2300               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2301
2302  verifyFormat(
2303      "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2304      "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
2305      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2306      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
2307
2308  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2309               "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2310
2311  verifyFormat(
2312      "void f() {\n"
2313      "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
2314      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2315      "}");
2316  verifyFormat(
2317      "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2318      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2319  verifyFormat(
2320      "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2321      "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2322  verifyFormat(
2323      "aaaaaaaaaaaaaaaaa(\n"
2324      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2325      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2326
2327  // This test case breaks on an incorrect memoization, i.e. an optimization not
2328  // taking into account the StopAt value.
2329  verifyFormat(
2330      "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2331      "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2332      "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2333      "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2334
2335  verifyFormat("{\n  {\n    {\n"
2336               "      Annotation.SpaceRequiredBefore =\n"
2337               "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
2338               "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
2339               "    }\n  }\n}");
2340}
2341
2342TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
2343  FormatStyle NoBinPacking = getGoogleStyle();
2344  NoBinPacking.BinPackParameters = false;
2345  verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
2346               "  aaaaaaaaaaaaaaaaaaaa,\n"
2347               "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
2348               NoBinPacking);
2349  verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
2350               "        aaaaaaaaaaaaa,\n"
2351               "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
2352               NoBinPacking);
2353  verifyFormat(
2354      "aaaaaaaa(aaaaaaaaaaaaa,\n"
2355      "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2356      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
2357      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2358      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
2359      NoBinPacking);
2360  verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
2361               "    .aaaaaaaaaaaaaaaaaa();",
2362               NoBinPacking);
2363  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2364               "    aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);",
2365               NoBinPacking);
2366
2367  verifyFormat(
2368      "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2369      "             aaaaaaaaaaaa,\n"
2370      "             aaaaaaaaaaaa);",
2371      NoBinPacking);
2372  verifyFormat(
2373      "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
2374      "                               ddddddddddddddddddddddddddddd),\n"
2375      "             test);",
2376      NoBinPacking);
2377
2378  verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
2379               "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
2380               "            aaaaaaaaaaaaaaaaaaaaaaa> aaaaaaaaaaaaaaaaaa;",
2381               NoBinPacking);
2382  verifyFormat("a(\"a\"\n"
2383               "  \"a\",\n"
2384               "  a);");
2385
2386  NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
2387  verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
2388               "                aaaaaaaaa,\n"
2389               "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
2390               NoBinPacking);
2391  verifyFormat(
2392      "void f() {\n"
2393      "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
2394      "      .aaaaaaa();\n"
2395      "}",
2396      NoBinPacking);
2397  verifyFormat(
2398      "template <class SomeType, class SomeOtherType>\n"
2399      "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
2400      NoBinPacking);
2401}
2402
2403TEST_F(FormatTest, FormatsBuilderPattern) {
2404  verifyFormat(
2405      "return llvm::StringSwitch<Reference::Kind>(name)\n"
2406      "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
2407      "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME).StartsWith(\".init\", ORDER_INIT)\n"
2408      "    .StartsWith(\".fini\", ORDER_FINI).StartsWith(\".hash\", ORDER_HASH)\n"
2409      "    .Default(ORDER_TEXT);\n");
2410
2411  verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
2412               "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
2413  verifyFormat(
2414      "aaaaaaa->aaaaaaa\n"
2415      "    ->aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2416      "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
2417  verifyFormat(
2418      "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
2419      "    aaaaaaaaaaaaaa);");
2420  verifyFormat(
2421      "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa = aaaaaa->aaaaaaaaaaaa()\n"
2422      "    ->aaaaaaaaaaaaaaaa(\n"
2423      "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2424      "    ->aaaaaaaaaaaaaaaaa();");
2425}
2426
2427TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
2428  verifyFormat(
2429      "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2430      "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
2431  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
2432               "    ccccccccccccccccccccccccc) {\n}");
2433  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
2434               "    ccccccccccccccccccccccccc) {\n}");
2435  verifyFormat(
2436      "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
2437      "    ccccccccccccccccccccccccc) {\n}");
2438  verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
2439               "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
2440               "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
2441               "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
2442  verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
2443               "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
2444               "    aaaaaaaaaaaaaaa != aa) {\n}");
2445}
2446
2447TEST_F(FormatTest, BreaksAfterAssignments) {
2448  verifyFormat(
2449      "unsigned Cost =\n"
2450      "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
2451      "                        SI->getPointerAddressSpaceee());\n");
2452  verifyFormat(
2453      "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
2454      "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
2455
2456  verifyFormat(
2457      "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa()\n"
2458      "    .aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
2459  verifyFormat("unsigned OriginalStartColumn =\n"
2460               "    SourceMgr.getSpellingColumnNumber(\n"
2461               "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
2462               "    1;");
2463}
2464
2465TEST_F(FormatTest, AlignsAfterAssignments) {
2466  verifyFormat(
2467      "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2468      "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
2469  verifyFormat(
2470      "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2471      "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
2472  verifyFormat(
2473      "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2474      "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
2475  verifyFormat(
2476      "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2477      "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
2478  verifyFormat("double LooooooooooooooooooooooooongResult =\n"
2479               "    aaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaa +\n"
2480               "    aaaaaaaaaaaaaaaaaaaaaaaa;");
2481}
2482
2483TEST_F(FormatTest, AlignsAfterReturn) {
2484  verifyFormat(
2485      "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2486      "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
2487  verifyFormat(
2488      "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2489      "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
2490  verifyFormat(
2491      "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
2492      "       aaaaaaaaaaaaaaaaaaaaaa();");
2493  verifyFormat(
2494      "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
2495      "        aaaaaaaaaaaaaaaaaaaaaa());");
2496  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2497               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2498  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2499               "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
2500               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2501}
2502
2503TEST_F(FormatTest, BreaksConditionalExpressions) {
2504  verifyFormat(
2505      "aaaa(aaaaaaaaaaaaaaaaaaaa,\n"
2506      "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2507      "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2508  verifyFormat(
2509      "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2510      "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2511  verifyFormat(
2512      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
2513      "                                                    : aaaaaaaaaaaaa);");
2514  verifyFormat(
2515      "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2516      "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2517      "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2518      "                   aaaaaaaaaaaaa);");
2519  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2520               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2521               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2522               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2523               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2524  verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2525               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2526               "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2527               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2528               "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2529               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2530               "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2531
2532  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2533               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2534               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2535  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
2536               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2537               "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2538               "        : aaaaaaaaaaaaaaaa;");
2539  verifyFormat(
2540      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2541      "    ? aaaaaaaaaaaaaaa\n"
2542      "    : aaaaaaaaaaaaaaa;");
2543  verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
2544               "          aaaaaaaaa\n"
2545               "      ? b\n"
2546               "      : c);");
2547  verifyFormat(
2548      "unsigned Indent =\n"
2549      "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0\n"
2550      "                              ? IndentForLevel[TheLine.Level]\n"
2551      "                              : TheLine * 2,\n"
2552      "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
2553      getLLVMStyleWithColumns(70));
2554
2555  FormatStyle NoBinPacking = getLLVMStyle();
2556  NoBinPacking.BinPackParameters = false;
2557  verifyFormat(
2558      "void f() {\n"
2559      "  g(aaa,\n"
2560      "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
2561      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2562      "        ? aaaaaaaaaaaaaaa\n"
2563      "        : aaaaaaaaaaaaaaa);\n"
2564      "}",
2565      NoBinPacking);
2566}
2567
2568TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
2569  verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
2570               "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
2571  verifyFormat("bool a = true, b = false;");
2572
2573  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
2574               "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
2575               "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
2576               "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
2577  verifyFormat(
2578      "bool aaaaaaaaaaaaaaaaaaaaa =\n"
2579      "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
2580      "     d = e && f;");
2581  verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
2582               "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
2583  verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
2584               "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
2585  verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
2586               "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
2587  // FIXME: If multiple variables are defined, the "*" needs to move to the new
2588  // line. Also fix indent for breaking after the type, this looks bad.
2589  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2590               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
2591               "   *b = bbbbbbbbbbbbbbbbbbb;");
2592
2593  // Not ideal, but pointer-with-type does not allow much here.
2594  verifyGoogleFormat(
2595      "aaaaaaaaa* a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
2596      "           *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;");
2597}
2598
2599TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
2600  verifyFormat("arr[foo ? bar : baz];");
2601  verifyFormat("f()[foo ? bar : baz];");
2602  verifyFormat("(a + b)[foo ? bar : baz];");
2603  verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
2604}
2605
2606TEST_F(FormatTest, AlignsStringLiterals) {
2607  verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
2608               "                                      \"short literal\");");
2609  verifyFormat(
2610      "looooooooooooooooooooooooongFunction(\n"
2611      "    \"short literal\"\n"
2612      "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
2613  verifyFormat("someFunction(\"Always break between multi-line\"\n"
2614               "             \" string literals\",\n"
2615               "             and, other, parameters);");
2616  EXPECT_EQ("fun + \"1243\" /* comment */\n"
2617            "      \"5678\";",
2618            format("fun + \"1243\" /* comment */\n"
2619                   "      \"5678\";",
2620                   getLLVMStyleWithColumns(28)));
2621  EXPECT_EQ(
2622      "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
2623      "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
2624      "         \"aaaaaaaaaaaaaaaa\";",
2625      format("aaaaaa ="
2626             "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
2627             "aaaaaaaaaaaaaaaaaaaaa\" "
2628             "\"aaaaaaaaaaaaaaaa\";"));
2629  verifyFormat("a = a + \"a\"\n"
2630               "        \"a\"\n"
2631               "        \"a\";");
2632  verifyFormat("f(\"a\", \"b\"\n"
2633               "       \"c\");");
2634
2635  verifyFormat(
2636      "#define LL_FORMAT \"ll\"\n"
2637      "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
2638      "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
2639
2640  verifyFormat("#define A(X)          \\\n"
2641               "  \"aaaaa\" #X \"bbbbbb\" \\\n"
2642               "  \"ccccc\"",
2643               getLLVMStyleWithColumns(23));
2644  verifyFormat("#define A \"def\"\n"
2645               "f(\"abc\" A \"ghi\"\n"
2646               "  \"jkl\");");
2647}
2648
2649TEST_F(FormatTest, AlignsPipes) {
2650  verifyFormat(
2651      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2652      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2653      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2654  verifyFormat(
2655      "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
2656      "                     << aaaaaaaaaaaaaaaaaaaa;");
2657  verifyFormat(
2658      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2659      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2660  verifyFormat(
2661      "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
2662      "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
2663      "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
2664  verifyFormat(
2665      "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2666      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2667      "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2668
2669  verifyFormat("return out << \"somepacket = {\\n\"\n"
2670               "           << \"  aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
2671               "           << \"  bbbb = \" << pkt.bbbb << \"\\n\"\n"
2672               "           << \"  cccccc = \" << pkt.cccccc << \"\\n\"\n"
2673               "           << \"  ddd = [\" << pkt.ddd << \"]\\n\"\n"
2674               "           << \"}\";");
2675
2676  verifyFormat(
2677      "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
2678      "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
2679      "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
2680      "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
2681      "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
2682  verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
2683               "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
2684  verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaa: \"\n"
2685               "             << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2686
2687  verifyFormat(
2688      "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2689      "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
2690}
2691
2692TEST_F(FormatTest, UnderstandsEquals) {
2693  verifyFormat(
2694      "aaaaaaaaaaaaaaaaa =\n"
2695      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2696  verifyFormat(
2697      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
2698      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2699  verifyFormat(
2700      "if (a) {\n"
2701      "  f();\n"
2702      "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
2703      "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2704      "}");
2705
2706  verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
2707               "        100000000 + 10000000) {\n}");
2708}
2709
2710TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
2711  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
2712               "    .looooooooooooooooooooooooooooooooooooooongFunction();");
2713
2714  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
2715               "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
2716
2717  verifyFormat(
2718      "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
2719      "                                                          Parameter2);");
2720
2721  verifyFormat(
2722      "ShortObject->shortFunction(\n"
2723      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
2724      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
2725
2726  verifyFormat("loooooooooooooongFunction(\n"
2727               "    LoooooooooooooongObject->looooooooooooooooongFunction());");
2728
2729  verifyFormat(
2730      "function(LoooooooooooooooooooooooooooooooooooongObject\n"
2731      "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
2732
2733  verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
2734               "    .WillRepeatedly(Return(SomeValue));");
2735  verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)]\n"
2736               "    .insert(ccccccccccccccccccccccc);");
2737  verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2738               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).aaaaa(aaaaa),\n"
2739               "      aaaaaaaaaaaaaaaaaaaaa);");
2740  verifyFormat(
2741      "aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2742      "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2743      "    .aaaaaaaaaaaaaaa(\n"
2744      "         aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2745      "            aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2746  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2747               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2748               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2749               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
2750               "}");
2751
2752  // Here, it is not necessary to wrap at "." or "->".
2753  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
2754               "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2755  verifyFormat(
2756      "aaaaaaaaaaa->aaaaaaaaa(\n"
2757      "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2758      "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
2759
2760  verifyFormat(
2761      "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2762      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
2763  verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
2764               "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
2765  verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
2766               "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
2767
2768  // FIXME: Should we break before .a()?
2769  verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2770               "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).a();");
2771
2772  FormatStyle NoBinPacking = getLLVMStyle();
2773  NoBinPacking.BinPackParameters = false;
2774  verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
2775               "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
2776               "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
2777               "                         aaaaaaaaaaaaaaaaaaa,\n"
2778               "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
2779               NoBinPacking);
2780}
2781
2782TEST_F(FormatTest, WrapsTemplateDeclarations) {
2783  verifyFormat("template <typename T>\n"
2784               "virtual void loooooooooooongFunction(int Param1, int Param2);");
2785  verifyFormat(
2786      "template <typename T>\n"
2787      "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
2788  verifyFormat("template <typename T>\n"
2789               "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
2790               "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
2791  verifyFormat(
2792      "template <typename T>\n"
2793      "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
2794      "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
2795  verifyFormat(
2796      "template <typename T>\n"
2797      "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
2798      "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
2799      "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2800  verifyFormat("template <typename T>\n"
2801               "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2802               "    int aaaaaaaaaaaaaaaaaaaaaa);");
2803  verifyFormat(
2804      "template <typename T1, typename T2 = char, typename T3 = char,\n"
2805      "          typename T4 = char>\n"
2806      "void f();");
2807  verifyFormat(
2808      "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
2809      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2810
2811  verifyFormat("a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
2812               "    a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));");
2813
2814  verifyFormat("template <typename T> class C {\n};");
2815  verifyFormat("template <typename T> void f();");
2816  verifyFormat("template <typename T> void f() {}");
2817
2818  FormatStyle AlwaysBreak = getLLVMStyle();
2819  AlwaysBreak.AlwaysBreakTemplateDeclarations = true;
2820  verifyFormat("template <typename T>\nclass C {\n};", AlwaysBreak);
2821  verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
2822  verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
2823}
2824
2825TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
2826  verifyFormat(
2827      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
2828      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
2829  verifyFormat(
2830      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
2831      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2832      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
2833
2834  // FIXME: Should we have the extra indent after the second break?
2835  verifyFormat(
2836      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
2837      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
2838      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
2839
2840  verifyFormat(
2841      "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
2842      "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
2843
2844  // Breaking at nested name specifiers is generally not desirable.
2845  verifyFormat(
2846      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2847      "    aaaaaaaaaaaaaaaaaaaaaaa);");
2848
2849  verifyFormat(
2850      "aaaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
2851      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2852      "                   aaaaaaaaaaaaaaaaaaaaa);",
2853      getLLVMStyleWithColumns(74));
2854
2855  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
2856               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2857               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
2858}
2859
2860TEST_F(FormatTest, UnderstandsTemplateParameters) {
2861  verifyFormat("A<int> a;");
2862  verifyFormat("A<A<A<int> > > a;");
2863  verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
2864  verifyFormat("bool x = a < 1 || 2 > a;");
2865  verifyFormat("bool x = 5 < f<int>();");
2866  verifyFormat("bool x = f<int>() > 5;");
2867  verifyFormat("bool x = 5 < a<int>::x;");
2868  verifyFormat("bool x = a < 4 ? a > 2 : false;");
2869  verifyFormat("bool x = f() ? a < 2 : a > 2;");
2870
2871  verifyGoogleFormat("A<A<int>> a;");
2872  verifyGoogleFormat("A<A<A<int>>> a;");
2873  verifyGoogleFormat("A<A<A<A<int>>>> a;");
2874  verifyGoogleFormat("A<A<int> > a;");
2875  verifyGoogleFormat("A<A<A<int> > > a;");
2876  verifyGoogleFormat("A<A<A<A<int> > > > a;");
2877  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
2878  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
2879
2880  verifyFormat("test >> a >> b;");
2881  verifyFormat("test << a >> b;");
2882
2883  verifyFormat("f<int>();");
2884  verifyFormat("template <typename T> void f() {}");
2885}
2886
2887TEST_F(FormatTest, UnderstandsBinaryOperators) {
2888  verifyFormat("COMPARE(a, ==, b);");
2889}
2890
2891TEST_F(FormatTest, UnderstandsPointersToMembers) {
2892  verifyFormat("int A::*x;");
2893  verifyFormat("int (S::*func)(void *);");
2894  verifyFormat("void f() { int (S::*func)(void *); }");
2895  verifyFormat("typedef bool *(Class::*Member)() const;");
2896  verifyFormat("void f() {\n"
2897               "  (a->*f)();\n"
2898               "  a->*x;\n"
2899               "  (a.*f)();\n"
2900               "  ((*a).*f)();\n"
2901               "  a.*x;\n"
2902               "}");
2903  FormatStyle Style = getLLVMStyle();
2904  Style.PointerBindsToType = true;
2905  verifyFormat("typedef bool* (Class::*Member)() const;", Style);
2906}
2907
2908TEST_F(FormatTest, UnderstandsUnaryOperators) {
2909  verifyFormat("int a = -2;");
2910  verifyFormat("f(-1, -2, -3);");
2911  verifyFormat("a[-1] = 5;");
2912  verifyFormat("int a = 5 + -2;");
2913  verifyFormat("if (i == -1) {\n}");
2914  verifyFormat("if (i != -1) {\n}");
2915  verifyFormat("if (i > -1) {\n}");
2916  verifyFormat("if (i < -1) {\n}");
2917  verifyFormat("++(a->f());");
2918  verifyFormat("--(a->f());");
2919  verifyFormat("(a->f())++;");
2920  verifyFormat("a[42]++;");
2921  verifyFormat("if (!(a->f())) {\n}");
2922
2923  verifyFormat("a-- > b;");
2924  verifyFormat("b ? -a : c;");
2925  verifyFormat("n * sizeof char16;");
2926  verifyFormat("n * alignof char16;");
2927  verifyFormat("sizeof(char);");
2928  verifyFormat("alignof(char);");
2929
2930  verifyFormat("return -1;");
2931  verifyFormat("switch (a) {\n"
2932               "case -1:\n"
2933               "  break;\n"
2934               "}");
2935  verifyFormat("#define X -1");
2936  verifyFormat("#define X -kConstant");
2937
2938  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { -5, +3 };");
2939  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { +5, -3 };");
2940
2941  verifyFormat("int a = /* confusing comment */ -1;");
2942  // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
2943  verifyFormat("int a = i /* confusing comment */++;");
2944}
2945
2946TEST_F(FormatTest, UndestandsOverloadedOperators) {
2947  verifyFormat("bool operator<();");
2948  verifyFormat("bool operator>();");
2949  verifyFormat("bool operator=();");
2950  verifyFormat("bool operator==();");
2951  verifyFormat("bool operator!=();");
2952  verifyFormat("int operator+();");
2953  verifyFormat("int operator++();");
2954  verifyFormat("bool operator();");
2955  verifyFormat("bool operator()();");
2956  verifyFormat("bool operator[]();");
2957  verifyFormat("operator bool();");
2958  verifyFormat("operator int();");
2959  verifyFormat("operator void *();");
2960  verifyFormat("operator SomeType<int>();");
2961  verifyFormat("operator SomeType<int, int>();");
2962  verifyFormat("operator SomeType<SomeType<int> >();");
2963  verifyFormat("void *operator new(std::size_t size);");
2964  verifyFormat("void *operator new[](std::size_t size);");
2965  verifyFormat("void operator delete(void *ptr);");
2966  verifyFormat("void operator delete[](void *ptr);");
2967  verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
2968               "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
2969
2970  verifyFormat(
2971      "ostream &operator<<(ostream &OutputStream,\n"
2972      "                    SomeReallyLongType WithSomeReallyLongValue);");
2973  verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
2974               "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
2975               "  return left.group < right.group;\n"
2976               "}");
2977  verifyFormat("SomeType &operator=(const SomeType &S);");
2978
2979  verifyGoogleFormat("operator void*();");
2980  verifyGoogleFormat("operator SomeType<SomeType<int>>();");
2981}
2982
2983TEST_F(FormatTest, UnderstandsNewAndDelete) {
2984  verifyFormat("void f() {\n"
2985               "  A *a = new A;\n"
2986               "  A *a = new (placement) A;\n"
2987               "  delete a;\n"
2988               "  delete (A *)a;\n"
2989               "}");
2990}
2991
2992TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
2993  verifyFormat("int *f(int *a) {}");
2994  verifyFormat("int main(int argc, char **argv) {}");
2995  verifyFormat("Test::Test(int b) : a(b * b) {}");
2996  verifyIndependentOfContext("f(a, *a);");
2997  verifyFormat("void g() { f(*a); }");
2998  verifyIndependentOfContext("int a = b * 10;");
2999  verifyIndependentOfContext("int a = 10 * b;");
3000  verifyIndependentOfContext("int a = b * c;");
3001  verifyIndependentOfContext("int a += b * c;");
3002  verifyIndependentOfContext("int a -= b * c;");
3003  verifyIndependentOfContext("int a *= b * c;");
3004  verifyIndependentOfContext("int a /= b * c;");
3005  verifyIndependentOfContext("int a = *b;");
3006  verifyIndependentOfContext("int a = *b * c;");
3007  verifyIndependentOfContext("int a = b * *c;");
3008  verifyIndependentOfContext("return 10 * b;");
3009  verifyIndependentOfContext("return *b * *c;");
3010  verifyIndependentOfContext("return a & ~b;");
3011  verifyIndependentOfContext("f(b ? *c : *d);");
3012  verifyIndependentOfContext("int a = b ? *c : *d;");
3013  verifyIndependentOfContext("*b = a;");
3014  verifyIndependentOfContext("a * ~b;");
3015  verifyIndependentOfContext("a * !b;");
3016  verifyIndependentOfContext("a * +b;");
3017  verifyIndependentOfContext("a * -b;");
3018  verifyIndependentOfContext("a * ++b;");
3019  verifyIndependentOfContext("a * --b;");
3020  verifyIndependentOfContext("a[4] * b;");
3021  verifyIndependentOfContext("a[a * a] = 1;");
3022  verifyIndependentOfContext("f() * b;");
3023  verifyIndependentOfContext("a * [self dostuff];");
3024  verifyIndependentOfContext("int x = a * (a + b);");
3025  verifyIndependentOfContext("(a *)(a + b);");
3026  verifyIndependentOfContext("int *pa = (int *)&a;");
3027  verifyIndependentOfContext("return sizeof(int **);");
3028  verifyIndependentOfContext("return sizeof(int ******);");
3029  verifyIndependentOfContext("return (int **&)a;");
3030  verifyIndependentOfContext("f((*PointerToArray)[10]);");
3031  verifyFormat("void f(Type (*parameter)[10]) {}");
3032  verifyGoogleFormat("return sizeof(int**);");
3033  verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
3034  verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
3035  verifyFormat("auto a = [](int **&, int ***) {};");
3036
3037  verifyIndependentOfContext("InvalidRegions[*R] = 0;");
3038
3039  verifyIndependentOfContext("A<int *> a;");
3040  verifyIndependentOfContext("A<int **> a;");
3041  verifyIndependentOfContext("A<int *, int *> a;");
3042  verifyIndependentOfContext(
3043      "const char *const p = reinterpret_cast<const char *const>(q);");
3044  verifyIndependentOfContext("A<int **, int **> a;");
3045  verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
3046  verifyFormat("for (char **a = b; *a; ++a) {\n}");
3047  verifyFormat("for (; a && b;) {\n}");
3048
3049  verifyFormat(
3050      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3051      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3052
3053  verifyGoogleFormat("int main(int argc, char** argv) {}");
3054  verifyGoogleFormat("A<int*> a;");
3055  verifyGoogleFormat("A<int**> a;");
3056  verifyGoogleFormat("A<int*, int*> a;");
3057  verifyGoogleFormat("A<int**, int**> a;");
3058  verifyGoogleFormat("f(b ? *c : *d);");
3059  verifyGoogleFormat("int a = b ? *c : *d;");
3060  verifyGoogleFormat("Type* t = **x;");
3061  verifyGoogleFormat("Type* t = *++*x;");
3062  verifyGoogleFormat("*++*x;");
3063  verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
3064  verifyGoogleFormat("Type* t = x++ * y;");
3065  verifyGoogleFormat(
3066      "const char* const p = reinterpret_cast<const char* const>(q);");
3067
3068  verifyIndependentOfContext("a = *(x + y);");
3069  verifyIndependentOfContext("a = &(x + y);");
3070  verifyIndependentOfContext("*(x + y).call();");
3071  verifyIndependentOfContext("&(x + y)->call();");
3072  verifyFormat("void f() { &(*I).first; }");
3073
3074  verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
3075  verifyFormat(
3076      "int *MyValues = {\n"
3077      "  *A, // Operator detection might be confused by the '{'\n"
3078      "  *BB // Operator detection might be confused by previous comment\n"
3079      "};");
3080
3081  verifyIndependentOfContext("if (int *a = &b)");
3082  verifyIndependentOfContext("if (int &a = *b)");
3083  verifyIndependentOfContext("if (a & b[i])");
3084  verifyIndependentOfContext("if (a::b::c::d & b[i])");
3085  verifyIndependentOfContext("if (*b[i])");
3086  verifyIndependentOfContext("if (int *a = (&b))");
3087  verifyIndependentOfContext("while (int *a = &b)");
3088  verifyFormat("void f() {\n"
3089               "  for (const int &v : Values) {\n"
3090               "  }\n"
3091               "}");
3092  verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
3093  verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
3094
3095  verifyFormat("#define MACRO     \\\n"
3096               "  int *i = a * b; \\\n"
3097               "  void f(a *b);",
3098               getLLVMStyleWithColumns(19));
3099
3100  verifyIndependentOfContext("A = new SomeType *[Length];");
3101  verifyIndependentOfContext("A = new SomeType *[Length]();");
3102  verifyGoogleFormat("A = new SomeType* [Length]();");
3103  verifyGoogleFormat("A = new SomeType* [Length];");
3104
3105  FormatStyle PointerLeft = getLLVMStyle();
3106  PointerLeft.PointerBindsToType = true;
3107  verifyFormat("delete *x;", PointerLeft);
3108}
3109
3110TEST_F(FormatTest, UnderstandsEllipsis) {
3111  verifyFormat("int printf(const char *fmt, ...);");
3112  verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
3113}
3114
3115TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
3116  EXPECT_EQ("int *a;\n"
3117            "int *a;\n"
3118            "int *a;",
3119            format("int *a;\n"
3120                   "int* a;\n"
3121                   "int *a;",
3122                   getGoogleStyle()));
3123  EXPECT_EQ("int* a;\n"
3124            "int* a;\n"
3125            "int* a;",
3126            format("int* a;\n"
3127                   "int* a;\n"
3128                   "int *a;",
3129                   getGoogleStyle()));
3130  EXPECT_EQ("int *a;\n"
3131            "int *a;\n"
3132            "int *a;",
3133            format("int *a;\n"
3134                   "int * a;\n"
3135                   "int *  a;",
3136                   getGoogleStyle()));
3137}
3138
3139TEST_F(FormatTest, UnderstandsRvalueReferences) {
3140  verifyFormat("int f(int &&a) {}");
3141  verifyFormat("int f(int a, char &&b) {}");
3142  verifyFormat("void f() { int &&a = b; }");
3143  verifyGoogleFormat("int f(int a, char&& b) {}");
3144  verifyGoogleFormat("void f() { int&& a = b; }");
3145
3146  verifyIndependentOfContext("A<int &&> a;");
3147  verifyIndependentOfContext("A<int &&, int &&> a;");
3148  verifyGoogleFormat("A<int&&> a;");
3149  verifyGoogleFormat("A<int&&, int&&> a;");
3150}
3151
3152TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
3153  verifyFormat("void f() {\n"
3154               "  x[aaaaaaaaa -\n"
3155               "    b] = 23;\n"
3156               "}",
3157               getLLVMStyleWithColumns(15));
3158}
3159
3160TEST_F(FormatTest, FormatsCasts) {
3161  verifyFormat("Type *A = static_cast<Type *>(P);");
3162  verifyFormat("Type *A = (Type *)P;");
3163  verifyFormat("Type *A = (vector<Type *, int *>)P;");
3164  verifyFormat("int a = (int)(2.0f);");
3165
3166  // FIXME: These also need to be identified.
3167  verifyFormat("int a = (int) 2.0f;");
3168  verifyFormat("int a = (int) * b;");
3169
3170  // These are not casts.
3171  verifyFormat("void f(int *) {}");
3172  verifyFormat("f(foo)->b;");
3173  verifyFormat("f(foo).b;");
3174  verifyFormat("f(foo)(b);");
3175  verifyFormat("f(foo)[b];");
3176  verifyFormat("[](foo) { return 4; }(bar)];");
3177  verifyFormat("(*funptr)(foo)[4];");
3178  verifyFormat("funptrs[4](foo)[4];");
3179  verifyFormat("void f(int *);");
3180  verifyFormat("void f(int *) = 0;");
3181  verifyFormat("void f(SmallVector<int>) {}");
3182  verifyFormat("void f(SmallVector<int>);");
3183  verifyFormat("void f(SmallVector<int>) = 0;");
3184  verifyFormat("void f(int i = (kValue) * kMask) {}");
3185  verifyFormat("void f(int i = (kA * kB) & kMask) {}");
3186  verifyFormat("int a = sizeof(int) * b;");
3187  verifyFormat("int a = alignof(int) * b;");
3188
3189  // These are not casts, but at some point were confused with casts.
3190  verifyFormat("virtual void foo(int *) override;");
3191  verifyFormat("virtual void foo(char &) const;");
3192  verifyFormat("virtual void foo(int *a, char *) const;");
3193  verifyFormat("int a = sizeof(int *) + b;");
3194  verifyFormat("int a = alignof(int *) + b;");
3195}
3196
3197TEST_F(FormatTest, FormatsFunctionTypes) {
3198  verifyFormat("A<bool()> a;");
3199  verifyFormat("A<SomeType()> a;");
3200  verifyFormat("A<void (*)(int, std::string)> a;");
3201  verifyFormat("A<void *(int)>;");
3202  verifyFormat("void *(*a)(int *, SomeType *);");
3203  verifyFormat("int (*func)(void *);");
3204  verifyFormat("void f() { int (*func)(void *); }");
3205
3206  verifyGoogleFormat("A<void*(int*, SomeType*)>;");
3207  verifyGoogleFormat("void* (*a)(int);");
3208
3209  // Other constructs can look somewhat like function types:
3210  verifyFormat("A<sizeof(*x)> a;");
3211  verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
3212}
3213
3214TEST_F(FormatTest, BreaksLongDeclarations) {
3215  verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
3216               "    AnotherNameForTheLongType;");
3217  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
3218               "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
3219  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
3220               "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
3221  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
3222               "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
3223
3224  // FIXME: Without the comment, this breaks after "(".
3225  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType // break\n"
3226               "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();");
3227
3228  verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
3229               "                  int LoooooooooooooooooooongParam2) {}");
3230  verifyFormat(
3231      "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
3232      "                                   SourceLocation L, IdentifierIn *II,\n"
3233      "                                   Type *T) {}");
3234  verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
3235               "ReallyReallyLongFunctionName(\n"
3236               "    const std::string &SomeParameter,\n"
3237               "    const SomeType<string, SomeOtherTemplateParameter> &\n"
3238               "        ReallyReallyLongParameterName,\n"
3239               "    const SomeType<string, SomeOtherTemplateParameter> &\n"
3240               "        AnotherLongParameterName) {}");
3241  verifyFormat("template <typename A>\n"
3242               "SomeLoooooooooooooooooooooongType<\n"
3243               "    typename some_namespace::SomeOtherType<A>::Type>\n"
3244               "Function() {}");
3245  verifyFormat(
3246      "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
3247      "    aaaaaaaaaaaaaaaaaaaaaaa;");
3248
3249  verifyGoogleFormat(
3250      "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
3251      "                                   SourceLocation L) {}");
3252  verifyGoogleFormat(
3253      "some_namespace::LongReturnType\n"
3254      "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
3255      "    int first_long_parameter, int second_parameter) {}");
3256
3257  verifyGoogleFormat("template <typename T>\n"
3258                     "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
3259                     "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
3260  verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3261                     "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
3262}
3263
3264TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
3265  verifyFormat("(a)->b();");
3266  verifyFormat("--a;");
3267}
3268
3269TEST_F(FormatTest, HandlesIncludeDirectives) {
3270  verifyFormat("#include <string>\n"
3271               "#include <a/b/c.h>\n"
3272               "#include \"a/b/string\"\n"
3273               "#include \"string.h\"\n"
3274               "#include \"string.h\"\n"
3275               "#include <a-a>\n"
3276               "#include < path with space >\n"
3277               "#include \"abc.h\" // this is included for ABC\n"
3278               "#include \"some long include\" // with a comment\n"
3279               "#include \"some very long include paaaaaaaaaaaaaaaaaaaaaaath\"",
3280               getLLVMStyleWithColumns(35));
3281
3282  verifyFormat("#import <string>");
3283  verifyFormat("#import <a/b/c.h>");
3284  verifyFormat("#import \"a/b/string\"");
3285  verifyFormat("#import \"string.h\"");
3286  verifyFormat("#import \"string.h\"");
3287}
3288
3289//===----------------------------------------------------------------------===//
3290// Error recovery tests.
3291//===----------------------------------------------------------------------===//
3292
3293TEST_F(FormatTest, IncompleteParameterLists) {
3294  FormatStyle NoBinPacking = getLLVMStyle();
3295  NoBinPacking.BinPackParameters = false;
3296  verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
3297               "                        double *min_x,\n"
3298               "                        double *max_x,\n"
3299               "                        double *min_y,\n"
3300               "                        double *max_y,\n"
3301               "                        double *min_z,\n"
3302               "                        double *max_z, ) {}",
3303               NoBinPacking);
3304}
3305
3306TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
3307  verifyFormat("void f() { return; }\n42");
3308  verifyFormat("void f() {\n"
3309               "  if (0)\n"
3310               "    return;\n"
3311               "}\n"
3312               "42");
3313  verifyFormat("void f() { return }\n42");
3314  verifyFormat("void f() {\n"
3315               "  if (0)\n"
3316               "    return\n"
3317               "}\n"
3318               "42");
3319}
3320
3321TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
3322  EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
3323  EXPECT_EQ("void f() {\n"
3324            "  if (a)\n"
3325            "    return\n"
3326            "}",
3327            format("void  f  (  )  {  if  ( a )  return  }"));
3328  EXPECT_EQ("namespace N {\n"
3329            "void f()\n"
3330            "}",
3331            format("namespace  N  {  void f()  }"));
3332  EXPECT_EQ("namespace N {\n"
3333            "void f() {}\n"
3334            "void g()\n"
3335            "}",
3336            format("namespace N  { void f( ) { } void g( ) }"));
3337}
3338
3339TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
3340  verifyFormat("int aaaaaaaa =\n"
3341               "    // Overlylongcomment\n"
3342               "    b;",
3343               getLLVMStyleWithColumns(20));
3344  verifyFormat("function(\n"
3345               "    ShortArgument,\n"
3346               "    LoooooooooooongArgument);\n",
3347               getLLVMStyleWithColumns(20));
3348}
3349
3350TEST_F(FormatTest, IncorrectAccessSpecifier) {
3351  verifyFormat("public:");
3352  verifyFormat("class A {\n"
3353               "public\n"
3354               "  void f() {}\n"
3355               "};");
3356  verifyFormat("public\n"
3357               "int qwerty;");
3358  verifyFormat("public\n"
3359               "B {}");
3360  verifyFormat("public\n"
3361               "{}");
3362  verifyFormat("public\n"
3363               "B { int x; }");
3364}
3365
3366TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
3367  verifyFormat("{");
3368  verifyFormat("#})");
3369}
3370
3371TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
3372  verifyFormat("do {\n}");
3373  verifyFormat("do {\n}\n"
3374               "f();");
3375  verifyFormat("do {\n}\n"
3376               "wheeee(fun);");
3377  verifyFormat("do {\n"
3378               "  f();\n"
3379               "}");
3380}
3381
3382TEST_F(FormatTest, IncorrectCodeMissingParens) {
3383  verifyFormat("if {\n  foo;\n  foo();\n}");
3384  verifyFormat("switch {\n  foo;\n  foo();\n}");
3385  verifyFormat("for {\n  foo;\n  foo();\n}");
3386  verifyFormat("while {\n  foo;\n  foo();\n}");
3387  verifyFormat("do {\n  foo;\n  foo();\n} while;");
3388}
3389
3390TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
3391  verifyFormat("namespace {\n"
3392               "class Foo {  Foo  ( }; }  // comment");
3393}
3394
3395TEST_F(FormatTest, IncorrectCodeErrorDetection) {
3396  EXPECT_EQ("{\n{}\n", format("{\n{\n}\n"));
3397  EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
3398  EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
3399  EXPECT_EQ("{\n  {}\n  }\n}\n", format("{\n  {\n    }\n  }\n}\n"));
3400
3401  EXPECT_EQ("{\n"
3402            "    {\n"
3403            " breakme(\n"
3404            "     qwe);\n"
3405            "}\n",
3406            format("{\n"
3407                   "    {\n"
3408                   " breakme(qwe);\n"
3409                   "}\n",
3410                   getLLVMStyleWithColumns(10)));
3411}
3412
3413TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
3414  verifyFormat("int x = {\n"
3415               "  avariable,\n"
3416               "  b(alongervariable)\n"
3417               "};",
3418               getLLVMStyleWithColumns(25));
3419}
3420
3421TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
3422  verifyFormat("return (a)(b) { 1, 2, 3 };");
3423}
3424
3425TEST_F(FormatTest, LayoutCxx11ConstructorBraceInitializers) {
3426    verifyFormat("vector<int> x{ 1, 2, 3, 4 };");
3427    verifyFormat("vector<T> x{ {}, {}, {}, {} };");
3428    verifyFormat("f({ 1, 2 });");
3429    verifyFormat("auto v = Foo{ 1 };");
3430    verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });");
3431    verifyFormat("Class::Class : member{ 1, 2, 3 } {}");
3432    verifyFormat("new vector<int>{ 1, 2, 3 };");
3433    verifyFormat("new int[3]{ 1, 2, 3 };");
3434    verifyFormat("return { arg1, arg2 };");
3435    verifyFormat("return { arg1, SomeType{ parameter } };");
3436    verifyFormat("new T{ arg1, arg2 };");
3437    verifyFormat("class Class {\n"
3438                 "  T member = { arg1, arg2 };\n"
3439                 "};");
3440
3441    FormatStyle NoSpaces = getLLVMStyle();
3442    NoSpaces.SpacesInBracedLists = false;
3443    verifyFormat("vector<int> x{1, 2, 3, 4};", NoSpaces);
3444    verifyFormat("vector<T> x{{}, {}, {}, {}};", NoSpaces);
3445    verifyFormat("f({1, 2});", NoSpaces);
3446    verifyFormat("auto v = Foo{-1};", NoSpaces);
3447    verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});", NoSpaces);
3448    verifyFormat("Class::Class : member{1, 2, 3} {}", NoSpaces);
3449    verifyFormat("new vector<int>{1, 2, 3};", NoSpaces);
3450    verifyFormat("new int[3]{1, 2, 3};", NoSpaces);
3451    verifyFormat("return {arg1, arg2};", NoSpaces);
3452    verifyFormat("return {arg1, SomeType{parameter}};", NoSpaces);
3453    verifyFormat("new T{arg1, arg2};", NoSpaces);
3454    verifyFormat("class Class {\n"
3455                 "  T member = {arg1, arg2};\n"
3456                 "};",
3457                 NoSpaces);
3458}
3459
3460TEST_F(FormatTest, LayoutTokensFollowingBlockInParentheses) {
3461  // FIXME: This is bad, find a better and more generic solution.
3462  verifyFormat(
3463      "Aaa({\n"
3464      "  int i;\n"
3465      "},\n"
3466      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
3467      "                                     ccccccccccccccccc));");
3468}
3469
3470TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
3471  verifyFormat("void f() { return 42; }");
3472  verifyFormat("void f() {\n"
3473               "  // Comment\n"
3474               "}");
3475  verifyFormat("{\n"
3476               "#error {\n"
3477               "  int a;\n"
3478               "}");
3479  verifyFormat("{\n"
3480               "  int a;\n"
3481               "#error {\n"
3482               "}");
3483  verifyFormat("void f() {} // comment");
3484  verifyFormat("void f() { int a; } // comment");
3485  verifyFormat("void f() {\n"
3486               "} // comment",
3487               getLLVMStyleWithColumns(15));
3488
3489  verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
3490  verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
3491
3492  verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
3493  verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
3494}
3495
3496TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
3497  // Elaborate type variable declarations.
3498  verifyFormat("struct foo a = { bar };\nint n;");
3499  verifyFormat("class foo a = { bar };\nint n;");
3500  verifyFormat("union foo a = { bar };\nint n;");
3501
3502  // Elaborate types inside function definitions.
3503  verifyFormat("struct foo f() {}\nint n;");
3504  verifyFormat("class foo f() {}\nint n;");
3505  verifyFormat("union foo f() {}\nint n;");
3506
3507  // Templates.
3508  verifyFormat("template <class X> void f() {}\nint n;");
3509  verifyFormat("template <struct X> void f() {}\nint n;");
3510  verifyFormat("template <union X> void f() {}\nint n;");
3511
3512  // Actual definitions...
3513  verifyFormat("struct {\n} n;");
3514  verifyFormat(
3515      "template <template <class T, class Y>, class Z> class X {\n} n;");
3516  verifyFormat("union Z {\n  int n;\n} x;");
3517  verifyFormat("class MACRO Z {\n} n;");
3518  verifyFormat("class MACRO(X) Z {\n} n;");
3519  verifyFormat("class __attribute__(X) Z {\n} n;");
3520  verifyFormat("class __declspec(X) Z {\n} n;");
3521  verifyFormat("class A##B##C {\n} n;");
3522
3523  // Redefinition from nested context:
3524  verifyFormat("class A::B::C {\n} n;");
3525
3526  // Template definitions.
3527  verifyFormat(
3528      "template <typename F>\n"
3529      "Matcher(const Matcher<F> &Other,\n"
3530      "        typename enable_if_c<is_base_of<F, T>::value &&\n"
3531      "                             !is_same<F, T>::value>::type * = 0)\n"
3532      "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
3533
3534  // FIXME: This is still incorrectly handled at the formatter side.
3535  verifyFormat("template <> struct X < 15, i < 3 && 42 < 50 && 33<28> {\n};");
3536
3537  // FIXME:
3538  // This now gets parsed incorrectly as class definition.
3539  // verifyFormat("class A<int> f() {\n}\nint n;");
3540
3541  // Elaborate types where incorrectly parsing the structural element would
3542  // break the indent.
3543  verifyFormat("if (true)\n"
3544               "  class X x;\n"
3545               "else\n"
3546               "  f();\n");
3547
3548  // This is simply incomplete. Formatting is not important, but must not crash.
3549  verifyFormat("class A:");
3550}
3551
3552TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
3553  verifyFormat("#error Leave     all         white!!!!! space* alone!\n");
3554  verifyFormat("#warning Leave     all         white!!!!! space* alone!\n");
3555  EXPECT_EQ("#error 1", format("  #  error   1"));
3556  EXPECT_EQ("#warning 1", format("  #  warning 1"));
3557}
3558
3559TEST_F(FormatTest, FormatHashIfExpressions) {
3560  // FIXME: Come up with a better indentation for #elif.
3561  verifyFormat(
3562      "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
3563      "    defined(BBBBBBBB)\n"
3564      "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
3565      "    defined(BBBBBBBB)\n"
3566      "#endif",
3567      getLLVMStyleWithColumns(65));
3568}
3569
3570TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
3571  FormatStyle AllowsMergedIf = getGoogleStyle();
3572  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
3573  verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
3574  verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
3575  verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
3576  EXPECT_EQ("if (true) return 42;",
3577            format("if (true)\nreturn 42;", AllowsMergedIf));
3578  FormatStyle ShortMergedIf = AllowsMergedIf;
3579  ShortMergedIf.ColumnLimit = 25;
3580  verifyFormat("#define A \\\n"
3581               "  if (true) return 42;",
3582               ShortMergedIf);
3583  verifyFormat("#define A \\\n"
3584               "  f();    \\\n"
3585               "  if (true)\n"
3586               "#define B",
3587               ShortMergedIf);
3588  verifyFormat("#define A \\\n"
3589               "  f();    \\\n"
3590               "  if (true)\n"
3591               "g();",
3592               ShortMergedIf);
3593  verifyFormat("{\n"
3594               "#ifdef A\n"
3595               "  // Comment\n"
3596               "  if (true) continue;\n"
3597               "#endif\n"
3598               "  // Comment\n"
3599               "  if (true) continue;",
3600               ShortMergedIf);
3601}
3602
3603TEST_F(FormatTest, BlockCommentsInControlLoops) {
3604  verifyFormat("if (0) /* a comment in a strange place */ {\n"
3605               "  f();\n"
3606               "}");
3607  verifyFormat("if (0) /* a comment in a strange place */ {\n"
3608               "  f();\n"
3609               "} /* another comment */ else /* comment #3 */ {\n"
3610               "  g();\n"
3611               "}");
3612  verifyFormat("while (0) /* a comment in a strange place */ {\n"
3613               "  f();\n"
3614               "}");
3615  verifyFormat("for (;;) /* a comment in a strange place */ {\n"
3616               "  f();\n"
3617               "}");
3618  verifyFormat("do /* a comment in a strange place */ {\n"
3619               "  f();\n"
3620               "} /* another comment */ while (0);");
3621}
3622
3623TEST_F(FormatTest, BlockComments) {
3624  EXPECT_EQ("/* */ /* */ /* */\n/* */ /* */ /* */",
3625            format("/* *//* */  /* */\n/* *//* */  /* */"));
3626  EXPECT_EQ("/* */ a /* */ b;", format("  /* */  a/* */  b;"));
3627  EXPECT_EQ("#define A /*123*/\\\n"
3628            "  b\n"
3629            "/* */\n"
3630            "someCall(\n"
3631            "    parameter);",
3632            format("#define A /*123*/ b\n"
3633                   "/* */\n"
3634                   "someCall(parameter);",
3635                   getLLVMStyleWithColumns(15)));
3636
3637  EXPECT_EQ("#define A\n"
3638            "/* */ someCall(\n"
3639            "    parameter);",
3640            format("#define A\n"
3641                   "/* */someCall(parameter);",
3642                   getLLVMStyleWithColumns(15)));
3643
3644  FormatStyle NoBinPacking = getLLVMStyle();
3645  NoBinPacking.BinPackParameters = false;
3646  EXPECT_EQ("someFunction(1, /* comment 1 */\n"
3647            "             2, /* comment 2 */\n"
3648            "             3, /* comment 3 */\n"
3649            "             aaaa,\n"
3650            "             bbbb);",
3651            format("someFunction (1,   /* comment 1 */\n"
3652                   "                2, /* comment 2 */  \n"
3653                   "               3,   /* comment 3 */\n"
3654                   "aaaa, bbbb );",
3655                   NoBinPacking));
3656  verifyFormat(
3657      "bool aaaaaaaaaaaaa = /* comment: */ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3658      "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3659  EXPECT_EQ(
3660      "bool aaaaaaaaaaaaa = /* trailing comment */\n"
3661      "    aaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
3662      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;",
3663      format(
3664          "bool       aaaaaaaaaaaaa =       /* trailing comment */\n"
3665          "    aaaaaaaaaaaaaaaaaaaaaaaaaaa||aaaaaaaaaaaaaaaaaaaaaaaaa    ||\n"
3666          "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa   || aaaaaaaaaaaaaaaaaaaaaaaaaa;"));
3667  EXPECT_EQ(
3668      "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
3669      "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   /* comment */\n"
3670      "int cccccccccccccccccccccccccccccc;       /* comment */\n",
3671      format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
3672             "int      bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n"
3673             "int    cccccccccccccccccccccccccccccc;  /* comment */\n"));
3674}
3675
3676TEST_F(FormatTest, BlockCommentsInMacros) {
3677  EXPECT_EQ("#define A          \\\n"
3678            "  {                \\\n"
3679            "    /* one line */ \\\n"
3680            "    someCall();",
3681            format("#define A {        \\\n"
3682                   "  /* one line */   \\\n"
3683                   "  someCall();",
3684                   getLLVMStyleWithColumns(20)));
3685  EXPECT_EQ("#define A          \\\n"
3686            "  {                \\\n"
3687            "    /* previous */ \\\n"
3688            "    /* one line */ \\\n"
3689            "    someCall();",
3690            format("#define A {        \\\n"
3691                   "  /* previous */   \\\n"
3692                   "  /* one line */   \\\n"
3693                   "  someCall();",
3694                   getLLVMStyleWithColumns(20)));
3695}
3696
3697TEST_F(FormatTest, BlockCommentsAtEndOfLine) {
3698  EXPECT_EQ("a = {\n"
3699            "  1111 /*    */\n"
3700            "};",
3701            format("a = {1111\n"
3702                   "/*    */\n"
3703                   "};",
3704                   getLLVMStyleWithColumns(15)));
3705  EXPECT_EQ("a = {\n"
3706            "  1111 /*      */\n"
3707            "};",
3708            format("a = {1111\n"
3709                   "/*      */\n"
3710                   "};",
3711                   getLLVMStyleWithColumns(15)));
3712
3713  // FIXME: The formatting is still wrong here.
3714  EXPECT_EQ("a = {\n"
3715            "  1111 /*      a\n"
3716            "          */\n"
3717            "};",
3718            format("a = {1111\n"
3719                   "/*      a */\n"
3720                   "};",
3721                   getLLVMStyleWithColumns(15)));
3722}
3723
3724TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
3725  // FIXME: This is not what we want...
3726  verifyFormat("{\n"
3727               "// a"
3728               "// b");
3729}
3730
3731TEST_F(FormatTest, FormatStarDependingOnContext) {
3732  verifyFormat("void f(int *a);");
3733  verifyFormat("void f() { f(fint * b); }");
3734  verifyFormat("class A {\n  void f(int *a);\n};");
3735  verifyFormat("class A {\n  int *a;\n};");
3736  verifyFormat("namespace a {\n"
3737               "namespace b {\n"
3738               "class A {\n"
3739               "  void f() {}\n"
3740               "  int *a;\n"
3741               "};\n"
3742               "}\n"
3743               "}");
3744}
3745
3746TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
3747  verifyFormat("while");
3748  verifyFormat("operator");
3749}
3750
3751//===----------------------------------------------------------------------===//
3752// Objective-C tests.
3753//===----------------------------------------------------------------------===//
3754
3755TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
3756  verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
3757  EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
3758            format("-(NSUInteger)indexOfObject:(id)anObject;"));
3759  EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
3760  EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
3761  EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
3762            format("-(NSInteger)Method3:(id)anObject;"));
3763  EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
3764            format("-(NSInteger)Method4:(id)anObject;"));
3765  EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
3766            format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
3767  EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
3768            format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
3769  EXPECT_EQ(
3770      "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;",
3771      format(
3772          "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;"));
3773
3774  // Very long objectiveC method declaration.
3775  verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
3776               "                    inRange:(NSRange)range\n"
3777               "                   outRange:(NSRange)out_range\n"
3778               "                  outRange1:(NSRange)out_range1\n"
3779               "                  outRange2:(NSRange)out_range2\n"
3780               "                  outRange3:(NSRange)out_range3\n"
3781               "                  outRange4:(NSRange)out_range4\n"
3782               "                  outRange5:(NSRange)out_range5\n"
3783               "                  outRange6:(NSRange)out_range6\n"
3784               "                  outRange7:(NSRange)out_range7\n"
3785               "                  outRange8:(NSRange)out_range8\n"
3786               "                  outRange9:(NSRange)out_range9;");
3787
3788  verifyFormat("- (int)sum:(vector<int>)numbers;");
3789  verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
3790  // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
3791  // protocol lists (but not for template classes):
3792  //verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
3793
3794  verifyFormat("- (int (*)())foo:(int (*)())f;");
3795  verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
3796
3797  // If there's no return type (very rare in practice!), LLVM and Google style
3798  // agree.
3799  verifyFormat("- foo;");
3800  verifyFormat("- foo:(int)f;");
3801  verifyGoogleFormat("- foo:(int)foo;");
3802}
3803
3804TEST_F(FormatTest, FormatObjCBlocks) {
3805  verifyFormat("int (^Block)(int, int);");
3806  verifyFormat("int (^Block1)(int, int) = ^(int i, int j)");
3807}
3808
3809TEST_F(FormatTest, FormatObjCInterface) {
3810  verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
3811               "@public\n"
3812               "  int field1;\n"
3813               "@protected\n"
3814               "  int field2;\n"
3815               "@private\n"
3816               "  int field3;\n"
3817               "@package\n"
3818               "  int field4;\n"
3819               "}\n"
3820               "+ (id)init;\n"
3821               "@end");
3822
3823  verifyGoogleFormat("@interface Foo : NSObject<NSSomeDelegate> {\n"
3824                     " @public\n"
3825                     "  int field1;\n"
3826                     " @protected\n"
3827                     "  int field2;\n"
3828                     " @private\n"
3829                     "  int field3;\n"
3830                     " @package\n"
3831                     "  int field4;\n"
3832                     "}\n"
3833                     "+ (id)init;\n"
3834                     "@end");
3835
3836  verifyFormat("@interface /* wait for it */ Foo\n"
3837               "+ (id)init;\n"
3838               "// Look, a comment!\n"
3839               "- (int)answerWith:(int)i;\n"
3840               "@end");
3841
3842  verifyFormat("@interface Foo\n"
3843               "@end\n"
3844               "@interface Bar\n"
3845               "@end");
3846
3847  verifyFormat("@interface Foo : Bar\n"
3848               "+ (id)init;\n"
3849               "@end");
3850
3851  verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
3852               "+ (id)init;\n"
3853               "@end");
3854
3855  verifyGoogleFormat("@interface Foo : Bar<Baz, Quux>\n"
3856                     "+ (id)init;\n"
3857                     "@end");
3858
3859  verifyFormat("@interface Foo (HackStuff)\n"
3860               "+ (id)init;\n"
3861               "@end");
3862
3863  verifyFormat("@interface Foo ()\n"
3864               "+ (id)init;\n"
3865               "@end");
3866
3867  verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
3868               "+ (id)init;\n"
3869               "@end");
3870
3871  verifyGoogleFormat("@interface Foo (HackStuff)<MyProtocol>\n"
3872                     "+ (id)init;\n"
3873                     "@end");
3874
3875  verifyFormat("@interface Foo {\n"
3876               "  int _i;\n"
3877               "}\n"
3878               "+ (id)init;\n"
3879               "@end");
3880
3881  verifyFormat("@interface Foo : Bar {\n"
3882               "  int _i;\n"
3883               "}\n"
3884               "+ (id)init;\n"
3885               "@end");
3886
3887  verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
3888               "  int _i;\n"
3889               "}\n"
3890               "+ (id)init;\n"
3891               "@end");
3892
3893  verifyFormat("@interface Foo (HackStuff) {\n"
3894               "  int _i;\n"
3895               "}\n"
3896               "+ (id)init;\n"
3897               "@end");
3898
3899  verifyFormat("@interface Foo () {\n"
3900               "  int _i;\n"
3901               "}\n"
3902               "+ (id)init;\n"
3903               "@end");
3904
3905  verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
3906               "  int _i;\n"
3907               "}\n"
3908               "+ (id)init;\n"
3909               "@end");
3910}
3911
3912TEST_F(FormatTest, FormatObjCImplementation) {
3913  verifyFormat("@implementation Foo : NSObject {\n"
3914               "@public\n"
3915               "  int field1;\n"
3916               "@protected\n"
3917               "  int field2;\n"
3918               "@private\n"
3919               "  int field3;\n"
3920               "@package\n"
3921               "  int field4;\n"
3922               "}\n"
3923               "+ (id)init {\n}\n"
3924               "@end");
3925
3926  verifyGoogleFormat("@implementation Foo : NSObject {\n"
3927                     " @public\n"
3928                     "  int field1;\n"
3929                     " @protected\n"
3930                     "  int field2;\n"
3931                     " @private\n"
3932                     "  int field3;\n"
3933                     " @package\n"
3934                     "  int field4;\n"
3935                     "}\n"
3936                     "+ (id)init {\n}\n"
3937                     "@end");
3938
3939  verifyFormat("@implementation Foo\n"
3940               "+ (id)init {\n"
3941               "  if (true)\n"
3942               "    return nil;\n"
3943               "}\n"
3944               "// Look, a comment!\n"
3945               "- (int)answerWith:(int)i {\n"
3946               "  return i;\n"
3947               "}\n"
3948               "+ (int)answerWith:(int)i {\n"
3949               "  return i;\n"
3950               "}\n"
3951               "@end");
3952
3953  verifyFormat("@implementation Foo\n"
3954               "@end\n"
3955               "@implementation Bar\n"
3956               "@end");
3957
3958  verifyFormat("@implementation Foo : Bar\n"
3959               "+ (id)init {\n}\n"
3960               "- (void)foo {\n}\n"
3961               "@end");
3962
3963  verifyFormat("@implementation Foo {\n"
3964               "  int _i;\n"
3965               "}\n"
3966               "+ (id)init {\n}\n"
3967               "@end");
3968
3969  verifyFormat("@implementation Foo : Bar {\n"
3970               "  int _i;\n"
3971               "}\n"
3972               "+ (id)init {\n}\n"
3973               "@end");
3974
3975  verifyFormat("@implementation Foo (HackStuff)\n"
3976               "+ (id)init {\n}\n"
3977               "@end");
3978}
3979
3980TEST_F(FormatTest, FormatObjCProtocol) {
3981  verifyFormat("@protocol Foo\n"
3982               "@property(weak) id delegate;\n"
3983               "- (NSUInteger)numberOfThings;\n"
3984               "@end");
3985
3986  verifyFormat("@protocol MyProtocol <NSObject>\n"
3987               "- (NSUInteger)numberOfThings;\n"
3988               "@end");
3989
3990  verifyGoogleFormat("@protocol MyProtocol<NSObject>\n"
3991                     "- (NSUInteger)numberOfThings;\n"
3992                     "@end");
3993
3994  verifyFormat("@protocol Foo;\n"
3995               "@protocol Bar;\n");
3996
3997  verifyFormat("@protocol Foo\n"
3998               "@end\n"
3999               "@protocol Bar\n"
4000               "@end");
4001
4002  verifyFormat("@protocol myProtocol\n"
4003               "- (void)mandatoryWithInt:(int)i;\n"
4004               "@optional\n"
4005               "- (void)optional;\n"
4006               "@required\n"
4007               "- (void)required;\n"
4008               "@optional\n"
4009               "@property(assign) int madProp;\n"
4010               "@end\n");
4011}
4012
4013TEST_F(FormatTest, FormatObjCMethodDeclarations) {
4014  verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
4015               "                   rect:(NSRect)theRect\n"
4016               "               interval:(float)theInterval {\n"
4017               "}");
4018  verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
4019               "          longKeyword:(NSRect)theRect\n"
4020               "    evenLongerKeyword:(float)theInterval\n"
4021               "                error:(NSError **)theError {\n"
4022               "}");
4023}
4024
4025TEST_F(FormatTest, FormatObjCMethodExpr) {
4026  verifyFormat("[foo bar:baz];");
4027  verifyFormat("return [foo bar:baz];");
4028  verifyFormat("f([foo bar:baz]);");
4029  verifyFormat("f(2, [foo bar:baz]);");
4030  verifyFormat("f(2, a ? b : c);");
4031  verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
4032
4033  // Unary operators.
4034  verifyFormat("int a = +[foo bar:baz];");
4035  verifyFormat("int a = -[foo bar:baz];");
4036  verifyFormat("int a = ![foo bar:baz];");
4037  verifyFormat("int a = ~[foo bar:baz];");
4038  verifyFormat("int a = ++[foo bar:baz];");
4039  verifyFormat("int a = --[foo bar:baz];");
4040  verifyFormat("int a = sizeof [foo bar:baz];");
4041  verifyFormat("int a = alignof [foo bar:baz];");
4042  verifyFormat("int a = &[foo bar:baz];");
4043  verifyFormat("int a = *[foo bar:baz];");
4044  // FIXME: Make casts work, without breaking f()[4].
4045  //verifyFormat("int a = (int)[foo bar:baz];");
4046  //verifyFormat("return (int)[foo bar:baz];");
4047  //verifyFormat("(void)[foo bar:baz];");
4048  verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
4049
4050  // Binary operators.
4051  verifyFormat("[foo bar:baz], [foo bar:baz];");
4052  verifyFormat("[foo bar:baz] = [foo bar:baz];");
4053  verifyFormat("[foo bar:baz] *= [foo bar:baz];");
4054  verifyFormat("[foo bar:baz] /= [foo bar:baz];");
4055  verifyFormat("[foo bar:baz] %= [foo bar:baz];");
4056  verifyFormat("[foo bar:baz] += [foo bar:baz];");
4057  verifyFormat("[foo bar:baz] -= [foo bar:baz];");
4058  verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
4059  verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
4060  verifyFormat("[foo bar:baz] &= [foo bar:baz];");
4061  verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
4062  verifyFormat("[foo bar:baz] |= [foo bar:baz];");
4063  verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
4064  verifyFormat("[foo bar:baz] || [foo bar:baz];");
4065  verifyFormat("[foo bar:baz] && [foo bar:baz];");
4066  verifyFormat("[foo bar:baz] | [foo bar:baz];");
4067  verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
4068  verifyFormat("[foo bar:baz] & [foo bar:baz];");
4069  verifyFormat("[foo bar:baz] == [foo bar:baz];");
4070  verifyFormat("[foo bar:baz] != [foo bar:baz];");
4071  verifyFormat("[foo bar:baz] >= [foo bar:baz];");
4072  verifyFormat("[foo bar:baz] <= [foo bar:baz];");
4073  verifyFormat("[foo bar:baz] > [foo bar:baz];");
4074  verifyFormat("[foo bar:baz] < [foo bar:baz];");
4075  verifyFormat("[foo bar:baz] >> [foo bar:baz];");
4076  verifyFormat("[foo bar:baz] << [foo bar:baz];");
4077  verifyFormat("[foo bar:baz] - [foo bar:baz];");
4078  verifyFormat("[foo bar:baz] + [foo bar:baz];");
4079  verifyFormat("[foo bar:baz] * [foo bar:baz];");
4080  verifyFormat("[foo bar:baz] / [foo bar:baz];");
4081  verifyFormat("[foo bar:baz] % [foo bar:baz];");
4082  // Whew!
4083
4084  verifyFormat("return in[42];");
4085  verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
4086               "}");
4087
4088  verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
4089  verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
4090  verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
4091  verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
4092  verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
4093  verifyFormat("[button setAction:@selector(zoomOut:)];");
4094  verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
4095
4096  verifyFormat("arr[[self indexForFoo:a]];");
4097  verifyFormat("throw [self errorFor:a];");
4098  verifyFormat("@throw [self errorFor:a];");
4099
4100  // This tests that the formatter doesn't break after "backing" but before ":",
4101  // which would be at 80 columns.
4102  verifyFormat(
4103      "void f() {\n"
4104      "  if ((self = [super initWithContentRect:contentRect\n"
4105      "                               styleMask:styleMask\n"
4106      "                                 backing:NSBackingStoreBuffered\n"
4107      "                                   defer:YES]))");
4108
4109  verifyFormat(
4110      "[foo checkThatBreakingAfterColonWorksOk:\n"
4111      "        [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
4112
4113  verifyFormat("[myObj short:arg1 // Force line break\n"
4114               "          longKeyword:arg2\n"
4115               "    evenLongerKeyword:arg3\n"
4116               "                error:arg4];");
4117  verifyFormat(
4118      "void f() {\n"
4119      "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
4120      "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
4121      "                                     pos.width(), pos.height())\n"
4122      "                styleMask:NSBorderlessWindowMask\n"
4123      "                  backing:NSBackingStoreBuffered\n"
4124      "                    defer:NO]);\n"
4125      "}");
4126  verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
4127               "                             with:contentsNativeView];");
4128
4129  verifyFormat(
4130      "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
4131      "           owner:nillllll];");
4132
4133  verifyFormat(
4134      "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
4135      "        forType:kBookmarkButtonDragType];");
4136
4137  verifyFormat("[defaultCenter addObserver:self\n"
4138               "                  selector:@selector(willEnterFullscreen)\n"
4139               "                      name:kWillEnterFullscreenNotification\n"
4140               "                    object:nil];");
4141  verifyFormat("[image_rep drawInRect:drawRect\n"
4142               "             fromRect:NSZeroRect\n"
4143               "            operation:NSCompositeCopy\n"
4144               "             fraction:1.0\n"
4145               "       respectFlipped:NO\n"
4146               "                hints:nil];");
4147
4148  verifyFormat(
4149      "scoped_nsobject<NSTextField> message(\n"
4150      "    // The frame will be fixed up when |-setMessageText:| is called.\n"
4151      "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
4152}
4153
4154TEST_F(FormatTest, ObjCAt) {
4155  verifyFormat("@autoreleasepool");
4156  verifyFormat("@catch");
4157  verifyFormat("@class");
4158  verifyFormat("@compatibility_alias");
4159  verifyFormat("@defs");
4160  verifyFormat("@dynamic");
4161  verifyFormat("@encode");
4162  verifyFormat("@end");
4163  verifyFormat("@finally");
4164  verifyFormat("@implementation");
4165  verifyFormat("@import");
4166  verifyFormat("@interface");
4167  verifyFormat("@optional");
4168  verifyFormat("@package");
4169  verifyFormat("@private");
4170  verifyFormat("@property");
4171  verifyFormat("@protected");
4172  verifyFormat("@protocol");
4173  verifyFormat("@public");
4174  verifyFormat("@required");
4175  verifyFormat("@selector");
4176  verifyFormat("@synchronized");
4177  verifyFormat("@synthesize");
4178  verifyFormat("@throw");
4179  verifyFormat("@try");
4180
4181  EXPECT_EQ("@interface", format("@ interface"));
4182
4183  // The precise formatting of this doesn't matter, nobody writes code like
4184  // this.
4185  verifyFormat("@ /*foo*/ interface");
4186}
4187
4188TEST_F(FormatTest, ObjCSnippets) {
4189  verifyFormat("@autoreleasepool {\n"
4190               "  foo();\n"
4191               "}");
4192  verifyFormat("@class Foo, Bar;");
4193  verifyFormat("@compatibility_alias AliasName ExistingClass;");
4194  verifyFormat("@dynamic textColor;");
4195  verifyFormat("char *buf1 = @encode(int *);");
4196  verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
4197  verifyFormat("char *buf1 = @encode(int **);");
4198  verifyFormat("Protocol *proto = @protocol(p1);");
4199  verifyFormat("SEL s = @selector(foo:);");
4200  verifyFormat("@synchronized(self) {\n"
4201               "  f();\n"
4202               "}");
4203
4204  verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
4205  verifyGoogleFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
4206
4207  verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
4208  verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
4209  verifyGoogleFormat("@property(assign, getter=isEditable) BOOL editable;");
4210}
4211
4212TEST_F(FormatTest, ObjCLiterals) {
4213  verifyFormat("@\"String\"");
4214  verifyFormat("@1");
4215  verifyFormat("@+4.8");
4216  verifyFormat("@-4");
4217  verifyFormat("@1LL");
4218  verifyFormat("@.5");
4219  verifyFormat("@'c'");
4220  verifyFormat("@true");
4221
4222  verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
4223  verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
4224  verifyFormat("NSNumber *favoriteColor = @(Green);");
4225  verifyFormat("NSString *path = @(getenv(\"PATH\"));");
4226
4227  verifyFormat("@[");
4228  verifyFormat("@[]");
4229  verifyFormat(
4230      "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
4231  verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
4232
4233  verifyFormat("@{");
4234  verifyFormat("@{}");
4235  verifyFormat("@{ @\"one\" : @1 }");
4236  verifyFormat("return @{ @\"one\" : @1 };");
4237  verifyFormat("@{ @\"one\" : @1, }");
4238
4239  verifyFormat("@{ @\"one\" : @{ @2 : @1 } }");
4240  verifyFormat("@{ @\"one\" : @{ @2 : @1 }, }");
4241
4242  verifyFormat("@{ 1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2 }");
4243  verifyFormat("[self setDict:@{}");
4244  verifyFormat("[self setDict:@{ @1 : @2 }");
4245  verifyFormat("NSLog(@\"%@\", @{ @1 : @2, @2 : @3 }[@1]);");
4246  verifyFormat(
4247      "NSDictionary *masses = @{ @\"H\" : @1.0078, @\"He\" : @4.0026 };");
4248  verifyFormat(
4249      "NSDictionary *settings = @{ AVEncoderKey : @(AVAudioQualityMax) };");
4250
4251  // FIXME: Nested and multi-line array and dictionary literals need more work.
4252  verifyFormat(
4253      "NSDictionary *d = @{ @\"nam\" : NSUserNam(), @\"dte\" : [NSDate date],\n"
4254      "                     @\"processInfo\" : [NSProcessInfo processInfo] };");
4255  verifyFormat(
4256      "@{ NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :\n"
4257      "   regularFont, };");
4258
4259}
4260
4261TEST_F(FormatTest, ReformatRegionAdjustsIndent) {
4262  EXPECT_EQ("{\n"
4263            "{\n"
4264            "a;\n"
4265            "b;\n"
4266            "}\n"
4267            "}",
4268            format("{\n"
4269                   "{\n"
4270                   "a;\n"
4271                   "     b;\n"
4272                   "}\n"
4273                   "}",
4274                   13, 2, getLLVMStyle()));
4275  EXPECT_EQ("{\n"
4276            "{\n"
4277            "  a;\n"
4278            "b;\n"
4279            "}\n"
4280            "}",
4281            format("{\n"
4282                   "{\n"
4283                   "     a;\n"
4284                   "b;\n"
4285                   "}\n"
4286                   "}",
4287                   9, 2, getLLVMStyle()));
4288  EXPECT_EQ("{\n"
4289            "{\n"
4290            "public:\n"
4291            "  b;\n"
4292            "}\n"
4293            "}",
4294            format("{\n"
4295                   "{\n"
4296                   "public:\n"
4297                   "     b;\n"
4298                   "}\n"
4299                   "}",
4300                   17, 2, getLLVMStyle()));
4301  EXPECT_EQ("{\n"
4302            "{\n"
4303            "a;\n"
4304            "}\n"
4305            "{\n"
4306            "  b; //\n"
4307            "}\n"
4308            "}",
4309            format("{\n"
4310                   "{\n"
4311                   "a;\n"
4312                   "}\n"
4313                   "{\n"
4314                   "           b; //\n"
4315                   "}\n"
4316                   "}",
4317                   22, 2, getLLVMStyle()));
4318  EXPECT_EQ("  {\n"
4319            "    a; //\n"
4320            "  }",
4321            format("  {\n"
4322                   "a; //\n"
4323                   "  }",
4324                   4, 2, getLLVMStyle()));
4325  EXPECT_EQ("void f() {}\n"
4326            "void g() {}",
4327            format("void f() {}\n"
4328                   "void g() {}",
4329                   13, 0, getLLVMStyle()));
4330  EXPECT_EQ("int a; // comment\n"
4331            "       // line 2\n"
4332            "int b;",
4333            format("int a; // comment\n"
4334                   "       // line 2\n"
4335                   "  int b;",
4336                   35, 0, getLLVMStyle()));
4337}
4338
4339TEST_F(FormatTest, BreakStringLiterals) {
4340  EXPECT_EQ("\"some text \"\n"
4341            "\"other\";",
4342            format("\"some text other\";", getLLVMStyleWithColumns(12)));
4343  EXPECT_EQ("\"some text \"\n"
4344            "\"other\";",
4345            format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
4346  EXPECT_EQ(
4347      "#define A  \\\n"
4348      "  \"some \"  \\\n"
4349      "  \"text \"  \\\n"
4350      "  \"other\";",
4351      format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
4352  EXPECT_EQ(
4353      "#define A  \\\n"
4354      "  \"so \"    \\\n"
4355      "  \"text \"  \\\n"
4356      "  \"other\";",
4357      format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
4358
4359  EXPECT_EQ("\"some text\"",
4360            format("\"some text\"", getLLVMStyleWithColumns(1)));
4361  EXPECT_EQ("\"some text\"",
4362            format("\"some text\"", getLLVMStyleWithColumns(11)));
4363  EXPECT_EQ("\"some \"\n"
4364            "\"text\"",
4365            format("\"some text\"", getLLVMStyleWithColumns(10)));
4366  EXPECT_EQ("\"some \"\n"
4367            "\"text\"",
4368            format("\"some text\"", getLLVMStyleWithColumns(7)));
4369  EXPECT_EQ("\"some\"\n"
4370            "\" tex\"\n"
4371            "\"t\"",
4372            format("\"some text\"", getLLVMStyleWithColumns(6)));
4373  EXPECT_EQ("\"some\"\n"
4374            "\" tex\"\n"
4375            "\" and\"",
4376            format("\"some tex and\"", getLLVMStyleWithColumns(6)));
4377  EXPECT_EQ("\"some\"\n"
4378            "\"/tex\"\n"
4379            "\"/and\"",
4380            format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
4381
4382  EXPECT_EQ("variable =\n"
4383            "    \"long string \"\n"
4384            "    \"literal\";",
4385            format("variable = \"long string literal\";",
4386                   getLLVMStyleWithColumns(20)));
4387
4388  EXPECT_EQ("variable = f(\n"
4389            "    \"long string \"\n"
4390            "    \"literal\",\n"
4391            "    short,\n"
4392            "    loooooooooooooooooooong);",
4393            format("variable = f(\"long string literal\", short, "
4394                   "loooooooooooooooooooong);",
4395                   getLLVMStyleWithColumns(20)));
4396  EXPECT_EQ(
4397      "f(\"one two\".split(\n"
4398      "    variable));",
4399      format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
4400  EXPECT_EQ("f(\"one two three four five six \"\n"
4401            "  \"seven\".split(\n"
4402            "      really_looooong_variable));",
4403            format("f(\"one two three four five six seven\"."
4404                   "split(really_looooong_variable));",
4405                   getLLVMStyleWithColumns(33)));
4406
4407  EXPECT_EQ("f(\"some \"\n"
4408            "  \"text\",\n"
4409            "  other);",
4410            format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
4411
4412  // Only break as a last resort.
4413  verifyFormat(
4414      "aaaaaaaaaaaaaaaaaaaa(\n"
4415      "    aaaaaaaaaaaaaaaaaaaa,\n"
4416      "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
4417
4418  EXPECT_EQ(
4419      "\"splitmea\"\n"
4420      "\"trandomp\"\n"
4421      "\"oint\"",
4422      format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
4423
4424  EXPECT_EQ(
4425      "\"split/\"\n"
4426      "\"pathat/\"\n"
4427      "\"slashes\"",
4428      format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
4429
4430  FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
4431  AlignLeft.AlignEscapedNewlinesLeft = true;
4432  EXPECT_EQ(
4433      "#define A \\\n"
4434      "  \"some \" \\\n"
4435      "  \"text \" \\\n"
4436      "  \"other\";",
4437      format("#define A \"some text other\";", AlignLeft));
4438}
4439
4440TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
4441  EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
4442            "             \"ddeeefff\");",
4443            format("someFunction(\"aaabbbcccdddeeefff\");",
4444                   getLLVMStyleWithColumns(25)));
4445  EXPECT_EQ("someFunction1234567890(\n"
4446            "    \"aaabbbcccdddeeefff\");",
4447            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
4448                   getLLVMStyleWithColumns(26)));
4449  EXPECT_EQ("someFunction1234567890(\n"
4450            "    \"aaabbbcccdddeeeff\"\n"
4451            "    \"f\");",
4452            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
4453                   getLLVMStyleWithColumns(25)));
4454  EXPECT_EQ("someFunction1234567890(\n"
4455            "    \"aaabbbcccdddeeeff\"\n"
4456            "    \"f\");",
4457            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
4458                   getLLVMStyleWithColumns(24)));
4459  EXPECT_EQ("someFunction(\n"
4460            "    \"aaabbbcc \"\n"
4461            "    \"dddeeefff\");",
4462            format("someFunction(\"aaabbbcc dddeeefff\");",
4463                   getLLVMStyleWithColumns(25)));
4464  EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
4465            "             \"ddeeefff\");",
4466            format("someFunction(\"aaabbbccc ddeeefff\");",
4467                   getLLVMStyleWithColumns(25)));
4468  EXPECT_EQ("someFunction1234567890(\n"
4469            "    \"aaabb \"\n"
4470            "    \"cccdddeeefff\");",
4471            format("someFunction1234567890(\"aaabb cccdddeeefff\");",
4472                   getLLVMStyleWithColumns(25)));
4473  EXPECT_EQ("#define A          \\\n"
4474            "  string s =       \\\n"
4475            "      \"123456789\"  \\\n"
4476            "      \"0\";         \\\n"
4477            "  int i;",
4478            format("#define A string s = \"1234567890\"; int i;",
4479                   getLLVMStyleWithColumns(20)));
4480}
4481
4482TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
4483  EXPECT_EQ("\"\\a\"",
4484            format("\"\\a\"", getLLVMStyleWithColumns(3)));
4485  EXPECT_EQ("\"\\\"",
4486            format("\"\\\"", getLLVMStyleWithColumns(2)));
4487  EXPECT_EQ("\"test\"\n"
4488            "\"\\n\"",
4489            format("\"test\\n\"", getLLVMStyleWithColumns(7)));
4490  EXPECT_EQ("\"tes\\\\\"\n"
4491            "\"n\"",
4492            format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
4493  EXPECT_EQ("\"\\\\\\\\\"\n"
4494            "\"\\n\"",
4495            format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
4496  EXPECT_EQ("\"\\uff01\"",
4497            format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
4498  EXPECT_EQ("\"\\uff01\"\n"
4499            "\"test\"",
4500            format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
4501  EXPECT_EQ("\"\\Uff01ff02\"",
4502            format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
4503  EXPECT_EQ("\"\\x000000000001\"\n"
4504            "\"next\"",
4505            format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
4506  EXPECT_EQ("\"\\x000000000001next\"",
4507            format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
4508  EXPECT_EQ("\"\\x000000000001\"",
4509            format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
4510  EXPECT_EQ("\"test\"\n"
4511            "\"\\000000\"\n"
4512            "\"000001\"",
4513            format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
4514  EXPECT_EQ("\"test\\000\"\n"
4515            "\"00000000\"\n"
4516            "\"1\"",
4517            format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
4518  EXPECT_EQ("R\"(\\x\\x00)\"\n",
4519            format("R\"(\\x\\x00)\"\n", getLLVMStyleWithColumns(7)));
4520}
4521
4522TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
4523  verifyFormat("void f() {\n"
4524               "  return g() {}\n"
4525               "  void h() {}");
4526  verifyFormat("if (foo)\n"
4527               "  return { forgot_closing_brace();\n"
4528               "test();");
4529  verifyFormat("int a[] = { void forgot_closing_brace() { f();\n"
4530               "g();\n"
4531               "}");
4532}
4533
4534TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
4535  verifyFormat("class X {\n"
4536               "  void f() {\n"
4537               "  }\n"
4538               "};",
4539               getLLVMStyleWithColumns(12));
4540}
4541
4542TEST_F(FormatTest, ConfigurableIndentWidth) {
4543  FormatStyle EightIndent = getLLVMStyleWithColumns(18);
4544  EightIndent.IndentWidth = 8;
4545  verifyFormat("void f() {\n"
4546               "        someFunction();\n"
4547               "        if (true) {\n"
4548               "                f();\n"
4549               "        }\n"
4550               "}",
4551               EightIndent);
4552  verifyFormat("class X {\n"
4553               "        void f() {\n"
4554               "        }\n"
4555               "};",
4556               EightIndent);
4557  verifyFormat("int x[] = {\n"
4558               "        call(),\n"
4559               "        call(),\n"
4560               "};",
4561               EightIndent);
4562}
4563
4564TEST_F(FormatTest, ConfigurableUseOfTab) {
4565  FormatStyle Tab = getLLVMStyleWithColumns(42);
4566  Tab.IndentWidth = 8;
4567  Tab.UseTab = true;
4568  Tab.AlignEscapedNewlinesLeft = true;
4569  verifyFormat("class X {\n"
4570               "\tvoid f() {\n"
4571               "\t\tsomeFunction(parameter1,\n"
4572               "\t\t\t     parameter2);\n"
4573               "\t}\n"
4574               "};",
4575               Tab);
4576  verifyFormat("#define A                        \\\n"
4577               "\tvoid f() {               \\\n"
4578               "\t\tsomeFunction(    \\\n"
4579               "\t\t    parameter1,  \\\n"
4580               "\t\t    parameter2); \\\n"
4581               "\t}",
4582               Tab);
4583
4584
4585  // FIXME: To correctly count mixed whitespace we need to
4586  // also correctly count mixed whitespace in front of the comment.
4587  //
4588  // EXPECT_EQ("/*\n"
4589  //           "\t      a\t\tcomment\n"
4590  //           "\t      in multiple lines\n"
4591  //           "       */",
4592  //           format("   /*\t \t \n"
4593  //                  " \t \t a\t\tcomment\t \t\n"
4594  //                  " \t \t in multiple lines\t\n"
4595  //                  " \t  */",
4596  //                  Tab));
4597  // Tab.UseTab = false;
4598  // EXPECT_EQ("/*\n"
4599  //           "              a\t\tcomment\n"
4600  //           "              in multiple lines\n"
4601  //           "       */",
4602  //           format("   /*\t \t \n"
4603  //                  " \t \t a\t\tcomment\t \t\n"
4604  //                  " \t \t in multiple lines\t\n"
4605  //                  " \t  */",
4606  //                  Tab));
4607  // EXPECT_EQ("/* some\n"
4608  //           "   comment */",
4609  //          format(" \t \t /* some\n"
4610  //                 " \t \t    comment */",
4611  //                 Tab));
4612
4613  EXPECT_EQ("{\n"
4614            "  /*\n"
4615            "   * Comment\n"
4616            "   */\n"
4617            "  int i;\n"
4618            "}",
4619            format("{\n"
4620                   "\t/*\n"
4621                   "\t * Comment\n"
4622                   "\t */\n"
4623                   "\t int i;\n"
4624                   "}"));
4625}
4626
4627TEST_F(FormatTest, LinuxBraceBreaking) {
4628  FormatStyle BreakBeforeBrace = getLLVMStyle();
4629  BreakBeforeBrace.BreakBeforeBraces = FormatStyle::BS_Linux;
4630  verifyFormat("namespace a\n"
4631               "{\n"
4632               "class A\n"
4633               "{\n"
4634               "  void f()\n"
4635               "  {\n"
4636               "    if (true) {\n"
4637               "      a();\n"
4638               "      b();\n"
4639               "    }\n"
4640               "  }\n"
4641               "  void g()\n"
4642               "  {\n"
4643               "    return;\n"
4644               "  }\n"
4645               "}\n"
4646               "}",
4647               BreakBeforeBrace);
4648}
4649
4650TEST_F(FormatTest, StroustrupBraceBreaking) {
4651  FormatStyle BreakBeforeBrace = getLLVMStyle();
4652  BreakBeforeBrace.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4653  verifyFormat("namespace a {\n"
4654               "class A {\n"
4655               "  void f()\n"
4656               "  {\n"
4657               "    if (true) {\n"
4658               "      a();\n"
4659               "      b();\n"
4660               "    }\n"
4661               "  }\n"
4662               "  void g()\n"
4663               "  {\n"
4664               "    return;\n"
4665               "  }\n"
4666               "}\n"
4667               "}",
4668               BreakBeforeBrace);
4669}
4670
4671bool allStylesEqual(ArrayRef<FormatStyle> Styles) {
4672  for (size_t i = 1; i < Styles.size(); ++i)
4673    if (!(Styles[0] == Styles[i]))
4674      return false;
4675  return true;
4676}
4677
4678TEST_F(FormatTest, GetsPredefinedStyleByName) {
4679  FormatStyle Styles[3];
4680
4681  Styles[0] = getLLVMStyle();
4682  EXPECT_TRUE(getPredefinedStyle("LLVM", &Styles[1]));
4683  EXPECT_TRUE(getPredefinedStyle("lLvM", &Styles[2]));
4684  EXPECT_TRUE(allStylesEqual(Styles));
4685
4686  Styles[0] = getGoogleStyle();
4687  EXPECT_TRUE(getPredefinedStyle("Google", &Styles[1]));
4688  EXPECT_TRUE(getPredefinedStyle("gOOgle", &Styles[2]));
4689  EXPECT_TRUE(allStylesEqual(Styles));
4690
4691  Styles[0] = getChromiumStyle();
4692  EXPECT_TRUE(getPredefinedStyle("Chromium", &Styles[1]));
4693  EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", &Styles[2]));
4694  EXPECT_TRUE(allStylesEqual(Styles));
4695
4696  Styles[0] = getMozillaStyle();
4697  EXPECT_TRUE(getPredefinedStyle("Mozilla", &Styles[1]));
4698  EXPECT_TRUE(getPredefinedStyle("moZILla", &Styles[2]));
4699  EXPECT_TRUE(allStylesEqual(Styles));
4700
4701  EXPECT_FALSE(getPredefinedStyle("qwerty", &Styles[0]));
4702}
4703
4704TEST_F(FormatTest, ParsesConfiguration) {
4705  FormatStyle Style = {};
4706#define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
4707  EXPECT_NE(VALUE, Style.FIELD);                                               \
4708  EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
4709  EXPECT_EQ(VALUE, Style.FIELD)
4710
4711#define CHECK_PARSE_BOOL(FIELD)                                                \
4712  Style.FIELD = false;                                                         \
4713  EXPECT_EQ(0, parseConfiguration(#FIELD ": true", &Style).value());           \
4714  EXPECT_TRUE(Style.FIELD);                                                    \
4715  EXPECT_EQ(0, parseConfiguration(#FIELD ": false", &Style).value());          \
4716  EXPECT_FALSE(Style.FIELD);
4717
4718  CHECK_PARSE_BOOL(AlignEscapedNewlinesLeft);
4719  CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
4720  CHECK_PARSE_BOOL(AllowShortIfStatementsOnASingleLine);
4721  CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
4722  CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
4723  CHECK_PARSE_BOOL(BinPackParameters);
4724  CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
4725  CHECK_PARSE_BOOL(DerivePointerBinding);
4726  CHECK_PARSE_BOOL(IndentCaseLabels);
4727  CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
4728  CHECK_PARSE_BOOL(PointerBindsToType);
4729  CHECK_PARSE_BOOL(SpacesInBracedLists);
4730  CHECK_PARSE_BOOL(UseTab);
4731
4732  CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
4733  CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
4734  CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
4735  CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
4736  CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
4737              PenaltyReturnTypeOnItsOwnLine, 1234u);
4738  CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
4739              SpacesBeforeTrailingComments, 1234u);
4740  CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
4741
4742  Style.Standard = FormatStyle::LS_Auto;
4743  CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
4744  CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
4745  CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
4746
4747  Style.ColumnLimit = 123;
4748  FormatStyle BaseStyle = getLLVMStyle();
4749  CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
4750  CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
4751
4752  Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
4753  CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
4754              FormatStyle::BS_Attach);
4755  CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
4756              FormatStyle::BS_Linux);
4757  CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
4758              FormatStyle::BS_Stroustrup);
4759
4760#undef CHECK_PARSE
4761#undef CHECK_PARSE_BOOL
4762}
4763
4764TEST_F(FormatTest, ConfigurationRoundTripTest) {
4765  FormatStyle Style = getLLVMStyle();
4766  std::string YAML = configurationAsText(Style);
4767  FormatStyle ParsedStyle = {};
4768  EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
4769  EXPECT_EQ(Style, ParsedStyle);
4770}
4771
4772} // end namespace tooling
4773} // end namespace clang
4774