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, RemovesEmptyLines) {
196  EXPECT_EQ("class C {\n"
197            "  int i;\n"
198            "};",
199            format("class C {\n"
200                   " int i;\n"
201                   "\n"
202                   "};"));
203
204  // Don't remove empty lines in more complex control statements.
205  EXPECT_EQ("void f() {\n"
206            "  if (a) {\n"
207            "    f();\n"
208            "\n"
209            "  } else if (b) {\n"
210            "    f();\n"
211            "  }\n"
212            "}",
213            format("void f() {\n"
214                   "  if (a) {\n"
215                   "    f();\n"
216                   "\n"
217                   "  } else if (b) {\n"
218                   "    f();\n"
219                   "\n"
220                   "  }\n"
221                   "\n"
222                   "}"));
223
224  // FIXME: This is slightly inconsistent.
225  EXPECT_EQ("namespace {\n"
226            "int i;\n"
227            "}",
228            format("namespace {\n"
229                   "int i;\n"
230                   "\n"
231                   "}"));
232  EXPECT_EQ("namespace {\n"
233            "int i;\n"
234            "\n"
235            "} // namespace",
236            format("namespace {\n"
237                   "int i;\n"
238                   "\n"
239                   "}  // namespace"));
240}
241
242TEST_F(FormatTest, ReformatsMovedLines) {
243  EXPECT_EQ(
244      "template <typename T> T *getFETokenInfo() const {\n"
245      "  return static_cast<T *>(FETokenInfo);\n"
246      "}\n"
247      "  int a; // <- Should not be formatted",
248      format(
249          "template<typename T>\n"
250          "T *getFETokenInfo() const { return static_cast<T*>(FETokenInfo); }\n"
251          "  int a; // <- Should not be formatted",
252          9, 5, getLLVMStyle()));
253}
254
255//===----------------------------------------------------------------------===//
256// Tests for control statements.
257//===----------------------------------------------------------------------===//
258
259TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
260  verifyFormat("if (true)\n  f();\ng();");
261  verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
262  verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
263
264  FormatStyle AllowsMergedIf = getLLVMStyle();
265  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
266  verifyFormat("if (a)\n"
267               "  // comment\n"
268               "  f();",
269               AllowsMergedIf);
270  verifyFormat("if (a)\n"
271               "  ;",
272               AllowsMergedIf);
273  verifyFormat("if (a)\n"
274               "  if (b) return;",
275               AllowsMergedIf);
276
277  verifyFormat("if (a) // Can't merge this\n"
278               "  f();\n",
279               AllowsMergedIf);
280  verifyFormat("if (a) /* still don't merge */\n"
281               "  f();",
282               AllowsMergedIf);
283  verifyFormat("if (a) { // Never merge this\n"
284               "  f();\n"
285               "}",
286               AllowsMergedIf);
287  verifyFormat("if (a) { /* Never merge this */\n"
288               "  f();\n"
289               "}",
290               AllowsMergedIf);
291
292  EXPECT_EQ("if (a) return;", format("if(a)\nreturn;", 7, 1, AllowsMergedIf));
293  EXPECT_EQ("if (a) return; // comment",
294            format("if(a)\nreturn; // comment", 20, 1, AllowsMergedIf));
295
296  AllowsMergedIf.ColumnLimit = 14;
297  verifyFormat("if (a) return;", AllowsMergedIf);
298  verifyFormat("if (aaaaaaaaa)\n"
299               "  return;",
300               AllowsMergedIf);
301
302  AllowsMergedIf.ColumnLimit = 13;
303  verifyFormat("if (a)\n  return;", AllowsMergedIf);
304}
305
306TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
307  FormatStyle AllowsMergedLoops = getLLVMStyle();
308  AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
309  verifyFormat("while (true) continue;", AllowsMergedLoops);
310  verifyFormat("for (;;) continue;", AllowsMergedLoops);
311  verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
312  verifyFormat("while (true)\n"
313               "  ;",
314               AllowsMergedLoops);
315  verifyFormat("for (;;)\n"
316               "  ;",
317               AllowsMergedLoops);
318  verifyFormat("for (;;)\n"
319               "  for (;;) continue;",
320               AllowsMergedLoops);
321  verifyFormat("for (;;) // Can't merge this\n"
322               "  continue;",
323               AllowsMergedLoops);
324  verifyFormat("for (;;) /* still don't merge */\n"
325               "  continue;",
326               AllowsMergedLoops);
327}
328
329TEST_F(FormatTest, ParseIfElse) {
330  verifyFormat("if (true)\n"
331               "  if (true)\n"
332               "    if (true)\n"
333               "      f();\n"
334               "    else\n"
335               "      g();\n"
336               "  else\n"
337               "    h();\n"
338               "else\n"
339               "  i();");
340  verifyFormat("if (true)\n"
341               "  if (true)\n"
342               "    if (true) {\n"
343               "      if (true)\n"
344               "        f();\n"
345               "    } else {\n"
346               "      g();\n"
347               "    }\n"
348               "  else\n"
349               "    h();\n"
350               "else {\n"
351               "  i();\n"
352               "}");
353}
354
355TEST_F(FormatTest, ElseIf) {
356  verifyFormat("if (a) {\n} else if (b) {\n}");
357  verifyFormat("if (a)\n"
358               "  f();\n"
359               "else if (b)\n"
360               "  g();\n"
361               "else\n"
362               "  h();");
363}
364
365TEST_F(FormatTest, FormatsForLoop) {
366  verifyFormat(
367      "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
368      "     ++VeryVeryLongLoopVariable)\n"
369      "  ;");
370  verifyFormat("for (;;)\n"
371               "  f();");
372  verifyFormat("for (;;) {\n}");
373  verifyFormat("for (;;) {\n"
374               "  f();\n"
375               "}");
376  verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
377
378  verifyFormat(
379      "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
380      "                                          E = UnwrappedLines.end();\n"
381      "     I != E; ++I) {\n}");
382
383  verifyFormat(
384      "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
385      "     ++IIIII) {\n}");
386  verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
387               "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
388               "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
389  verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
390               "         I = FD->getDeclsInPrototypeScope().begin(),\n"
391               "         E = FD->getDeclsInPrototypeScope().end();\n"
392               "     I != E; ++I) {\n}");
393
394  // FIXME: Not sure whether we want extra identation in line 3 here:
395  verifyFormat(
396      "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
397      "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
398      "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
399      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
400      "     ++aaaaaaaaaaa) {\n}");
401  verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
402               "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
403               "}");
404  verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
405               "         aaaaaaaaaa);\n"
406               "     iter; ++iter) {\n"
407               "}");
408
409  FormatStyle NoBinPacking = getLLVMStyle();
410  NoBinPacking.BinPackParameters = false;
411  verifyFormat("for (int aaaaaaaaaaa = 1;\n"
412               "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
413               "                                           aaaaaaaaaaaaaaaa,\n"
414               "                                           aaaaaaaaaaaaaaaa,\n"
415               "                                           aaaaaaaaaaaaaaaa);\n"
416               "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
417               "}",
418               NoBinPacking);
419  verifyFormat(
420      "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
421      "                                          E = UnwrappedLines.end();\n"
422      "     I != E;\n"
423      "     ++I) {\n}",
424      NoBinPacking);
425}
426
427TEST_F(FormatTest, RangeBasedForLoops) {
428  verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
429               "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
430  verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
431               "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
432  verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
433               "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
434}
435
436TEST_F(FormatTest, FormatsWhileLoop) {
437  verifyFormat("while (true) {\n}");
438  verifyFormat("while (true)\n"
439               "  f();");
440  verifyFormat("while () {\n}");
441  verifyFormat("while () {\n"
442               "  f();\n"
443               "}");
444}
445
446TEST_F(FormatTest, FormatsDoWhile) {
447  verifyFormat("do {\n"
448               "  do_something();\n"
449               "} while (something());");
450  verifyFormat("do\n"
451               "  do_something();\n"
452               "while (something());");
453}
454
455TEST_F(FormatTest, FormatsSwitchStatement) {
456  verifyFormat("switch (x) {\n"
457               "case 1:\n"
458               "  f();\n"
459               "  break;\n"
460               "case kFoo:\n"
461               "case ns::kBar:\n"
462               "case kBaz:\n"
463               "  break;\n"
464               "default:\n"
465               "  g();\n"
466               "  break;\n"
467               "}");
468  verifyFormat("switch (x) {\n"
469               "case 1: {\n"
470               "  f();\n"
471               "  break;\n"
472               "}\n"
473               "}");
474  verifyFormat("switch (x) {\n"
475               "case 1: {\n"
476               "  f();\n"
477               "  {\n"
478               "    g();\n"
479               "    h();\n"
480               "  }\n"
481               "  break;\n"
482               "}\n"
483               "}");
484  verifyFormat("switch (x) {\n"
485               "case 1: {\n"
486               "  f();\n"
487               "  if (foo) {\n"
488               "    g();\n"
489               "    h();\n"
490               "  }\n"
491               "  break;\n"
492               "}\n"
493               "}");
494  verifyFormat("switch (x) {\n"
495               "case 1: {\n"
496               "  f();\n"
497               "  g();\n"
498               "} break;\n"
499               "}");
500  verifyFormat("switch (test)\n"
501               "  ;");
502  verifyFormat("switch (x) {\n"
503               "default: {\n"
504               "  // Do nothing.\n"
505               "}\n"
506               "}");
507  verifyFormat("switch (x) {\n"
508               "// comment\n"
509               "// if 1, do f()\n"
510               "case 1:\n"
511               "  f();\n"
512               "}");
513  verifyFormat("switch (x) {\n"
514               "case 1:\n"
515               "  // Do amazing stuff\n"
516               "  {\n"
517               "    f();\n"
518               "    g();\n"
519               "  }\n"
520               "  break;\n"
521               "}");
522  verifyFormat("#define A          \\\n"
523               "  switch (x) {     \\\n"
524               "  case a:          \\\n"
525               "    foo = b;       \\\n"
526               "  }", getLLVMStyleWithColumns(20));
527
528  verifyGoogleFormat("switch (x) {\n"
529                     "  case 1:\n"
530                     "    f();\n"
531                     "    break;\n"
532                     "  case kFoo:\n"
533                     "  case ns::kBar:\n"
534                     "  case kBaz:\n"
535                     "    break;\n"
536                     "  default:\n"
537                     "    g();\n"
538                     "    break;\n"
539                     "}");
540  verifyGoogleFormat("switch (x) {\n"
541                     "  case 1: {\n"
542                     "    f();\n"
543                     "    break;\n"
544                     "  }\n"
545                     "}");
546  verifyGoogleFormat("switch (test)\n"
547                     "  ;");
548
549  verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
550                     "  case OP_name:              \\\n"
551                     "    return operations::Operation##name\n");
552  verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
553                     "  // Get the correction operation class.\n"
554                     "  switch (OpCode) {\n"
555                     "    CASE(Add);\n"
556                     "    CASE(Subtract);\n"
557                     "    default:\n"
558                     "      return operations::Unknown;\n"
559                     "  }\n"
560                     "#undef OPERATION_CASE\n"
561                     "}");
562}
563
564TEST_F(FormatTest, FormatsLabels) {
565  verifyFormat("void f() {\n"
566               "  some_code();\n"
567               "test_label:\n"
568               "  some_other_code();\n"
569               "  {\n"
570               "    some_more_code();\n"
571               "  another_label:\n"
572               "    some_more_code();\n"
573               "  }\n"
574               "}");
575  verifyFormat("some_code();\n"
576               "test_label:\n"
577               "some_other_code();");
578}
579
580//===----------------------------------------------------------------------===//
581// Tests for comments.
582//===----------------------------------------------------------------------===//
583
584TEST_F(FormatTest, UnderstandsSingleLineComments) {
585  verifyFormat("//* */");
586  verifyFormat("// line 1\n"
587               "// line 2\n"
588               "void f() {}\n");
589
590  verifyFormat("void f() {\n"
591               "  // Doesn't do anything\n"
592               "}");
593  verifyFormat("SomeObject\n"
594               "    // Calling someFunction on SomeObject\n"
595               "    .someFunction();");
596  verifyFormat("void f(int i,  // some comment (probably for i)\n"
597               "       int j,  // some comment (probably for j)\n"
598               "       int k); // some comment (probably for k)");
599  verifyFormat("void f(int i,\n"
600               "       // some comment (probably for j)\n"
601               "       int j,\n"
602               "       // some comment (probably for k)\n"
603               "       int k);");
604
605  verifyFormat("int i    // This is a fancy variable\n"
606               "    = 5; // with nicely aligned comment.");
607
608  verifyFormat("// Leading comment.\n"
609               "int a; // Trailing comment.");
610  verifyFormat("int a; // Trailing comment\n"
611               "       // on 2\n"
612               "       // or 3 lines.\n"
613               "int b;");
614  verifyFormat("int a; // Trailing comment\n"
615               "\n"
616               "// Leading comment.\n"
617               "int b;");
618  verifyFormat("int a;    // Comment.\n"
619               "          // More details.\n"
620               "int bbbb; // Another comment.");
621  verifyFormat(
622      "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
623      "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   // comment\n"
624      "int cccccccccccccccccccccccccccccc;       // comment\n"
625      "int ddd;                     // looooooooooooooooooooooooong comment\n"
626      "int aaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
627      "int bbbbbbbbbbbbbbbbbbbbb;   // comment\n"
628      "int ccccccccccccccccccc;     // comment");
629
630  verifyFormat("#include \"a\"     // comment\n"
631               "#include \"a/b/c\" // comment");
632  verifyFormat("#include <a>     // comment\n"
633               "#include <a/b/c> // comment");
634  EXPECT_EQ("#include \\\n"
635            "  \"a\"            // comment\n"
636            "#include \"a/b/c\" // comment",
637            format("#include \\\n"
638                   "  \"a\" // comment\n"
639                   "#include \"a/b/c\" // comment"));
640
641  verifyFormat("enum E {\n"
642               "  // comment\n"
643               "  VAL_A, // comment\n"
644               "  VAL_B\n"
645               "};");
646
647  verifyFormat(
648      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
649      "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // Trailing comment");
650  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
651               "    // Comment inside a statement.\n"
652               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
653  verifyFormat(
654      "bool aaaaaaaaaaaaa = // comment\n"
655      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
656      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
657
658  verifyFormat("int aaaa; // aaaaa\n"
659               "int aa;   // aaaaaaa",
660               getLLVMStyleWithColumns(20));
661
662  EXPECT_EQ("void f() { // This does something ..\n"
663            "}\n"
664            "int a; // This is unrelated",
665            format("void f()    {     // This does something ..\n"
666                   "  }\n"
667                   "int   a;     // This is unrelated"));
668  EXPECT_EQ("class C {\n"
669            "  void f() { // This does something ..\n"
670            "  }          // awesome..\n"
671            "\n"
672            "  int a; // This is unrelated\n"
673            "};",
674            format("class C{void f()    { // This does something ..\n"
675                   "      } // awesome..\n"
676                   " \n"
677                   "int a;    // This is unrelated\n"
678                   "};"));
679
680  EXPECT_EQ("int i; // single line trailing comment",
681            format("int i;\\\n// single line trailing comment"));
682
683  verifyGoogleFormat("int a;  // Trailing comment.");
684
685  verifyFormat("someFunction(anotherFunction( // Force break.\n"
686               "    parameter));");
687
688  verifyGoogleFormat("#endif  // HEADER_GUARD");
689
690  verifyFormat("const char *test[] = {\n"
691               "  // A\n"
692               "  \"aaaa\",\n"
693               "  // B\n"
694               "  \"aaaaa\",\n"
695               "};");
696  verifyGoogleFormat(
697      "aaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
698      "    aaaaaaaaaaaaaaaaaaaaaa);  // 81_cols_with_this_comment");
699  EXPECT_EQ("D(a, {\n"
700            "  // test\n"
701            "  int a;\n"
702            "});",
703            format("D(a, {\n"
704                   "// test\n"
705                   "int a;\n"
706                   "});"));
707
708  EXPECT_EQ("lineWith(); // comment\n"
709            "// at start\n"
710            "otherLine();",
711            format("lineWith();   // comment\n"
712                   "// at start\n"
713                   "otherLine();"));
714  EXPECT_EQ("lineWith(); // comment\n"
715            "            // at start\n"
716            "otherLine();",
717            format("lineWith();   // comment\n"
718                   " // at start\n"
719                   "otherLine();"));
720
721  EXPECT_EQ("lineWith(); // comment\n"
722            "// at start\n"
723            "otherLine(); // comment",
724            format("lineWith();   // comment\n"
725                   "// at start\n"
726                   "otherLine();   // comment"));
727  EXPECT_EQ("lineWith();\n"
728            "// at start\n"
729            "otherLine(); // comment",
730            format("lineWith();\n"
731                   " // at start\n"
732                   "otherLine();   // comment"));
733  EXPECT_EQ("// first\n"
734            "// at start\n"
735            "otherLine(); // comment",
736            format("// first\n"
737                   " // at start\n"
738                   "otherLine();   // comment"));
739  EXPECT_EQ("f();\n"
740            "// first\n"
741            "// at start\n"
742            "otherLine(); // comment",
743            format("f();\n"
744                   "// first\n"
745                   " // at start\n"
746                   "otherLine();   // comment"));
747}
748
749TEST_F(FormatTest, CanFormatCommentsLocally) {
750  EXPECT_EQ("int a;    // comment\n"
751            "int    b; // comment",
752            format("int   a; // comment\n"
753                   "int    b; // comment",
754                   0, 0, getLLVMStyle()));
755  EXPECT_EQ("int   a; // comment\n"
756            "         // line 2\n"
757            "int b;",
758            format("int   a; // comment\n"
759                   "            // line 2\n"
760                   "int b;",
761                   28, 0, getLLVMStyle()));
762  EXPECT_EQ("int aaaaaa; // comment\n"
763            "int b;\n"
764            "int c; // unrelated comment",
765            format("int aaaaaa; // comment\n"
766                   "int b;\n"
767                   "int   c; // unrelated comment",
768                   31, 0, getLLVMStyle()));
769}
770
771TEST_F(FormatTest, RemovesTrailingWhitespaceOfComments) {
772  EXPECT_EQ("// comment", format("// comment  "));
773  EXPECT_EQ("int aaaaaaa, bbbbbbb; // comment",
774            format("int aaaaaaa, bbbbbbb; // comment                   ",
775                   getLLVMStyleWithColumns(33)));
776}
777
778TEST_F(FormatTest, UnderstandsBlockComments) {
779  verifyFormat("f(/*noSpaceAfterParameterNamingComment=*/true);");
780  EXPECT_EQ(
781      "f(aaaaaaaaaaaaaaaaaaaaaaaaa, /* Trailing comment for aa... */\n"
782      "  bbbbbbbbbbbbbbbbbbbbbbbbb);",
783      format("f(aaaaaaaaaaaaaaaaaaaaaaaaa ,   \\\n/* Trailing comment for aa... */\n"
784             "  bbbbbbbbbbbbbbbbbbbbbbbbb);"));
785  EXPECT_EQ(
786      "f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
787      "  /* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);",
788      format("f(aaaaaaaaaaaaaaaaaaaaaaaaa    ,   \n"
789             "/* Leading comment for bb... */   bbbbbbbbbbbbbbbbbbbbbbbbb);"));
790  EXPECT_EQ(
791      "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
792      "    aaaaaaaaaaaaaaaaaa,\n"
793      "    aaaaaaaaaaaaaaaaaa) { /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
794      "}",
795      format("void      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
796             "                      aaaaaaaaaaaaaaaaaa  ,\n"
797             "    aaaaaaaaaaaaaaaaaa) {   /*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*/\n"
798             "}"));
799
800  FormatStyle NoBinPacking = getLLVMStyle();
801  NoBinPacking.BinPackParameters = false;
802  verifyFormat("aaaaaaaa(/* parameter 1 */ aaaaaa,\n"
803               "         /* parameter 2 */ aaaaaa,\n"
804               "         /* parameter 3 */ aaaaaa,\n"
805               "         /* parameter 4 */ aaaaaa);",
806               NoBinPacking);
807}
808
809TEST_F(FormatTest, AlignsBlockComments) {
810  EXPECT_EQ("/*\n"
811            " * Really multi-line\n"
812            " * comment.\n"
813            " */\n"
814            "void f() {}",
815            format("  /*\n"
816                   "   * Really multi-line\n"
817                   "   * comment.\n"
818                   "   */\n"
819                   "  void f() {}"));
820  EXPECT_EQ("class C {\n"
821            "  /*\n"
822            "   * Another multi-line\n"
823            "   * comment.\n"
824            "   */\n"
825            "  void f() {}\n"
826            "};",
827            format("class C {\n"
828                   "/*\n"
829                   " * Another multi-line\n"
830                   " * comment.\n"
831                   " */\n"
832                   "void f() {}\n"
833                   "};"));
834  EXPECT_EQ("/*\n"
835            "  1. This is a comment with non-trivial formatting.\n"
836            "     1.1. We have to indent/outdent all lines equally\n"
837            "         1.1.1. to keep the formatting.\n"
838            " */",
839            format("  /*\n"
840                   "    1. This is a comment with non-trivial formatting.\n"
841                   "       1.1. We have to indent/outdent all lines equally\n"
842                   "           1.1.1. to keep the formatting.\n"
843                   "   */"));
844  EXPECT_EQ("/*\n"
845            "Don't try to outdent if there's not enough indentation.\n"
846            "*/",
847            format("  /*\n"
848                   " Don't try to outdent if there's not enough indentation.\n"
849                   " */"));
850
851  EXPECT_EQ("int i; /* Comment with empty...\n"
852            "        *\n"
853            "        * line. */",
854            format("int i; /* Comment with empty...\n"
855                   "        *\n"
856                   "        * line. */"));
857}
858
859TEST_F(FormatTest, CorrectlyHandlesLengthOfBlockComments) {
860  EXPECT_EQ("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
861            "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */",
862            format("double *x; /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
863                   "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */"));
864  EXPECT_EQ(
865      "void ffffffffffff(\n"
866      "    int aaaaaaaa, int bbbbbbbb,\n"
867      "    int cccccccccccc) { /*\n"
868      "                           aaaaaaaaaa\n"
869      "                           aaaaaaaaaaaaa\n"
870      "                           bbbbbbbbbbbbbb\n"
871      "                           bbbbbbbbbb\n"
872      "                         */\n"
873      "}",
874      format("void ffffffffffff(int aaaaaaaa, int bbbbbbbb, int cccccccccccc)\n"
875             "{ /*\n"
876             "     aaaaaaaaaa aaaaaaaaaaaaa\n"
877             "     bbbbbbbbbbbbbb bbbbbbbbbb\n"
878             "   */\n"
879             "}",
880             getLLVMStyleWithColumns(40)));
881}
882
883TEST_F(FormatTest, DontBreakNonTrailingBlockComments) {
884  EXPECT_EQ("void\n"
885            "ffffffffff(int aaaaa /* test */);",
886            format("void ffffffffff(int aaaaa /* test */);",
887                   getLLVMStyleWithColumns(35)));
888}
889
890TEST_F(FormatTest, SplitsLongCxxComments) {
891  EXPECT_EQ("// A comment that\n"
892            "// doesn't fit on\n"
893            "// one line",
894            format("// A comment that doesn't fit on one line",
895                   getLLVMStyleWithColumns(20)));
896  EXPECT_EQ("// a b c d\n"
897            "// e f  g\n"
898            "// h i j k",
899            format("// a b c d e f  g h i j k",
900                   getLLVMStyleWithColumns(10)));
901  EXPECT_EQ("// a b c d\n"
902            "// e f  g\n"
903            "// h i j k",
904            format("\\\n// a b c d e f  g h i j k",
905                   getLLVMStyleWithColumns(10)));
906  EXPECT_EQ("if (true) // A comment that\n"
907            "          // doesn't fit on\n"
908            "          // one line",
909            format("if (true) // A comment that doesn't fit on one line   ",
910                   getLLVMStyleWithColumns(30)));
911  EXPECT_EQ("//    Don't_touch_leading_whitespace",
912            format("//    Don't_touch_leading_whitespace",
913                   getLLVMStyleWithColumns(20)));
914  EXPECT_EQ("// Add leading\n"
915            "// whitespace",
916            format("//Add leading whitespace", getLLVMStyleWithColumns(20)));
917  EXPECT_EQ("// whitespace", format("//whitespace", getLLVMStyle()));
918  EXPECT_EQ("// Even if it makes the line exceed the column\n"
919            "// limit",
920            format("//Even if it makes the line exceed the column limit",
921                   getLLVMStyleWithColumns(51)));
922  EXPECT_EQ("//--But not here", format("//--But not here", getLLVMStyle()));
923  EXPECT_EQ("// A comment before\n"
924            "// a macro\n"
925            "// definition\n"
926            "#define a b",
927            format("// A comment before a macro definition\n"
928                   "#define a b",
929                   getLLVMStyleWithColumns(20)));
930  EXPECT_EQ("void ffffff(int aaaaaaaaa,  // wwww\n"
931            "            int a, int bbb, // xxxxxxx\n"
932            "                            // yyyyyyyyy\n"
933            "            int c, int d, int e) {}",
934            format("void ffffff(\n"
935                   "    int aaaaaaaaa, // wwww\n"
936                   "    int a,\n"
937                   "    int bbb, // xxxxxxx yyyyyyyyy\n"
938                   "    int c, int d, int e) {}",
939                   getLLVMStyleWithColumns(40)));
940  EXPECT_EQ("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
941            format("//\t aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
942                   getLLVMStyleWithColumns(20)));
943}
944
945TEST_F(FormatTest, DontSplitLineCommentsWithEscapedNewlines) {
946  EXPECT_EQ("// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
947            "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
948            "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
949            format("// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
950                   "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
951                   "// aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
952  EXPECT_EQ("int a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
953            "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
954            "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
955            format("int a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
956                   "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
957                   "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
958                   getLLVMStyleWithColumns(50)));
959  // FIXME: One day we might want to implement adjustment of leading whitespace
960  // of the consecutive lines in this kind of comment:
961  EXPECT_EQ("int\n"
962            "a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
963            "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
964            "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
965            format("int a; // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
966                   "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\\n"
967                   "       // AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
968                   getLLVMStyleWithColumns(49)));
969}
970
971TEST_F(FormatTest, PriorityOfCommentBreaking) {
972  EXPECT_EQ("if (xxx == yyy && // aaaaaaaaaaaa\n"
973            "                  // bbbbbbbbb\n"
974            "    zzz)\n"
975            "  q();",
976            format("if (xxx == yyy && // aaaaaaaaaaaa bbbbbbbbb\n"
977                   "    zzz) q();",
978                   getLLVMStyleWithColumns(40)));
979  EXPECT_EQ("if (xxxxxxxxxx ==\n"
980            "        yyy && // aaaaaa bbbbbbbb cccc\n"
981            "    zzz)\n"
982            "  q();",
983            format("if (xxxxxxxxxx == yyy && // aaaaaa bbbbbbbb cccc\n"
984                   "    zzz) q();",
985                   getLLVMStyleWithColumns(40)));
986  EXPECT_EQ("if (xxxxxxxxxx &&\n"
987            "        yyy || // aaaaaa bbbbbbbb cccc\n"
988            "    zzz)\n"
989            "  q();",
990            format("if (xxxxxxxxxx && yyy || // aaaaaa bbbbbbbb cccc\n"
991                   "    zzz) q();",
992                   getLLVMStyleWithColumns(40)));
993  EXPECT_EQ("fffffffff(&xxx, // aaaaaaaaaaaa\n"
994            "                // bbbbbbbbbbb\n"
995            "          zzz);",
996            format("fffffffff(&xxx, // aaaaaaaaaaaa bbbbbbbbbbb\n"
997                   " zzz);",
998                   getLLVMStyleWithColumns(40)));
999}
1000
1001TEST_F(FormatTest, MultiLineCommentsInDefines) {
1002  EXPECT_EQ("#define A(x) /* \\\n"
1003            "  a comment     \\\n"
1004            "  inside */     \\\n"
1005            "  f();",
1006            format("#define A(x) /* \\\n"
1007                   "  a comment     \\\n"
1008                   "  inside */     \\\n"
1009                   "  f();",
1010                   getLLVMStyleWithColumns(17)));
1011  EXPECT_EQ("#define A(      \\\n"
1012            "    x) /*       \\\n"
1013            "  a comment     \\\n"
1014            "  inside */     \\\n"
1015            "  f();",
1016            format("#define A(      \\\n"
1017                   "    x) /*       \\\n"
1018                   "  a comment     \\\n"
1019                   "  inside */     \\\n"
1020                   "  f();",
1021                   getLLVMStyleWithColumns(17)));
1022}
1023
1024TEST_F(FormatTest, ParsesCommentsAdjacentToPPDirectives) {
1025  EXPECT_EQ("namespace {}\n// Test\n#define A",
1026            format("namespace {}\n   // Test\n#define A"));
1027  EXPECT_EQ("namespace {}\n/* Test */\n#define A",
1028            format("namespace {}\n   /* Test */\n#define A"));
1029  EXPECT_EQ("namespace {}\n/* Test */ #define A",
1030            format("namespace {}\n   /* Test */    #define A"));
1031}
1032
1033TEST_F(FormatTest, SplitsLongLinesInComments) {
1034  EXPECT_EQ("/* This is a long\n"
1035            " * comment that\n"
1036            " * doesn't\n"
1037            " * fit on one line.\n"
1038            " */",
1039            format("/* "
1040                   "This is a long                                         "
1041                   "comment that "
1042                   "doesn't                                    "
1043                   "fit on one line.  */",
1044                   getLLVMStyleWithColumns(20)));
1045  EXPECT_EQ("/* a b c d\n"
1046            " * e f  g\n"
1047            " * h i j k\n"
1048            " */",
1049            format("/* a b c d e f  g h i j k */",
1050                   getLLVMStyleWithColumns(10)));
1051  EXPECT_EQ("/* a b c d\n"
1052            " * e f  g\n"
1053            " * h i j k\n"
1054            " */",
1055            format("\\\n/* a b c d e f  g h i j k */",
1056                   getLLVMStyleWithColumns(10)));
1057  EXPECT_EQ("/*\n"
1058            "This is a long\n"
1059            "comment that doesn't\n"
1060            "fit on one line.\n"
1061            "*/",
1062            format("/*\n"
1063                   "This is a long                                         "
1064                   "comment that doesn't                                    "
1065                   "fit on one line.                                      \n"
1066                   "*/", getLLVMStyleWithColumns(20)));
1067  EXPECT_EQ("/*\n"
1068            " * This is a long\n"
1069            " * comment that\n"
1070            " * doesn't fit on\n"
1071            " * one line.\n"
1072            " */",
1073            format("/*      \n"
1074                   " * This is a long "
1075                   "   comment that     "
1076                   "   doesn't fit on   "
1077                   "   one line.                                            \n"
1078                   " */", getLLVMStyleWithColumns(20)));
1079  EXPECT_EQ("/*\n"
1080            " * This_is_a_comment_with_words_that_dont_fit_on_one_line\n"
1081            " * so_it_should_be_broken\n"
1082            " * wherever_a_space_occurs\n"
1083            " */",
1084            format("/*\n"
1085                   " * This_is_a_comment_with_words_that_dont_fit_on_one_line "
1086                   "   so_it_should_be_broken "
1087                   "   wherever_a_space_occurs                             \n"
1088                   " */",
1089                   getLLVMStyleWithColumns(20)));
1090  EXPECT_EQ("/*\n"
1091            " *    This_comment_can_not_be_broken_into_lines\n"
1092            " */",
1093            format("/*\n"
1094                   " *    This_comment_can_not_be_broken_into_lines\n"
1095                   " */",
1096                   getLLVMStyleWithColumns(20)));
1097  EXPECT_EQ("{\n"
1098            "  /*\n"
1099            "  This is another\n"
1100            "  long comment that\n"
1101            "  doesn't fit on one\n"
1102            "  line    1234567890\n"
1103            "  */\n"
1104            "}",
1105            format("{\n"
1106                   "/*\n"
1107                   "This is another     "
1108                   "  long comment that "
1109                   "  doesn't fit on one"
1110                   "  line    1234567890\n"
1111                   "*/\n"
1112                   "}", getLLVMStyleWithColumns(20)));
1113  EXPECT_EQ("{\n"
1114            "  /*\n"
1115            "   * This        i s\n"
1116            "   * another comment\n"
1117            "   * t hat  doesn' t\n"
1118            "   * fit on one l i\n"
1119            "   * n e\n"
1120            "   */\n"
1121            "}",
1122            format("{\n"
1123                   "/*\n"
1124                   " * This        i s"
1125                   "   another comment"
1126                   "   t hat  doesn' t"
1127                   "   fit on one l i"
1128                   "   n e\n"
1129                   " */\n"
1130                   "}", getLLVMStyleWithColumns(20)));
1131  EXPECT_EQ("/*\n"
1132            " * This is a long\n"
1133            " * comment that\n"
1134            " * doesn't fit on\n"
1135            " * one line\n"
1136            " */",
1137            format("   /*\n"
1138                   "    * This is a long comment that doesn't fit on one line\n"
1139                   "    */", getLLVMStyleWithColumns(20)));
1140  EXPECT_EQ("{\n"
1141            "  if (something) /* This is a\n"
1142            "                    long\n"
1143            "                    comment */\n"
1144            "    ;\n"
1145            "}",
1146            format("{\n"
1147                   "  if (something) /* This is a long comment */\n"
1148                   "    ;\n"
1149                   "}",
1150                   getLLVMStyleWithColumns(30)));
1151
1152  EXPECT_EQ("/* A comment before\n"
1153            " * a macro\n"
1154            " * definition */\n"
1155            "#define a b",
1156            format("/* A comment before a macro definition */\n"
1157                   "#define a b",
1158                   getLLVMStyleWithColumns(20)));
1159
1160  EXPECT_EQ("/* some comment\n"
1161            "     *   a comment\n"
1162            "* that we break\n"
1163            " * another comment\n"
1164            "* we have to break\n"
1165            "* a left comment\n"
1166            " */",
1167            format("  /* some comment\n"
1168                   "       *   a comment that we break\n"
1169                   "   * another comment we have to break\n"
1170                   "* a left comment\n"
1171                   "   */",
1172                   getLLVMStyleWithColumns(20)));
1173
1174  EXPECT_EQ("/*\n"
1175            "\n"
1176            "\n"
1177            "    */\n",
1178            format("  /*       \n"
1179                   "      \n"
1180                   "               \n"
1181                   "      */\n"));
1182}
1183
1184TEST_F(FormatTest, SplitsLongLinesInCommentsInPreprocessor) {
1185  EXPECT_EQ("#define X          \\\n"
1186            "  /*               \\\n"
1187            "   Test            \\\n"
1188            "   Macro comment   \\\n"
1189            "   with a long     \\\n"
1190            "   line            \\\n"
1191            "   */              \\\n"
1192            "  A + B",
1193            format("#define X \\\n"
1194                   "  /*\n"
1195                   "   Test\n"
1196                   "   Macro comment with a long  line\n"
1197                   "   */ \\\n"
1198                   "  A + B",
1199                   getLLVMStyleWithColumns(20)));
1200  EXPECT_EQ("#define X          \\\n"
1201            "  /* Macro comment \\\n"
1202            "     with a long   \\\n"
1203            "     line */       \\\n"
1204            "  A + B",
1205            format("#define X \\\n"
1206                   "  /* Macro comment with a long\n"
1207                   "     line */ \\\n"
1208                   "  A + B",
1209                   getLLVMStyleWithColumns(20)));
1210  EXPECT_EQ("#define X          \\\n"
1211            "  /* Macro comment \\\n"
1212            "   * with a long   \\\n"
1213            "   * line */       \\\n"
1214            "  A + B",
1215            format("#define X \\\n"
1216                   "  /* Macro comment with a long  line */ \\\n"
1217                   "  A + B",
1218                   getLLVMStyleWithColumns(20)));
1219}
1220
1221TEST_F(FormatTest, CommentsInStaticInitializers) {
1222  EXPECT_EQ(
1223      "static SomeType type = { aaaaaaaaaaaaaaaaaaaa, /* comment */\n"
1224      "                         aaaaaaaaaaaaaaaaaaaa /* comment */,\n"
1225      "                         /* comment */ aaaaaaaaaaaaaaaaaaaa,\n"
1226      "                         aaaaaaaaaaaaaaaaaaaa, // comment\n"
1227      "                         aaaaaaaaaaaaaaaaaaaa };",
1228      format("static SomeType type = { aaaaaaaaaaaaaaaaaaaa  ,  /* comment */\n"
1229             "                   aaaaaaaaaaaaaaaaaaaa   /* comment */ ,\n"
1230             "                     /* comment */   aaaaaaaaaaaaaaaaaaaa ,\n"
1231             "              aaaaaaaaaaaaaaaaaaaa ,   // comment\n"
1232             "                  aaaaaaaaaaaaaaaaaaaa };"));
1233  verifyFormat("static SomeType type = { aaaaaaaaaaa, // comment for aa...\n"
1234               "                         bbbbbbbbbbb, ccccccccccc };");
1235  verifyFormat("static SomeType type = { aaaaaaaaaaa,\n"
1236               "                         // comment for bb....\n"
1237               "                         bbbbbbbbbbb, ccccccccccc };");
1238  verifyGoogleFormat(
1239      "static SomeType type = {aaaaaaaaaaa,  // comment for aa...\n"
1240      "                        bbbbbbbbbbb, ccccccccccc};");
1241  verifyGoogleFormat("static SomeType type = {aaaaaaaaaaa,\n"
1242                     "                        // comment for bb....\n"
1243                     "                        bbbbbbbbbbb, ccccccccccc};");
1244
1245  verifyFormat("S s = { { a, b, c },   // Group #1\n"
1246               "        { d, e, f },   // Group #2\n"
1247               "        { g, h, i } }; // Group #3");
1248  verifyFormat("S s = { { // Group #1\n"
1249               "          a, b, c },\n"
1250               "        { // Group #2\n"
1251               "          d, e, f },\n"
1252               "        { // Group #3\n"
1253               "          g, h, i } };");
1254
1255  EXPECT_EQ("S s = {\n"
1256            "  // Some comment\n"
1257            "  a,\n"
1258            "\n"
1259            "  // Comment after empty line\n"
1260            "  b\n"
1261            "}",
1262            format("S s =    {\n"
1263                   "      // Some comment\n"
1264                   "  a,\n"
1265                   "  \n"
1266                   "     // Comment after empty line\n"
1267                   "      b\n"
1268                   "}"));
1269  EXPECT_EQ("S s = {\n"
1270            "  /* Some comment */\n"
1271            "  a,\n"
1272            "\n"
1273            "  /* Comment after empty line */\n"
1274            "  b\n"
1275            "}",
1276            format("S s =    {\n"
1277                   "      /* Some comment */\n"
1278                   "  a,\n"
1279                   "  \n"
1280                   "     /* Comment after empty line */\n"
1281                   "      b\n"
1282                   "}"));
1283  verifyFormat("const uint8_t aaaaaaaaaaaaaaaaaaaaaa[0] = {\n"
1284               "  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1285               "  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // comment\n"
1286               "  0x00, 0x00, 0x00, 0x00              // comment\n"
1287               "};");
1288}
1289
1290TEST_F(FormatTest, IgnoresIf0Contents) {
1291  EXPECT_EQ("#if 0\n"
1292            "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1293            "#endif\n"
1294            "void f() {}",
1295            format("#if 0\n"
1296                   "}{)(&*(^%%#%@! fsadj f;ldjs ,:;| <<<>>>][)(][\n"
1297                   "#endif\n"
1298                   "void f(  ) {  }"));
1299  EXPECT_EQ("#if false\n"
1300            "void f(  ) {  }\n"
1301            "#endif\n"
1302            "void g() {}\n",
1303            format("#if false\n"
1304                   "void f(  ) {  }\n"
1305                   "#endif\n"
1306                   "void g(  ) {  }\n"));
1307  EXPECT_EQ("enum E {\n"
1308            "  One,\n"
1309            "  Two,\n"
1310            "#if 0\n"
1311            "Three,\n"
1312            "      Four,\n"
1313            "#endif\n"
1314            "  Five\n"
1315            "};",
1316            format("enum E {\n"
1317                   "  One,Two,\n"
1318                   "#if 0\n"
1319                   "Three,\n"
1320                   "      Four,\n"
1321                   "#endif\n"
1322                   "  Five};"));
1323  EXPECT_EQ("enum F {\n"
1324            "  One,\n"
1325            "#if 1\n"
1326            "  Two,\n"
1327            "#if 0\n"
1328            "Three,\n"
1329            "      Four,\n"
1330            "#endif\n"
1331            "  Five\n"
1332            "#endif\n"
1333            "};",
1334            format("enum F {\n"
1335                   "One,\n"
1336                   "#if 1\n"
1337                   "Two,\n"
1338                   "#if 0\n"
1339                   "Three,\n"
1340                   "      Four,\n"
1341                   "#endif\n"
1342                   "Five\n"
1343                   "#endif\n"
1344                   "};"));
1345  EXPECT_EQ("enum G {\n"
1346            "  One,\n"
1347            "#if 0\n"
1348            "Two,\n"
1349            "#else\n"
1350            "  Three,\n"
1351            "#endif\n"
1352            "  Four\n"
1353            "};",
1354            format("enum G {\n"
1355                   "One,\n"
1356                   "#if 0\n"
1357                   "Two,\n"
1358                   "#else\n"
1359                   "Three,\n"
1360                   "#endif\n"
1361                   "Four\n"
1362                   "};"));
1363  EXPECT_EQ("enum H {\n"
1364            "  One,\n"
1365            "#if 0\n"
1366            "#ifdef Q\n"
1367            "Two,\n"
1368            "#else\n"
1369            "Three,\n"
1370            "#endif\n"
1371            "#endif\n"
1372            "  Four\n"
1373            "};",
1374            format("enum H {\n"
1375                   "One,\n"
1376                   "#if 0\n"
1377                   "#ifdef Q\n"
1378                   "Two,\n"
1379                   "#else\n"
1380                   "Three,\n"
1381                   "#endif\n"
1382                   "#endif\n"
1383                   "Four\n"
1384                   "};"));
1385  EXPECT_EQ("enum I {\n"
1386            "  One,\n"
1387            "#if /* test */ 0 || 1\n"
1388            "Two,\n"
1389            "Three,\n"
1390            "#endif\n"
1391            "  Four\n"
1392            "};",
1393            format("enum I {\n"
1394                   "One,\n"
1395                   "#if /* test */ 0 || 1\n"
1396                   "Two,\n"
1397                   "Three,\n"
1398                   "#endif\n"
1399                   "Four\n"
1400                   "};"));
1401  EXPECT_EQ("enum J {\n"
1402            "  One,\n"
1403            "#if 0\n"
1404            "#if 0\n"
1405            "Two,\n"
1406            "#else\n"
1407            "Three,\n"
1408            "#endif\n"
1409            "Four,\n"
1410            "#endif\n"
1411            "  Five\n"
1412            "};",
1413            format("enum J {\n"
1414                   "One,\n"
1415                   "#if 0\n"
1416                   "#if 0\n"
1417                   "Two,\n"
1418                   "#else\n"
1419                   "Three,\n"
1420                   "#endif\n"
1421                   "Four,\n"
1422                   "#endif\n"
1423                   "Five\n"
1424                   "};"));
1425
1426}
1427
1428//===----------------------------------------------------------------------===//
1429// Tests for classes, namespaces, etc.
1430//===----------------------------------------------------------------------===//
1431
1432TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1433  verifyFormat("class A {};");
1434}
1435
1436TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1437  verifyFormat("class A {\n"
1438               "public:\n"
1439               "public: // comment\n"
1440               "protected:\n"
1441               "private:\n"
1442               "  void f() {}\n"
1443               "};");
1444  verifyGoogleFormat("class A {\n"
1445                     " public:\n"
1446                     " protected:\n"
1447                     " private:\n"
1448                     "  void f() {}\n"
1449                     "};");
1450}
1451
1452TEST_F(FormatTest, SeparatesLogicalBlocks) {
1453  EXPECT_EQ("class A {\n"
1454            "public:\n"
1455            "  void f();\n"
1456            "\n"
1457            "private:\n"
1458            "  void g() {}\n"
1459            "  // test\n"
1460            "protected:\n"
1461            "  int h;\n"
1462            "};",
1463            format("class A {\n"
1464                   "public:\n"
1465                   "void f();\n"
1466                   "private:\n"
1467                   "void g() {}\n"
1468                   "// test\n"
1469                   "protected:\n"
1470                   "int h;\n"
1471                   "};"));
1472}
1473
1474TEST_F(FormatTest, FormatsClasses) {
1475  verifyFormat("class A : public B {};");
1476  verifyFormat("class A : public ::B {};");
1477
1478  verifyFormat(
1479      "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1480      "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1481  verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
1482               "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1483               "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1484  verifyFormat(
1485      "class A : public B, public C, public D, public E, public F {};");
1486  verifyFormat("class AAAAAAAAAAAA : public B,\n"
1487               "                     public C,\n"
1488               "                     public D,\n"
1489               "                     public E,\n"
1490               "                     public F,\n"
1491               "                     public G {};");
1492
1493  verifyFormat("class\n"
1494               "    ReallyReallyLongClassName {\n};",
1495               getLLVMStyleWithColumns(32));
1496}
1497
1498TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
1499  verifyFormat("class A {\n} a, b;");
1500  verifyFormat("struct A {\n} a, b;");
1501  verifyFormat("union A {\n} a;");
1502}
1503
1504TEST_F(FormatTest, FormatsEnum) {
1505  verifyFormat("enum {\n"
1506               "  Zero,\n"
1507               "  One = 1,\n"
1508               "  Two = One + 1,\n"
1509               "  Three = (One + Two),\n"
1510               "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1511               "  Five = (One, Two, Three, Four, 5)\n"
1512               "};");
1513  verifyFormat("enum Enum {};");
1514  verifyFormat("enum {};");
1515  verifyFormat("enum X E {\n} d;");
1516  verifyFormat("enum __attribute__((...)) E {\n} d;");
1517  verifyFormat("enum __declspec__((...)) E {\n} d;");
1518  verifyFormat("enum X f() {\n  a();\n  return 42;\n}");
1519}
1520
1521TEST_F(FormatTest, FormatsBitfields) {
1522  verifyFormat("struct Bitfields {\n"
1523               "  unsigned sClass : 8;\n"
1524               "  unsigned ValueKind : 2;\n"
1525               "};");
1526}
1527
1528TEST_F(FormatTest, FormatsNamespaces) {
1529  verifyFormat("namespace some_namespace {\n"
1530               "class A {};\n"
1531               "void f() { f(); }\n"
1532               "}");
1533  verifyFormat("namespace {\n"
1534               "class A {};\n"
1535               "void f() { f(); }\n"
1536               "}");
1537  verifyFormat("inline namespace X {\n"
1538               "class A {};\n"
1539               "void f() { f(); }\n"
1540               "}");
1541  verifyFormat("using namespace some_namespace;\n"
1542               "class A {};\n"
1543               "void f() { f(); }");
1544
1545  // This code is more common than we thought; if we
1546  // layout this correctly the semicolon will go into
1547  // its own line, which is undesireable.
1548  verifyFormat("namespace {};");
1549  verifyFormat("namespace {\n"
1550               "class A {};\n"
1551               "};");
1552
1553  verifyFormat("namespace {\n"
1554               "int SomeVariable = 0; // comment\n"
1555               "} // namespace");
1556  EXPECT_EQ("#ifndef HEADER_GUARD\n"
1557            "#define HEADER_GUARD\n"
1558            "namespace my_namespace {\n"
1559            "int i;\n"
1560            "} // my_namespace\n"
1561            "#endif // HEADER_GUARD",
1562            format("#ifndef HEADER_GUARD\n"
1563                   " #define HEADER_GUARD\n"
1564                   "   namespace my_namespace {\n"
1565                   "int i;\n"
1566                   "}    // my_namespace\n"
1567                   "#endif    // HEADER_GUARD"));
1568
1569  FormatStyle Style = getLLVMStyle();
1570  Style.NamespaceIndentation = FormatStyle::NI_All;
1571  EXPECT_EQ("namespace out {\n"
1572            "  int i;\n"
1573            "  namespace in {\n"
1574            "    int i;\n"
1575            "  } // namespace\n"
1576            "} // namespace",
1577            format("namespace out {\n"
1578                   "int i;\n"
1579                   "namespace in {\n"
1580                   "int i;\n"
1581                   "} // namespace\n"
1582                   "} // namespace",
1583                   Style));
1584
1585  Style.NamespaceIndentation = FormatStyle::NI_Inner;
1586  EXPECT_EQ("namespace out {\n"
1587            "int i;\n"
1588            "namespace in {\n"
1589            "  int i;\n"
1590            "} // namespace\n"
1591            "} // namespace",
1592            format("namespace out {\n"
1593                   "int i;\n"
1594                   "namespace in {\n"
1595                   "int i;\n"
1596                   "} // namespace\n"
1597                   "} // namespace",
1598                   Style));
1599}
1600
1601TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
1602
1603TEST_F(FormatTest, FormatsInlineASM) {
1604  verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
1605  verifyFormat(
1606      "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
1607      "    \"cpuid\\n\\t\"\n"
1608      "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
1609      "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
1610      "    : \"a\"(value));");
1611}
1612
1613TEST_F(FormatTest, FormatTryCatch) {
1614  // FIXME: Handle try-catch explicitly in the UnwrappedLineParser, then we'll
1615  // also not create single-line-blocks.
1616  verifyFormat("try {\n"
1617               "  throw a * b;\n"
1618               "}\n"
1619               "catch (int a) {\n"
1620               "  // Do nothing.\n"
1621               "}\n"
1622               "catch (...) {\n"
1623               "  exit(42);\n"
1624               "}");
1625
1626  // Function-level try statements.
1627  verifyFormat("int f() try { return 4; }\n"
1628               "catch (...) {\n"
1629               "  return 5;\n"
1630               "}");
1631  verifyFormat("class A {\n"
1632               "  int a;\n"
1633               "  A() try : a(0) {}\n"
1634               "  catch (...) {\n"
1635               "    throw;\n"
1636               "  }\n"
1637               "};\n");
1638}
1639
1640TEST_F(FormatTest, FormatObjCTryCatch) {
1641  verifyFormat("@try {\n"
1642               "  f();\n"
1643               "}\n"
1644               "@catch (NSException e) {\n"
1645               "  @throw;\n"
1646               "}\n"
1647               "@finally {\n"
1648               "  exit(42);\n"
1649               "}");
1650}
1651
1652TEST_F(FormatTest, StaticInitializers) {
1653  verifyFormat("static SomeClass SC = { 1, 'a' };");
1654
1655  verifyFormat(
1656      "static SomeClass WithALoooooooooooooooooooongName = {\n"
1657      "  100000000, \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
1658      "};");
1659
1660  verifyFormat(
1661      "static SomeClass = { a, b, c, d, e, f, g, h, i, j,\n"
1662      "                     looooooooooooooooooooooooooooooooooongname,\n"
1663      "                     looooooooooooooooooooooooooooooong };");
1664  // Allow bin-packing in static initializers as this would often lead to
1665  // terrible results, e.g.:
1666  verifyGoogleFormat(
1667      "static SomeClass = {a, b, c, d, e, f, g, h, i, j,\n"
1668      "                    looooooooooooooooooooooooooooooooooongname,\n"
1669      "                    looooooooooooooooooooooooooooooong};");
1670  // Here, everything other than the "}" would fit on a line.
1671  verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
1672               "  100000000000000000000000\n"
1673               "};");
1674  EXPECT_EQ("S s = { a, b };", format("S s = {\n"
1675                                      "  a,\n"
1676                                      "\n"
1677                                      "  b\n"
1678                                      "};"));
1679
1680  // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
1681  // line. However, the formatting looks a bit off and this probably doesn't
1682  // happen often in practice.
1683  verifyFormat("static int Variable[1] = {\n"
1684               "  { 1000000000000000000000000000000000000 }\n"
1685               "};",
1686               getLLVMStyleWithColumns(40));
1687}
1688
1689TEST_F(FormatTest, DesignatedInitializers) {
1690  verifyFormat("const struct A a = { .a = 1, .b = 2 };");
1691  verifyFormat("const struct A a = { .aaaaaaaaaa = 1,\n"
1692               "                     .bbbbbbbbbb = 2,\n"
1693               "                     .cccccccccc = 3,\n"
1694               "                     .dddddddddd = 4,\n"
1695               "                     .eeeeeeeeee = 5 };");
1696  verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
1697               "  .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
1698               "  .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
1699               "  .ccccccccccccccccccccccccccc = 3,\n"
1700               "  .ddddddddddddddddddddddddddd = 4,\n"
1701               "  .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5\n"
1702               "};");
1703
1704  verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
1705}
1706
1707TEST_F(FormatTest, NestedStaticInitializers) {
1708  verifyFormat("static A x = { { {} } };\n");
1709  verifyFormat("static A x = { { { init1, init2, init3, init4 },\n"
1710               "                 { init1, init2, init3, init4 } } };");
1711
1712  verifyFormat("somes Status::global_reps[3] = {\n"
1713               "  { kGlobalRef, OK_CODE, NULL, NULL, NULL },\n"
1714               "  { kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL },\n"
1715               "  { kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL }\n"
1716               "};");
1717  verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
1718                     "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
1719                     "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
1720                     "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
1721  verifyFormat(
1722      "CGRect cg_rect = { { rect.fLeft, rect.fTop },\n"
1723      "                   { rect.fRight - rect.fLeft, rect.fBottom - rect.fTop"
1724      " } };");
1725
1726  verifyFormat(
1727      "SomeArrayOfSomeType a = { { { 1, 2, 3 }, { 1, 2, 3 },\n"
1728      "                            { 111111111111111111111111111111,\n"
1729      "                              222222222222222222222222222222,\n"
1730      "                              333333333333333333333333333333 },\n"
1731      "                            { 1, 2, 3 }, { 1, 2, 3 } } };");
1732  verifyFormat(
1733      "SomeArrayOfSomeType a = { { { 1, 2, 3 } }, { { 1, 2, 3 } },\n"
1734      "                          { { 111111111111111111111111111111,\n"
1735      "                              222222222222222222222222222222,\n"
1736      "                              333333333333333333333333333333 } },\n"
1737      "                          { { 1, 2, 3 } }, { { 1, 2, 3 } } };");
1738  verifyGoogleFormat(
1739      "SomeArrayOfSomeType a = {\n"
1740      "    {{1, 2, 3}}, {{1, 2, 3}},\n"
1741      "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
1742      "      333333333333333333333333333333}},\n"
1743      "    {{1, 2, 3}}, {{1, 2, 3}}};");
1744
1745  // FIXME: We might at some point want to handle this similar to parameter
1746  // lists, where we have an option to put each on a single line.
1747  verifyFormat(
1748      "struct {\n"
1749      "  unsigned bit;\n"
1750      "  const char *const name;\n"
1751      "} kBitsToOs[] = { { kOsMac, \"Mac\" }, { kOsWin, \"Windows\" },\n"
1752      "                  { kOsLinux, \"Linux\" }, { kOsCrOS, \"Chrome OS\" } };");
1753}
1754
1755TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
1756  verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
1757               "                      \\\n"
1758               "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
1759}
1760
1761TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
1762  verifyFormat(
1763      "virtual void write(ELFWriter *writerrr,\n"
1764      "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
1765}
1766
1767TEST_F(FormatTest, LayoutUnknownPPDirective) {
1768  EXPECT_EQ("#123 \"A string literal\"",
1769            format("   #     123    \"A string literal\""));
1770  EXPECT_EQ("#;", format("#;"));
1771  verifyFormat("#\n;\n;\n;");
1772}
1773
1774TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
1775  EXPECT_EQ("#line 42 \"test\"\n",
1776            format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
1777  EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
1778                                    getLLVMStyleWithColumns(12)));
1779}
1780
1781TEST_F(FormatTest, EndOfFileEndsPPDirective) {
1782  EXPECT_EQ("#line 42 \"test\"",
1783            format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
1784  EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
1785}
1786
1787TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
1788  verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
1789  verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
1790  verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
1791  // FIXME: We never break before the macro name.
1792  verifyFormat("#define AA(\\\n    B)", getLLVMStyleWithColumns(12));
1793
1794  verifyFormat("#define A A\n#define A A");
1795  verifyFormat("#define A(X) A\n#define A A");
1796
1797  verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
1798  verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
1799}
1800
1801TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
1802  EXPECT_EQ("// somecomment\n"
1803            "#include \"a.h\"\n"
1804            "#define A(  \\\n"
1805            "    A, B)\n"
1806            "#include \"b.h\"\n"
1807            "// somecomment\n",
1808            format("  // somecomment\n"
1809                   "  #include \"a.h\"\n"
1810                   "#define A(A,\\\n"
1811                   "    B)\n"
1812                   "    #include \"b.h\"\n"
1813                   " // somecomment\n",
1814                   getLLVMStyleWithColumns(13)));
1815}
1816
1817TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
1818
1819TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
1820  EXPECT_EQ("#define A    \\\n"
1821            "  c;         \\\n"
1822            "  e;\n"
1823            "f;",
1824            format("#define A c; e;\n"
1825                   "f;",
1826                   getLLVMStyleWithColumns(14)));
1827}
1828
1829TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
1830
1831TEST_F(FormatTest, AlwaysFormatsEntireMacroDefinitions) {
1832  EXPECT_EQ("int  i;\n"
1833            "#define A \\\n"
1834            "  int i;  \\\n"
1835            "  int j\n"
1836            "int  k;",
1837            format("int  i;\n"
1838                   "#define A  \\\n"
1839                   " int   i    ;  \\\n"
1840                   " int   j\n"
1841                   "int  k;",
1842                   8, 0, getGoogleStyle())); // 8: position of "#define".
1843  EXPECT_EQ("int  i;\n"
1844            "#define A \\\n"
1845            "  int i;  \\\n"
1846            "  int j\n"
1847            "int  k;",
1848            format("int  i;\n"
1849                   "#define A  \\\n"
1850                   " int   i    ;  \\\n"
1851                   " int   j\n"
1852                   "int  k;",
1853                   45, 0, getGoogleStyle())); // 45: position of "j".
1854}
1855
1856TEST_F(FormatTest, MacroDefinitionInsideStatement) {
1857  EXPECT_EQ("int x,\n"
1858            "#define A\n"
1859            "    y;",
1860            format("int x,\n#define A\ny;"));
1861}
1862
1863TEST_F(FormatTest, HashInMacroDefinition) {
1864  verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
1865  verifyFormat("#define A \\\n"
1866               "  {       \\\n"
1867               "    f(#c);\\\n"
1868               "  }",
1869               getLLVMStyleWithColumns(11));
1870
1871  verifyFormat("#define A(X)         \\\n"
1872               "  void function##X()",
1873               getLLVMStyleWithColumns(22));
1874
1875  verifyFormat("#define A(a, b, c)   \\\n"
1876               "  void a##b##c()",
1877               getLLVMStyleWithColumns(22));
1878
1879  verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
1880}
1881
1882TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
1883  verifyFormat("#define A (1)");
1884}
1885
1886TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
1887  EXPECT_EQ("#define A b;", format("#define A \\\n"
1888                                   "          \\\n"
1889                                   "  b;",
1890                                   getLLVMStyleWithColumns(25)));
1891  EXPECT_EQ("#define A \\\n"
1892            "          \\\n"
1893            "  a;      \\\n"
1894            "  b;",
1895            format("#define A \\\n"
1896                   "          \\\n"
1897                   "  a;      \\\n"
1898                   "  b;",
1899                   getLLVMStyleWithColumns(11)));
1900  EXPECT_EQ("#define A \\\n"
1901            "  a;      \\\n"
1902            "          \\\n"
1903            "  b;",
1904            format("#define A \\\n"
1905                   "  a;      \\\n"
1906                   "          \\\n"
1907                   "  b;",
1908                   getLLVMStyleWithColumns(11)));
1909}
1910
1911TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
1912  verifyFormat("#define A :");
1913  verifyFormat("#define SOMECASES  \\\n"
1914               "  case 1:          \\\n"
1915               "  case 2\n",
1916               getLLVMStyleWithColumns(20));
1917  verifyFormat("#define A template <typename T>");
1918  verifyFormat("#define STR(x) #x\n"
1919               "f(STR(this_is_a_string_literal{));");
1920}
1921
1922TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
1923  verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
1924  EXPECT_EQ("class A : public QObject {\n"
1925            "  Q_OBJECT\n"
1926            "\n"
1927            "  A() {}\n"
1928            "};",
1929            format("class A  :  public QObject {\n"
1930                   "     Q_OBJECT\n"
1931                   "\n"
1932                   "  A() {\n}\n"
1933                   "}  ;"));
1934  EXPECT_EQ("SOME_MACRO\n"
1935            "namespace {\n"
1936            "void f();\n"
1937            "}",
1938            format("SOME_MACRO\n"
1939                   "  namespace    {\n"
1940                   "void   f(  );\n"
1941                   "}"));
1942  // Only if the identifier contains at least 5 characters.
1943  EXPECT_EQ("HTTP f();",
1944            format("HTTP\nf();"));
1945  EXPECT_EQ("MACRO\nf();",
1946            format("MACRO\nf();"));
1947  // Only if everything is upper case.
1948  EXPECT_EQ("class A : public QObject {\n"
1949            "  Q_Object A() {}\n"
1950            "};",
1951            format("class A  :  public QObject {\n"
1952                   "     Q_Object\n"
1953                   "\n"
1954                   "  A() {\n}\n"
1955                   "}  ;"));
1956}
1957
1958TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
1959  EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
1960            "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
1961            "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
1962            "class X {};\n"
1963            "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
1964            "int *createScopDetectionPass() { return 0; }",
1965            format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
1966                   "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
1967                   "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
1968                   "  class X {};\n"
1969                   "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
1970                   "  int *createScopDetectionPass() { return 0; }"));
1971  // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
1972  // braces, so that inner block is indented one level more.
1973  EXPECT_EQ("int q() {\n"
1974            "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
1975            "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
1976            "  IPC_END_MESSAGE_MAP()\n"
1977            "}",
1978            format("int q() {\n"
1979                   "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
1980                   "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
1981                   "  IPC_END_MESSAGE_MAP()\n"
1982                   "}"));
1983  EXPECT_EQ("int q() {\n"
1984            "  f(x);\n"
1985            "  f(x) {}\n"
1986            "  f(x)->g();\n"
1987            "  f(x)->*g();\n"
1988            "  f(x).g();\n"
1989            "  f(x) = x;\n"
1990            "  f(x) += x;\n"
1991            "  f(x) -= x;\n"
1992            "  f(x) *= x;\n"
1993            "  f(x) /= x;\n"
1994            "  f(x) %= x;\n"
1995            "  f(x) &= x;\n"
1996            "  f(x) |= x;\n"
1997            "  f(x) ^= x;\n"
1998            "  f(x) >>= x;\n"
1999            "  f(x) <<= x;\n"
2000            "  f(x)[y].z();\n"
2001            "  LOG(INFO) << x;\n"
2002            "  ifstream(x) >> x;\n"
2003            "}\n",
2004            format("int q() {\n"
2005                   "  f(x)\n;\n"
2006                   "  f(x)\n {}\n"
2007                   "  f(x)\n->g();\n"
2008                   "  f(x)\n->*g();\n"
2009                   "  f(x)\n.g();\n"
2010                   "  f(x)\n = x;\n"
2011                   "  f(x)\n += x;\n"
2012                   "  f(x)\n -= x;\n"
2013                   "  f(x)\n *= x;\n"
2014                   "  f(x)\n /= x;\n"
2015                   "  f(x)\n %= x;\n"
2016                   "  f(x)\n &= x;\n"
2017                   "  f(x)\n |= x;\n"
2018                   "  f(x)\n ^= x;\n"
2019                   "  f(x)\n >>= x;\n"
2020                   "  f(x)\n <<= x;\n"
2021                   "  f(x)\n[y].z();\n"
2022                   "  LOG(INFO)\n << x;\n"
2023                   "  ifstream(x)\n >> x;\n"
2024                   "}\n"));
2025  EXPECT_EQ("int q() {\n"
2026            "  f(x)\n"
2027            "  if (1) {\n"
2028            "  }\n"
2029            "  f(x)\n"
2030            "  while (1) {\n"
2031            "  }\n"
2032            "  f(x)\n"
2033            "  g(x);\n"
2034            "  f(x)\n"
2035            "  try {\n"
2036            "    q();\n"
2037            "  }\n"
2038            "  catch (...) {\n"
2039            "  }\n"
2040            "}\n",
2041            format("int q() {\n"
2042                   "f(x)\n"
2043                   "if (1) {}\n"
2044                   "f(x)\n"
2045                   "while (1) {}\n"
2046                   "f(x)\n"
2047                   "g(x);\n"
2048                   "f(x)\n"
2049                   "try { q(); } catch (...) {}\n"
2050                   "}\n"));
2051  EXPECT_EQ("class A {\n"
2052            "  A() : t(0) {}\n"
2053            "  A(X x)\n" // FIXME: function-level try blocks are broken.
2054            "  try : t(0) {\n"
2055            "  }\n"
2056            "  catch (...) {\n"
2057            "  }\n"
2058            "};",
2059            format("class A {\n"
2060                   "  A()\n : t(0) {}\n"
2061                   "  A(X x)\n"
2062                   "  try : t(0) {} catch (...) {}\n"
2063                   "};"));
2064}
2065
2066TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
2067  verifyFormat("#define A \\\n"
2068               "  f({     \\\n"
2069               "    g();  \\\n"
2070               "  });", getLLVMStyleWithColumns(11));
2071}
2072
2073TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
2074  EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
2075}
2076
2077TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
2078  verifyFormat("{\n  { a #c; }\n}");
2079}
2080
2081TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
2082  EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
2083            format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
2084  EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
2085            format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
2086}
2087
2088TEST_F(FormatTest, EscapedNewlineAtStartOfToken) {
2089  EXPECT_EQ(
2090      "#define A \\\n  int i;  \\\n  int j;",
2091      format("#define A \\\nint i;\\\n  int j;", getLLVMStyleWithColumns(11)));
2092  EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
2093}
2094
2095TEST_F(FormatTest, NoEscapedNewlineHandlingInBlockComments) {
2096  EXPECT_EQ("/* \\  \\  \\\n*/", format("\\\n/* \\  \\  \\\n*/"));
2097}
2098
2099TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
2100  verifyFormat("#define A \\\n"
2101               "  int v(  \\\n"
2102               "      a); \\\n"
2103               "  int i;",
2104               getLLVMStyleWithColumns(11));
2105}
2106
2107TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
2108  EXPECT_EQ(
2109      "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
2110      "                      \\\n"
2111      "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
2112      "\n"
2113      "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
2114      "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
2115      format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
2116             "\\\n"
2117             "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
2118             "  \n"
2119             "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
2120             "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
2121}
2122
2123TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
2124  EXPECT_EQ("int\n"
2125            "#define A\n"
2126            "    a;",
2127            format("int\n#define A\na;", getGoogleStyle()));
2128  verifyFormat("functionCallTo(\n"
2129               "    someOtherFunction(\n"
2130               "        withSomeParameters, whichInSequence,\n"
2131               "        areLongerThanALine(andAnotherCall,\n"
2132               "#define A B\n"
2133               "                           withMoreParamters,\n"
2134               "                           whichStronglyInfluenceTheLayout),\n"
2135               "        andMoreParameters),\n"
2136               "    trailing);",
2137               getLLVMStyleWithColumns(69));
2138}
2139
2140TEST_F(FormatTest, LayoutBlockInsideParens) {
2141  EXPECT_EQ("functionCall({\n"
2142            "  int i;\n"
2143            "});",
2144            format(" functionCall ( {int i;} );"));
2145
2146  // FIXME: This is bad, find a better and more generic solution.
2147  EXPECT_EQ("functionCall({\n"
2148            "  int i;\n"
2149            "},\n"
2150            "             aaaa, bbbb, cccc);",
2151            format(" functionCall ( {int i;},  aaaa,   bbbb, cccc);"));
2152  verifyFormat(
2153      "Aaa({\n"
2154      "  int i;\n"
2155      "},\n"
2156      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
2157      "                                     ccccccccccccccccc));");
2158}
2159
2160TEST_F(FormatTest, LayoutBlockInsideStatement) {
2161  EXPECT_EQ("SOME_MACRO { int i; }\n"
2162            "int i;",
2163            format("  SOME_MACRO  {int i;}  int i;"));
2164}
2165
2166TEST_F(FormatTest, LayoutNestedBlocks) {
2167  verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
2168               "  struct s {\n"
2169               "    int i;\n"
2170               "  };\n"
2171               "  s kBitsToOs[] = { { 10 } };\n"
2172               "  for (int i = 0; i < 10; ++i)\n"
2173               "    return;\n"
2174               "}");
2175}
2176
2177TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
2178  EXPECT_EQ("{}", format("{}"));
2179  verifyFormat("enum E {};");
2180  verifyFormat("enum E {}");
2181}
2182
2183//===----------------------------------------------------------------------===//
2184// Line break tests.
2185//===----------------------------------------------------------------------===//
2186
2187TEST_F(FormatTest, FormatsAwesomeMethodCall) {
2188  verifyFormat(
2189      "SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
2190      "                       parameter, parameter, parameter)),\n"
2191      "                   SecondLongCall(parameter));");
2192}
2193
2194TEST_F(FormatTest, PreventConfusingIndents) {
2195  verifyFormat(
2196      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2197      "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
2198      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2199      "    aaaaaaaaaaaaaaaaaaaaaaaa);");
2200  verifyFormat(
2201      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2202      "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
2203      "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
2204      "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
2205  verifyFormat(
2206      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
2207      "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
2208      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
2209      "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
2210  verifyFormat("int a = bbbb && ccc && fffff(\n"
2211               "#define A Just forcing a new line\n"
2212               "                           ddd);");
2213}
2214
2215TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
2216  verifyFormat(
2217      "bool aaaaaaa =\n"
2218      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
2219      "    bbbbbbbb();");
2220  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
2221               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
2222               "    ccccccccc == ddddddddddd;");
2223
2224  verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
2225               "                 aaaaaa) &&\n"
2226               "         bbbbbb && cccccc;");
2227  verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
2228               "                 aaaaaa) >>\n"
2229               "         bbbbbb;");
2230  verifyFormat("Whitespaces.addUntouchableComment(\n"
2231               "    SourceMgr.getSpellingColumnNumber(\n"
2232               "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
2233               "    1);");
2234
2235  verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2236               "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
2237               "    cccccc) {\n}");
2238
2239  // If the LHS of a comparison is not a binary expression itself, the
2240  // additional linebreak confuses many people.
2241  verifyFormat(
2242      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2243      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
2244      "}");
2245  verifyFormat(
2246      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2247      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
2248      "}");
2249  // Even explicit parentheses stress the precedence enough to make the
2250  // additional break unnecessary.
2251  verifyFormat(
2252      "if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2253      "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
2254      "}");
2255  // This cases is borderline, but with the indentation it is still readable.
2256  verifyFormat(
2257      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2258      "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2259      "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2260      "}",
2261      getLLVMStyleWithColumns(75));
2262
2263  // If the LHS is a binary expression, we should still use the additional break
2264  // as otherwise the formatting hides the operator precedence.
2265  verifyFormat(
2266      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2267      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2268      "    5) {\n"
2269      "}");
2270
2271  FormatStyle OnePerLine = getLLVMStyle();
2272  OnePerLine.BinPackParameters = false;
2273  verifyFormat(
2274      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2275      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2276      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
2277      OnePerLine);
2278}
2279
2280TEST_F(FormatTest, ExpressionIndentation) {
2281  verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2282               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2283               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2284               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2285               "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
2286               "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
2287               "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2288               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
2289               "                 ccccccccccccccccccccccccccccccccccccccccc;");
2290  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2291               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2292               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2293               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2294  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2295               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2296               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2297               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2298  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2299               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2300               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2301               "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2302  verifyFormat("if () {\n"
2303               "} else if (aaaaa && bbbbb > // break\n"
2304               "                        ccccc) {\n"
2305               "}");
2306
2307  // Presence of a trailing comment used to change indentation of b.
2308  verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
2309               "       b;\n"
2310               "return aaaaaaaaaaaaaaaaaaa +\n"
2311               "       b; //",
2312               getLLVMStyleWithColumns(30));
2313}
2314
2315TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
2316  // Not sure what the best system is here. Like this, the LHS can be found
2317  // immediately above an operator (everything with the same or a higher
2318  // indent). The RHS is aligned right of the operator and so compasses
2319  // everything until something with the same indent as the operator is found.
2320  // FIXME: Is this a good system?
2321  FormatStyle Style = getLLVMStyle();
2322  Style.BreakBeforeBinaryOperators = true;
2323  verifyFormat(
2324      "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2325      "             + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2326      "             + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2327      "             == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2328      "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
2329      "                + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
2330      "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2331      "                * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2332      "                > ccccccccccccccccccccccccccccccccccccccccc;",
2333      Style);
2334  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2335               "    * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2336               "    + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2337               "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
2338               Style);
2339  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2340               "    + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2341               "      * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2342               "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
2343               Style);
2344  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2345               "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2346               "       * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2347               "       + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
2348               Style);
2349  verifyFormat("if () {\n"
2350               "} else if (aaaaa && bbbbb // break\n"
2351               "                    > ccccc) {\n"
2352               "}",
2353               Style);
2354}
2355
2356TEST_F(FormatTest, ConstructorInitializers) {
2357  verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
2358  verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
2359               getLLVMStyleWithColumns(45));
2360  verifyFormat("Constructor()\n"
2361               "    : Inttializer(FitsOnTheLine) {}",
2362               getLLVMStyleWithColumns(44));
2363  verifyFormat("Constructor()\n"
2364               "    : Inttializer(FitsOnTheLine) {}",
2365               getLLVMStyleWithColumns(43));
2366
2367  verifyFormat(
2368      "SomeClass::Constructor()\n"
2369      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
2370
2371  verifyFormat(
2372      "SomeClass::Constructor()\n"
2373      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2374      "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
2375  verifyFormat(
2376      "SomeClass::Constructor()\n"
2377      "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2378      "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
2379
2380  verifyFormat("Constructor()\n"
2381               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2382               "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2383               "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2384               "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
2385
2386  verifyFormat("Constructor()\n"
2387               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2388               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2389
2390  verifyFormat("Constructor(int Parameter = 0)\n"
2391               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
2392               "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
2393
2394  // Here a line could be saved by splitting the second initializer onto two
2395  // lines, but that is not desireable.
2396  verifyFormat("Constructor()\n"
2397               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
2398               "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
2399               "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2400
2401  FormatStyle OnePerLine = getLLVMStyle();
2402  OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
2403  verifyFormat("SomeClass::Constructor()\n"
2404               "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2405               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2406               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
2407               OnePerLine);
2408  verifyFormat("SomeClass::Constructor()\n"
2409               "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
2410               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2411               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
2412               OnePerLine);
2413  verifyFormat("MyClass::MyClass(int var)\n"
2414               "    : some_var_(var),            // 4 space indent\n"
2415               "      some_other_var_(var + 1) { // lined up\n"
2416               "}",
2417               OnePerLine);
2418  verifyFormat("Constructor()\n"
2419               "    : aaaaa(aaaaaa),\n"
2420               "      aaaaa(aaaaaa),\n"
2421               "      aaaaa(aaaaaa),\n"
2422               "      aaaaa(aaaaaa),\n"
2423               "      aaaaa(aaaaaa) {}",
2424               OnePerLine);
2425  verifyFormat("Constructor()\n"
2426               "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
2427               "            aaaaaaaaaaaaaaaaaaaaaa) {}",
2428               OnePerLine);
2429}
2430
2431TEST_F(FormatTest, MemoizationTests) {
2432  // This breaks if the memoization lookup does not take \c Indent and
2433  // \c LastSpace into account.
2434  verifyFormat(
2435      "extern CFRunLoopTimerRef\n"
2436      "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
2437      "                     CFTimeInterval interval, CFOptionFlags flags,\n"
2438      "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
2439      "                     CFRunLoopTimerContext *context) {}");
2440
2441  // Deep nesting somewhat works around our memoization.
2442  verifyFormat(
2443      "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2444      "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2445      "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2446      "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2447      "                aaaaa())))))))))))))))))))))))))))))))))))))));",
2448      getLLVMStyleWithColumns(65));
2449  verifyFormat(
2450      "aaaaa(\n"
2451      "    aaaaa,\n"
2452      "    aaaaa(\n"
2453      "        aaaaa,\n"
2454      "        aaaaa(\n"
2455      "            aaaaa,\n"
2456      "            aaaaa(\n"
2457      "                aaaaa,\n"
2458      "                aaaaa(\n"
2459      "                    aaaaa,\n"
2460      "                    aaaaa(\n"
2461      "                        aaaaa,\n"
2462      "                        aaaaa(\n"
2463      "                            aaaaa,\n"
2464      "                            aaaaa(\n"
2465      "                                aaaaa,\n"
2466      "                                aaaaa(\n"
2467      "                                    aaaaa,\n"
2468      "                                    aaaaa(\n"
2469      "                                        aaaaa,\n"
2470      "                                        aaaaa(\n"
2471      "                                            aaaaa,\n"
2472      "                                            aaaaa(\n"
2473      "                                                aaaaa,\n"
2474      "                                                aaaaa))))))))))));",
2475      getLLVMStyleWithColumns(65));
2476  verifyFormat(
2477      "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"
2478      "                                  a),\n"
2479      "                                a),\n"
2480      "                              a),\n"
2481      "                            a),\n"
2482      "                          a),\n"
2483      "                        a),\n"
2484      "                      a),\n"
2485      "                    a),\n"
2486      "                  a),\n"
2487      "                a),\n"
2488      "              a),\n"
2489      "            a),\n"
2490      "          a),\n"
2491      "        a),\n"
2492      "      a),\n"
2493      "    a),\n"
2494      "  a)",
2495      getLLVMStyleWithColumns(65));
2496
2497  // This test takes VERY long when memoization is broken.
2498  FormatStyle OnePerLine = getLLVMStyle();
2499  OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
2500  OnePerLine.BinPackParameters = false;
2501  std::string input = "Constructor()\n"
2502                      "    : aaaa(a,\n";
2503  for (unsigned i = 0, e = 80; i != e; ++i) {
2504    input += "           a,\n";
2505  }
2506  input += "           a) {}";
2507  verifyFormat(input, OnePerLine);
2508}
2509
2510TEST_F(FormatTest, BreaksAsHighAsPossible) {
2511  verifyFormat(
2512      "void f() {\n"
2513      "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
2514      "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
2515      "    f();\n"
2516      "}");
2517  verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
2518               "    Intervals[i - 1].getRange().getLast()) {\n}");
2519}
2520
2521TEST_F(FormatTest, BreaksFunctionDeclarations) {
2522  // Principially, we break function declarations in a certain order:
2523  // 1) break amongst arguments.
2524  verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
2525               "                              Cccccccccccccc cccccccccccccc);");
2526
2527  // 2) break after return type.
2528  verifyFormat(
2529      "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2530      "    bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
2531      getGoogleStyle());
2532
2533  // 3) break after (.
2534  verifyFormat(
2535      "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
2536      "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
2537      getGoogleStyle());
2538
2539  // 4) break before after nested name specifiers.
2540  verifyFormat(
2541      "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2542      "    SomeClasssssssssssssssssssssssssssssssssssssss::\n"
2543      "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
2544      getGoogleStyle());
2545
2546  // However, there are exceptions, if a sufficient amount of lines can be
2547  // saved.
2548  // FIXME: The precise cut-offs wrt. the number of saved lines might need some
2549  // more adjusting.
2550  verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
2551               "                                  Cccccccccccccc cccccccccc,\n"
2552               "                                  Cccccccccccccc cccccccccc,\n"
2553               "                                  Cccccccccccccc cccccccccc,\n"
2554               "                                  Cccccccccccccc cccccccccc);");
2555  verifyFormat(
2556      "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2557      "    bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2558      "                Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2559      "                Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
2560      getGoogleStyle());
2561  verifyFormat(
2562      "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
2563      "                                          Cccccccccccccc cccccccccc,\n"
2564      "                                          Cccccccccccccc cccccccccc,\n"
2565      "                                          Cccccccccccccc cccccccccc,\n"
2566      "                                          Cccccccccccccc cccccccccc,\n"
2567      "                                          Cccccccccccccc cccccccccc,\n"
2568      "                                          Cccccccccccccc cccccccccc);");
2569  verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
2570               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2571               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2572               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2573               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
2574
2575  // Break after multi-line parameters.
2576  verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2577               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2578               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2579               "    bbbb bbbb);");
2580
2581  // Treat overloaded operators like other functions.
2582  verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
2583               "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
2584  verifyGoogleFormat(
2585      "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
2586      "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
2587}
2588
2589TEST_F(FormatTest, TrailingReturnType) {
2590  verifyFormat("auto foo() -> int;\n");
2591  verifyFormat("struct S {\n"
2592               "  auto bar() const -> int;\n"
2593               "};");
2594  verifyFormat("template <size_t Order, typename T>\n"
2595               "auto load_img(const std::string &filename)\n"
2596               "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
2597
2598  // Not trailing return types.
2599  verifyFormat("void f() { auto a = b->c(); }");
2600}
2601
2602TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
2603  // Avoid breaking before trailing 'const'.
2604  verifyFormat("void someLongFunction(\n"
2605               "    int someLongParameter) const {}",
2606               getLLVMStyleWithColumns(46));
2607  FormatStyle Style = getGoogleStyle();
2608  Style.ColumnLimit = 47;
2609  verifyFormat("void\n"
2610               "someLongFunction(int someLongParameter) const {\n}",
2611               getLLVMStyleWithColumns(47));
2612  verifyFormat("void someLongFunction(\n"
2613               "    int someLongParameter) const {}",
2614               Style);
2615  verifyFormat("LoooooongReturnType\n"
2616               "someLoooooooongFunction() const {}",
2617               getLLVMStyleWithColumns(47));
2618  verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
2619               "    const {}",
2620               Style);
2621
2622  // Avoid breaking before other trailing annotations, if they are not
2623  // function-like.
2624  verifyFormat("void SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2625               "                  aaaaaaaaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
2626
2627  // Breaking before function-like trailing annotations is fine to keep them
2628  // close to their arguments.
2629  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2630               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
2631  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
2632               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
2633  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
2634               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
2635
2636  verifyFormat(
2637      "void aaaaaaaaaaaaaaaaaa()\n"
2638      "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
2639      "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
2640  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2641               "    __attribute__((unused));");
2642  verifyFormat(
2643      "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2644      "    GUARDED_BY(aaaaaaaaaaaa);",
2645      getGoogleStyle());
2646  verifyFormat(
2647      "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2648      "    GUARDED_BY(aaaaaaaaaaaa);",
2649      getGoogleStyle());
2650}
2651
2652TEST_F(FormatTest, BreaksDesireably) {
2653  verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
2654               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
2655               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
2656  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2657               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2658               "}");
2659
2660  verifyFormat(
2661      "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2662      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2663
2664  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2665               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2666               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2667
2668  verifyFormat(
2669      "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2670      "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
2671      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2672      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
2673
2674  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2675               "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2676
2677  verifyFormat(
2678      "void f() {\n"
2679      "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
2680      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2681      "}");
2682  verifyFormat(
2683      "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2684      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2685  verifyFormat(
2686      "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2687      "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2688  verifyFormat(
2689      "aaaaaaaaaaaaaaaaa(\n"
2690      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2691      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2692
2693  // This test case breaks on an incorrect memoization, i.e. an optimization not
2694  // taking into account the StopAt value.
2695  verifyFormat(
2696      "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2697      "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2698      "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2699      "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2700
2701  verifyFormat("{\n  {\n    {\n"
2702               "      Annotation.SpaceRequiredBefore =\n"
2703               "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
2704               "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
2705               "    }\n  }\n}");
2706
2707  // Break on an outer level if there was a break on an inner level.
2708  EXPECT_EQ("f(g(h(a, // comment\n"
2709            "      b, c),\n"
2710            "    d, e),\n"
2711            "  x, y);",
2712            format("f(g(h(a, // comment\n"
2713                   "    b, c), d, e), x, y);"));
2714
2715  // Prefer breaking similar line breaks.
2716  verifyFormat(
2717      "const int kTrackingOptions = NSTrackingMouseMoved |\n"
2718      "                             NSTrackingMouseEnteredAndExited |\n"
2719      "                             NSTrackingActiveAlways;");
2720}
2721
2722TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
2723  FormatStyle NoBinPacking = getGoogleStyle();
2724  NoBinPacking.BinPackParameters = false;
2725  verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
2726               "  aaaaaaaaaaaaaaaaaaaa,\n"
2727               "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
2728               NoBinPacking);
2729  verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
2730               "        aaaaaaaaaaaaa,\n"
2731               "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
2732               NoBinPacking);
2733  verifyFormat(
2734      "aaaaaaaa(aaaaaaaaaaaaa,\n"
2735      "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2736      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
2737      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2738      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
2739      NoBinPacking);
2740  verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
2741               "    .aaaaaaaaaaaaaaaaaa();",
2742               NoBinPacking);
2743  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2744               "    aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);",
2745               NoBinPacking);
2746
2747  verifyFormat(
2748      "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2749      "             aaaaaaaaaaaa,\n"
2750      "             aaaaaaaaaaaa);",
2751      NoBinPacking);
2752  verifyFormat(
2753      "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
2754      "                               ddddddddddddddddddddddddddddd),\n"
2755      "             test);",
2756      NoBinPacking);
2757
2758  verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
2759               "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
2760               "            aaaaaaaaaaaaaaaaaaaaaaa> aaaaaaaaaaaaaaaaaa;",
2761               NoBinPacking);
2762  verifyFormat("a(\"a\"\n"
2763               "  \"a\",\n"
2764               "  a);");
2765
2766  NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
2767  verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
2768               "                aaaaaaaaa,\n"
2769               "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
2770               NoBinPacking);
2771  verifyFormat(
2772      "void f() {\n"
2773      "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
2774      "      .aaaaaaa();\n"
2775      "}",
2776      NoBinPacking);
2777  verifyFormat(
2778      "template <class SomeType, class SomeOtherType>\n"
2779      "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
2780      NoBinPacking);
2781}
2782
2783TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
2784  FormatStyle Style = getLLVMStyleWithColumns(15);
2785  Style.ExperimentalAutoDetectBinPacking = true;
2786  EXPECT_EQ("aaa(aaaa,\n"
2787            "    aaaa,\n"
2788            "    aaaa);\n"
2789            "aaa(aaaa,\n"
2790            "    aaaa,\n"
2791            "    aaaa);",
2792            format("aaa(aaaa,\n" // one-per-line
2793                   "  aaaa,\n"
2794                   "    aaaa  );\n"
2795                   "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
2796                   Style));
2797  EXPECT_EQ("aaa(aaaa, aaaa,\n"
2798            "    aaaa);\n"
2799            "aaa(aaaa, aaaa,\n"
2800            "    aaaa);",
2801            format("aaa(aaaa,  aaaa,\n" // bin-packed
2802                   "    aaaa  );\n"
2803                   "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
2804                   Style));
2805}
2806
2807TEST_F(FormatTest, FormatsBuilderPattern) {
2808  verifyFormat(
2809      "return llvm::StringSwitch<Reference::Kind>(name)\n"
2810      "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
2811      "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME).StartsWith(\".init\", ORDER_INIT)\n"
2812      "    .StartsWith(\".fini\", ORDER_FINI).StartsWith(\".hash\", ORDER_HASH)\n"
2813      "    .Default(ORDER_TEXT);\n");
2814
2815  verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
2816               "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
2817  verifyFormat(
2818      "aaaaaaa->aaaaaaa->aaaaaaaaaaaaaaaa(\n"
2819      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2820      "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
2821  verifyFormat(
2822      "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
2823      "    aaaaaaaaaaaaaa);");
2824  verifyFormat(
2825      "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa = aaaaaa->aaaaaaaaaaaa()\n"
2826      "    ->aaaaaaaaaaaaaaaa(\n"
2827      "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2828      "    ->aaaaaaaaaaaaaaaaa();");
2829}
2830
2831TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
2832  verifyFormat(
2833      "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2834      "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
2835  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
2836               "    ccccccccccccccccccccccccc) {\n}");
2837  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
2838               "    ccccccccccccccccccccccccc) {\n}");
2839  verifyFormat(
2840      "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
2841      "    ccccccccccccccccccccccccc) {\n}");
2842  verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
2843               "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
2844               "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
2845               "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
2846  verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
2847               "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
2848               "    aaaaaaaaaaaaaaa != aa) {\n}");
2849}
2850
2851TEST_F(FormatTest, BreaksAfterAssignments) {
2852  verifyFormat(
2853      "unsigned Cost =\n"
2854      "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
2855      "                        SI->getPointerAddressSpaceee());\n");
2856  verifyFormat(
2857      "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
2858      "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
2859
2860  verifyFormat(
2861      "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0)\n"
2862      "    .aaaa().aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
2863  verifyFormat("unsigned OriginalStartColumn =\n"
2864               "    SourceMgr.getSpellingColumnNumber(\n"
2865               "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
2866               "    1;");
2867}
2868
2869TEST_F(FormatTest, AlignsAfterAssignments) {
2870  verifyFormat(
2871      "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2872      "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
2873  verifyFormat(
2874      "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2875      "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
2876  verifyFormat(
2877      "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2878      "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
2879  verifyFormat(
2880      "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2881      "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
2882  verifyFormat(
2883      "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
2884      "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
2885      "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
2886}
2887
2888TEST_F(FormatTest, AlignsAfterReturn) {
2889  verifyFormat(
2890      "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2891      "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
2892  verifyFormat(
2893      "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2894      "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
2895  verifyFormat(
2896      "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
2897      "       aaaaaaaaaaaaaaaaaaaaaa();");
2898  verifyFormat(
2899      "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
2900      "        aaaaaaaaaaaaaaaaaaaaaa());");
2901  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2902               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2903  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2904               "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
2905               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2906}
2907
2908TEST_F(FormatTest, BreaksConditionalExpressions) {
2909  verifyFormat(
2910      "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2911      "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2912      "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2913  verifyFormat(
2914      "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2915      "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2916  verifyFormat(
2917      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
2918      "                                                    : aaaaaaaaaaaaa);");
2919  verifyFormat(
2920      "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2921      "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2922      "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2923      "                   aaaaaaaaaaaaa);");
2924  verifyFormat(
2925      "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2926      "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2927      "                   aaaaaaaaaaaaa);");
2928  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2929               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2930               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2931               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2932               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2933  verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2934               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2935               "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2936               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2937               "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2938               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2939               "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2940  verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2941               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2942               "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2943               "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2944               "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2945  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2946               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2947               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2948  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
2949               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2950               "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2951               "        : aaaaaaaaaaaaaaaa;");
2952  verifyFormat(
2953      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2954      "    ? aaaaaaaaaaaaaaa\n"
2955      "    : aaaaaaaaaaaaaaa;");
2956  verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
2957               "          aaaaaaaaa\n"
2958               "      ? b\n"
2959               "      : c);");
2960  verifyFormat(
2961      "unsigned Indent =\n"
2962      "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0\n"
2963      "                              ? IndentForLevel[TheLine.Level]\n"
2964      "                              : TheLine * 2,\n"
2965      "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
2966      getLLVMStyleWithColumns(70));
2967  verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
2968               "                  ? aaaaaaaaaaaaaaa\n"
2969               "                  : bbbbbbbbbbbbbbb //\n"
2970               "                        ? ccccccccccccccc\n"
2971               "                        : ddddddddddddddd;");
2972  verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
2973               "                  ? aaaaaaaaaaaaaaa\n"
2974               "                  : (bbbbbbbbbbbbbbb //\n"
2975               "                         ? ccccccccccccccc\n"
2976               "                         : ddddddddddddddd);");
2977
2978  FormatStyle NoBinPacking = getLLVMStyle();
2979  NoBinPacking.BinPackParameters = false;
2980  verifyFormat(
2981      "void f() {\n"
2982      "  g(aaa,\n"
2983      "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
2984      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2985      "        ? aaaaaaaaaaaaaaa\n"
2986      "        : aaaaaaaaaaaaaaa);\n"
2987      "}",
2988      NoBinPacking);
2989  verifyFormat(
2990      "void f() {\n"
2991      "  g(aaa,\n"
2992      "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
2993      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2994      "        ?: aaaaaaaaaaaaaaa);\n"
2995      "}",
2996      NoBinPacking);
2997}
2998
2999TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
3000  verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
3001               "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
3002  verifyFormat("bool a = true, b = false;");
3003
3004  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3005               "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
3006               "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
3007               "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
3008  verifyFormat(
3009      "bool aaaaaaaaaaaaaaaaaaaaa =\n"
3010      "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
3011      "     d = e && f;");
3012  verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
3013               "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
3014  verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
3015               "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
3016  verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
3017               "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
3018  // FIXME: If multiple variables are defined, the "*" needs to move to the new
3019  // line. Also fix indent for breaking after the type, this looks bad.
3020  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
3021               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
3022               "    *b = bbbbbbbbbbbbbbbbbbb;",
3023               getGoogleStyle());
3024
3025  // Not ideal, but pointer-with-type does not allow much here.
3026  verifyGoogleFormat(
3027      "aaaaaaaaa* a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
3028      "           *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;");
3029}
3030
3031TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
3032  verifyFormat("arr[foo ? bar : baz];");
3033  verifyFormat("f()[foo ? bar : baz];");
3034  verifyFormat("(a + b)[foo ? bar : baz];");
3035  verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
3036}
3037
3038TEST_F(FormatTest, AlignsStringLiterals) {
3039  verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
3040               "                                      \"short literal\");");
3041  verifyFormat(
3042      "looooooooooooooooooooooooongFunction(\n"
3043      "    \"short literal\"\n"
3044      "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
3045  verifyFormat("someFunction(\"Always break between multi-line\"\n"
3046               "             \" string literals\",\n"
3047               "             and, other, parameters);");
3048  EXPECT_EQ("fun + \"1243\" /* comment */\n"
3049            "      \"5678\";",
3050            format("fun + \"1243\" /* comment */\n"
3051                   "      \"5678\";",
3052                   getLLVMStyleWithColumns(28)));
3053  EXPECT_EQ(
3054      "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
3055      "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
3056      "         \"aaaaaaaaaaaaaaaa\";",
3057      format("aaaaaa ="
3058             "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
3059             "aaaaaaaaaaaaaaaaaaaaa\" "
3060             "\"aaaaaaaaaaaaaaaa\";"));
3061  verifyFormat("a = a + \"a\"\n"
3062               "        \"a\"\n"
3063               "        \"a\";");
3064  verifyFormat("f(\"a\", \"b\"\n"
3065               "       \"c\");");
3066
3067  verifyFormat(
3068      "#define LL_FORMAT \"ll\"\n"
3069      "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
3070      "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
3071
3072  verifyFormat("#define A(X)          \\\n"
3073               "  \"aaaaa\" #X \"bbbbbb\" \\\n"
3074               "  \"ccccc\"",
3075               getLLVMStyleWithColumns(23));
3076  verifyFormat("#define A \"def\"\n"
3077               "f(\"abc\" A \"ghi\"\n"
3078               "  \"jkl\");");
3079}
3080
3081TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
3082  FormatStyle NoBreak = getLLVMStyle();
3083  NoBreak.AlwaysBreakBeforeMultilineStrings = false;
3084  FormatStyle Break = getLLVMStyle();
3085  Break.AlwaysBreakBeforeMultilineStrings = true;
3086  verifyFormat("aaaa = \"bbbb\"\n"
3087               "       \"cccc\";",
3088               NoBreak);
3089  verifyFormat("aaaa =\n"
3090               "    \"bbbb\"\n"
3091               "    \"cccc\";",
3092               Break);
3093  verifyFormat("aaaa(\"bbbb\"\n"
3094               "     \"cccc\");",
3095               NoBreak);
3096  verifyFormat("aaaa(\n"
3097               "    \"bbbb\"\n"
3098               "    \"cccc\");",
3099               Break);
3100  verifyFormat("aaaa(qqq, \"bbbb\"\n"
3101               "          \"cccc\");",
3102               NoBreak);
3103  verifyFormat("aaaa(qqq,\n"
3104               "     \"bbbb\"\n"
3105               "     \"cccc\");",
3106               Break);
3107
3108  // Don't break if there is no column gain.
3109  verifyFormat("f(\"aaaa\"\n"
3110               "  \"bbbb\");",
3111               Break);
3112
3113  // Treat literals with escaped newlines like multi-line string literals.
3114  EXPECT_EQ("x = \"a\\\n"
3115            "b\\\n"
3116            "c\";",
3117            format("x = \"a\\\n"
3118                   "b\\\n"
3119                   "c\";",
3120                   NoBreak));
3121  EXPECT_EQ("x =\n"
3122            "    \"a\\\n"
3123            "b\\\n"
3124            "c\";",
3125            format("x = \"a\\\n"
3126                   "b\\\n"
3127                   "c\";",
3128                   Break));
3129}
3130
3131TEST_F(FormatTest, AlignsPipes) {
3132  verifyFormat(
3133      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3134      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3135      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3136  verifyFormat(
3137      "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
3138      "                     << aaaaaaaaaaaaaaaaaaaa;");
3139  verifyFormat(
3140      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3141      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3142  verifyFormat(
3143      "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
3144      "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
3145      "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
3146  verifyFormat(
3147      "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3148      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3149      "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3150
3151  verifyFormat("return out << \"somepacket = {\\n\"\n"
3152               "           << \"  aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
3153               "           << \"  bbbb = \" << pkt.bbbb << \"\\n\"\n"
3154               "           << \"  cccccc = \" << pkt.cccccc << \"\\n\"\n"
3155               "           << \"  ddd = [\" << pkt.ddd << \"]\\n\"\n"
3156               "           << \"}\";");
3157
3158  verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
3159               "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
3160               "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
3161  verifyFormat(
3162      "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
3163      "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
3164      "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
3165      "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
3166      "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
3167  verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
3168               "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
3169  verifyFormat(
3170      "void f() {\n"
3171      "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
3172      "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
3173      "}");
3174
3175  // Breaking before the first "<<" is generally not desirable.
3176  verifyFormat(
3177      "llvm::errs()\n"
3178      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3179      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3180      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3181      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
3182      getLLVMStyleWithColumns(70));
3183  verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
3184               "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3185               "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
3186               "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3187               "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
3188               "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
3189               getLLVMStyleWithColumns(70));
3190
3191  // But sometimes, breaking before the first "<<" is necessary.
3192  verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
3193               "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3194               "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3195
3196  verifyFormat(
3197      "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3198      "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3199}
3200
3201TEST_F(FormatTest, UnderstandsEquals) {
3202  verifyFormat(
3203      "aaaaaaaaaaaaaaaaa =\n"
3204      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3205  verifyFormat(
3206      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3207      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
3208  verifyFormat(
3209      "if (a) {\n"
3210      "  f();\n"
3211      "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3212      "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
3213      "}");
3214
3215  verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3216               "        100000000 + 10000000) {\n}");
3217}
3218
3219TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
3220  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
3221               "    .looooooooooooooooooooooooooooooooooooooongFunction();");
3222
3223  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
3224               "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
3225
3226  verifyFormat(
3227      "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
3228      "                                                          Parameter2);");
3229
3230  verifyFormat(
3231      "ShortObject->shortFunction(\n"
3232      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
3233      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
3234
3235  verifyFormat("loooooooooooooongFunction(\n"
3236               "    LoooooooooooooongObject->looooooooooooooooongFunction());");
3237
3238  verifyFormat(
3239      "function(LoooooooooooooooooooooooooooooooooooongObject\n"
3240      "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
3241
3242  verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
3243               "    .WillRepeatedly(Return(SomeValue));");
3244  verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)]\n"
3245               "    .insert(ccccccccccccccccccccccc);");
3246  verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3247               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).aaaaa(aaaaa),\n"
3248               "      aaaaaaaaaaaaaaaaaaaaa);");
3249  verifyFormat(
3250      "aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3251      "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3252      "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3253      "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3254      "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
3255  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3256               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3257               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3258               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
3259               "}");
3260
3261  // Here, it is not necessary to wrap at "." or "->".
3262  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
3263               "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
3264  verifyFormat(
3265      "aaaaaaaaaaa->aaaaaaaaa(\n"
3266      "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3267      "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
3268
3269  verifyFormat(
3270      "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3271      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
3272  verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
3273               "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
3274  verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
3275               "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
3276
3277  // FIXME: Should we break before .a()?
3278  verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3279               "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).a();");
3280
3281  FormatStyle NoBinPacking = getLLVMStyle();
3282  NoBinPacking.BinPackParameters = false;
3283  verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
3284               "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
3285               "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
3286               "                         aaaaaaaaaaaaaaaaaaa,\n"
3287               "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
3288               NoBinPacking);
3289
3290  // If there is a subsequent call, change to hanging indentation.
3291  verifyFormat(
3292      "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3293      "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
3294      "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3295  verifyFormat(
3296      "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3297      "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
3298}
3299
3300TEST_F(FormatTest, WrapsTemplateDeclarations) {
3301  verifyFormat("template <typename T>\n"
3302               "virtual void loooooooooooongFunction(int Param1, int Param2);");
3303  verifyFormat(
3304      "template <typename T>\n"
3305      "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
3306  verifyFormat("template <typename T>\n"
3307               "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
3308               "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
3309  verifyFormat(
3310      "template <typename T>\n"
3311      "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
3312      "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
3313  verifyFormat(
3314      "template <typename T>\n"
3315      "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
3316      "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
3317      "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3318  verifyFormat("template <typename T>\n"
3319               "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3320               "    int aaaaaaaaaaaaaaaaaaaaaa);");
3321  verifyFormat(
3322      "template <typename T1, typename T2 = char, typename T3 = char,\n"
3323      "          typename T4 = char>\n"
3324      "void f();");
3325  verifyFormat(
3326      "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
3327      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3328
3329  verifyFormat("a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
3330               "    a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));");
3331
3332  verifyFormat("template <typename T> class C {};");
3333  verifyFormat("template <typename T> void f();");
3334  verifyFormat("template <typename T> void f() {}");
3335
3336  FormatStyle AlwaysBreak = getLLVMStyle();
3337  AlwaysBreak.AlwaysBreakTemplateDeclarations = true;
3338  verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
3339  verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
3340  verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
3341  verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3342               "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
3343               "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
3344  verifyFormat(
3345      "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
3346      "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3347      "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
3348      "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
3349      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3350      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
3351      "        bbbbbbbbbbbbbbbbbbbbbbbb);",
3352      getLLVMStyleWithColumns(72));
3353}
3354
3355TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
3356  verifyFormat(
3357      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3358      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3359  verifyFormat(
3360      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3361      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3362      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
3363
3364  // FIXME: Should we have the extra indent after the second break?
3365  verifyFormat(
3366      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3367      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3368      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3369
3370  verifyFormat(
3371      "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
3372      "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
3373
3374  // Breaking at nested name specifiers is generally not desirable.
3375  verifyFormat(
3376      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3377      "    aaaaaaaaaaaaaaaaaaaaaaa);");
3378
3379  verifyFormat(
3380      "aaaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3381      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3382      "                   aaaaaaaaaaaaaaaaaaaaa);",
3383      getLLVMStyleWithColumns(74));
3384
3385  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3386               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3387               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3388}
3389
3390TEST_F(FormatTest, UnderstandsTemplateParameters) {
3391  verifyFormat("A<int> a;");
3392  verifyFormat("A<A<A<int> > > a;");
3393  verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
3394  verifyFormat("bool x = a < 1 || 2 > a;");
3395  verifyFormat("bool x = 5 < f<int>();");
3396  verifyFormat("bool x = f<int>() > 5;");
3397  verifyFormat("bool x = 5 < a<int>::x;");
3398  verifyFormat("bool x = a < 4 ? a > 2 : false;");
3399  verifyFormat("bool x = f() ? a < 2 : a > 2;");
3400
3401  verifyGoogleFormat("A<A<int>> a;");
3402  verifyGoogleFormat("A<A<A<int>>> a;");
3403  verifyGoogleFormat("A<A<A<A<int>>>> a;");
3404  verifyGoogleFormat("A<A<int> > a;");
3405  verifyGoogleFormat("A<A<A<int> > > a;");
3406  verifyGoogleFormat("A<A<A<A<int> > > > a;");
3407  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
3408  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
3409
3410  verifyFormat("test >> a >> b;");
3411  verifyFormat("test << a >> b;");
3412
3413  verifyFormat("f<int>();");
3414  verifyFormat("template <typename T> void f() {}");
3415
3416  // Not template parameters.
3417  verifyFormat("return a < b && c > d;");
3418  verifyFormat("void f() {\n"
3419               "  while (a < b && c > d) {\n"
3420               "  }\n"
3421               "}");
3422  verifyFormat("template <typename... Types>\n"
3423               "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
3424}
3425
3426TEST_F(FormatTest, UnderstandsBinaryOperators) {
3427  verifyFormat("COMPARE(a, ==, b);");
3428}
3429
3430TEST_F(FormatTest, UnderstandsPointersToMembers) {
3431  verifyFormat("int A::*x;");
3432  verifyFormat("int (S::*func)(void *);");
3433  verifyFormat("void f() { int (S::*func)(void *); }");
3434  verifyFormat("typedef bool *(Class::*Member)() const;");
3435  verifyFormat("void f() {\n"
3436               "  (a->*f)();\n"
3437               "  a->*x;\n"
3438               "  (a.*f)();\n"
3439               "  ((*a).*f)();\n"
3440               "  a.*x;\n"
3441               "}");
3442  verifyFormat("void f() {\n"
3443               "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
3444               "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
3445               "}");
3446  FormatStyle Style = getLLVMStyle();
3447  Style.PointerBindsToType = true;
3448  verifyFormat("typedef bool* (Class::*Member)() const;", Style);
3449}
3450
3451TEST_F(FormatTest, UnderstandsUnaryOperators) {
3452  verifyFormat("int a = -2;");
3453  verifyFormat("f(-1, -2, -3);");
3454  verifyFormat("a[-1] = 5;");
3455  verifyFormat("int a = 5 + -2;");
3456  verifyFormat("if (i == -1) {\n}");
3457  verifyFormat("if (i != -1) {\n}");
3458  verifyFormat("if (i > -1) {\n}");
3459  verifyFormat("if (i < -1) {\n}");
3460  verifyFormat("++(a->f());");
3461  verifyFormat("--(a->f());");
3462  verifyFormat("(a->f())++;");
3463  verifyFormat("a[42]++;");
3464  verifyFormat("if (!(a->f())) {\n}");
3465
3466  verifyFormat("a-- > b;");
3467  verifyFormat("b ? -a : c;");
3468  verifyFormat("n * sizeof char16;");
3469  verifyFormat("n * alignof char16;", getGoogleStyle());
3470  verifyFormat("sizeof(char);");
3471  verifyFormat("alignof(char);", getGoogleStyle());
3472
3473  verifyFormat("return -1;");
3474  verifyFormat("switch (a) {\n"
3475               "case -1:\n"
3476               "  break;\n"
3477               "}");
3478  verifyFormat("#define X -1");
3479  verifyFormat("#define X -kConstant");
3480
3481  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { -5, +3 };");
3482  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { +5, -3 };");
3483
3484  verifyFormat("int a = /* confusing comment */ -1;");
3485  // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
3486  verifyFormat("int a = i /* confusing comment */++;");
3487}
3488
3489TEST_F(FormatTest, UndestandsOverloadedOperators) {
3490  verifyFormat("bool operator<();");
3491  verifyFormat("bool operator>();");
3492  verifyFormat("bool operator=();");
3493  verifyFormat("bool operator==();");
3494  verifyFormat("bool operator!=();");
3495  verifyFormat("int operator+();");
3496  verifyFormat("int operator++();");
3497  verifyFormat("bool operator();");
3498  verifyFormat("bool operator()();");
3499  verifyFormat("bool operator[]();");
3500  verifyFormat("operator bool();");
3501  verifyFormat("operator int();");
3502  verifyFormat("operator void *();");
3503  verifyFormat("operator SomeType<int>();");
3504  verifyFormat("operator SomeType<int, int>();");
3505  verifyFormat("operator SomeType<SomeType<int> >();");
3506  verifyFormat("void *operator new(std::size_t size);");
3507  verifyFormat("void *operator new[](std::size_t size);");
3508  verifyFormat("void operator delete(void *ptr);");
3509  verifyFormat("void operator delete[](void *ptr);");
3510  verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
3511               "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
3512
3513  verifyFormat(
3514      "ostream &operator<<(ostream &OutputStream,\n"
3515      "                    SomeReallyLongType WithSomeReallyLongValue);");
3516  verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
3517               "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
3518               "  return left.group < right.group;\n"
3519               "}");
3520  verifyFormat("SomeType &operator=(const SomeType &S);");
3521
3522  verifyGoogleFormat("operator void*();");
3523  verifyGoogleFormat("operator SomeType<SomeType<int>>();");
3524}
3525
3526TEST_F(FormatTest, UnderstandsNewAndDelete) {
3527  verifyFormat("void f() {\n"
3528               "  A *a = new A;\n"
3529               "  A *a = new (placement) A;\n"
3530               "  delete a;\n"
3531               "  delete (A *)a;\n"
3532               "}");
3533}
3534
3535TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
3536  verifyFormat("int *f(int *a) {}");
3537  verifyFormat("int main(int argc, char **argv) {}");
3538  verifyFormat("Test::Test(int b) : a(b * b) {}");
3539  verifyIndependentOfContext("f(a, *a);");
3540  verifyFormat("void g() { f(*a); }");
3541  verifyIndependentOfContext("int a = b * 10;");
3542  verifyIndependentOfContext("int a = 10 * b;");
3543  verifyIndependentOfContext("int a = b * c;");
3544  verifyIndependentOfContext("int a += b * c;");
3545  verifyIndependentOfContext("int a -= b * c;");
3546  verifyIndependentOfContext("int a *= b * c;");
3547  verifyIndependentOfContext("int a /= b * c;");
3548  verifyIndependentOfContext("int a = *b;");
3549  verifyIndependentOfContext("int a = *b * c;");
3550  verifyIndependentOfContext("int a = b * *c;");
3551  verifyIndependentOfContext("return 10 * b;");
3552  verifyIndependentOfContext("return *b * *c;");
3553  verifyIndependentOfContext("return a & ~b;");
3554  verifyIndependentOfContext("f(b ? *c : *d);");
3555  verifyIndependentOfContext("int a = b ? *c : *d;");
3556  verifyIndependentOfContext("*b = a;");
3557  verifyIndependentOfContext("a * ~b;");
3558  verifyIndependentOfContext("a * !b;");
3559  verifyIndependentOfContext("a * +b;");
3560  verifyIndependentOfContext("a * -b;");
3561  verifyIndependentOfContext("a * ++b;");
3562  verifyIndependentOfContext("a * --b;");
3563  verifyIndependentOfContext("a[4] * b;");
3564  verifyIndependentOfContext("a[a * a] = 1;");
3565  verifyIndependentOfContext("f() * b;");
3566  verifyIndependentOfContext("a * [self dostuff];");
3567  verifyIndependentOfContext("int x = a * (a + b);");
3568  verifyIndependentOfContext("(a *)(a + b);");
3569  verifyIndependentOfContext("int *pa = (int *)&a;");
3570  verifyIndependentOfContext("return sizeof(int **);");
3571  verifyIndependentOfContext("return sizeof(int ******);");
3572  verifyIndependentOfContext("return (int **&)a;");
3573  verifyIndependentOfContext("f((*PointerToArray)[10]);");
3574  verifyFormat("void f(Type (*parameter)[10]) {}");
3575  verifyGoogleFormat("return sizeof(int**);");
3576  verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
3577  verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
3578  verifyFormat("auto a = [](int **&, int ***) {};");
3579
3580  verifyIndependentOfContext("InvalidRegions[*R] = 0;");
3581
3582  verifyIndependentOfContext("A<int *> a;");
3583  verifyIndependentOfContext("A<int **> a;");
3584  verifyIndependentOfContext("A<int *, int *> a;");
3585  verifyIndependentOfContext(
3586      "const char *const p = reinterpret_cast<const char *const>(q);");
3587  verifyIndependentOfContext("A<int **, int **> a;");
3588  verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
3589  verifyFormat("for (char **a = b; *a; ++a) {\n}");
3590  verifyFormat("for (; a && b;) {\n}");
3591
3592  verifyFormat(
3593      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3594      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3595
3596  verifyGoogleFormat("int main(int argc, char** argv) {}");
3597  verifyGoogleFormat("A<int*> a;");
3598  verifyGoogleFormat("A<int**> a;");
3599  verifyGoogleFormat("A<int*, int*> a;");
3600  verifyGoogleFormat("A<int**, int**> a;");
3601  verifyGoogleFormat("f(b ? *c : *d);");
3602  verifyGoogleFormat("int a = b ? *c : *d;");
3603  verifyGoogleFormat("Type* t = **x;");
3604  verifyGoogleFormat("Type* t = *++*x;");
3605  verifyGoogleFormat("*++*x;");
3606  verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
3607  verifyGoogleFormat("Type* t = x++ * y;");
3608  verifyGoogleFormat(
3609      "const char* const p = reinterpret_cast<const char* const>(q);");
3610
3611  verifyIndependentOfContext("a = *(x + y);");
3612  verifyIndependentOfContext("a = &(x + y);");
3613  verifyIndependentOfContext("*(x + y).call();");
3614  verifyIndependentOfContext("&(x + y)->call();");
3615  verifyFormat("void f() { &(*I).first; }");
3616
3617  verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
3618  verifyFormat(
3619      "int *MyValues = {\n"
3620      "  *A, // Operator detection might be confused by the '{'\n"
3621      "  *BB // Operator detection might be confused by previous comment\n"
3622      "};");
3623
3624  verifyIndependentOfContext("if (int *a = &b)");
3625  verifyIndependentOfContext("if (int &a = *b)");
3626  verifyIndependentOfContext("if (a & b[i])");
3627  verifyIndependentOfContext("if (a::b::c::d & b[i])");
3628  verifyIndependentOfContext("if (*b[i])");
3629  verifyIndependentOfContext("if (int *a = (&b))");
3630  verifyIndependentOfContext("while (int *a = &b)");
3631  verifyFormat("void f() {\n"
3632               "  for (const int &v : Values) {\n"
3633               "  }\n"
3634               "}");
3635  verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
3636  verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
3637
3638  verifyFormat("#define MACRO     \\\n"
3639               "  int *i = a * b; \\\n"
3640               "  void f(a *b);",
3641               getLLVMStyleWithColumns(19));
3642
3643  verifyIndependentOfContext("A = new SomeType *[Length];");
3644  verifyIndependentOfContext("A = new SomeType *[Length]();");
3645  verifyIndependentOfContext("T **t = new T *;");
3646  verifyIndependentOfContext("T **t = new T *();");
3647  verifyGoogleFormat("A = new SomeType* [Length]();");
3648  verifyGoogleFormat("A = new SomeType* [Length];");
3649  verifyGoogleFormat("T** t = new T*;");
3650  verifyGoogleFormat("T** t = new T*();");
3651
3652  FormatStyle PointerLeft = getLLVMStyle();
3653  PointerLeft.PointerBindsToType = true;
3654  verifyFormat("delete *x;", PointerLeft);
3655}
3656
3657TEST_F(FormatTest, UnderstandsAttributes) {
3658  verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
3659}
3660
3661TEST_F(FormatTest, UnderstandsEllipsis) {
3662  verifyFormat("int printf(const char *fmt, ...);");
3663  verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
3664  verifyFormat("template <class... Ts> void Foo(Ts *... ts) {}");
3665
3666  FormatStyle PointersLeft = getLLVMStyle();
3667  PointersLeft.PointerBindsToType = true;
3668  verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", PointersLeft);
3669}
3670
3671TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
3672  EXPECT_EQ("int *a;\n"
3673            "int *a;\n"
3674            "int *a;",
3675            format("int *a;\n"
3676                   "int* a;\n"
3677                   "int *a;",
3678                   getGoogleStyle()));
3679  EXPECT_EQ("int* a;\n"
3680            "int* a;\n"
3681            "int* a;",
3682            format("int* a;\n"
3683                   "int* a;\n"
3684                   "int *a;",
3685                   getGoogleStyle()));
3686  EXPECT_EQ("int *a;\n"
3687            "int *a;\n"
3688            "int *a;",
3689            format("int *a;\n"
3690                   "int * a;\n"
3691                   "int *  a;",
3692                   getGoogleStyle()));
3693}
3694
3695TEST_F(FormatTest, UnderstandsRvalueReferences) {
3696  verifyFormat("int f(int &&a) {}");
3697  verifyFormat("int f(int a, char &&b) {}");
3698  verifyFormat("void f() { int &&a = b; }");
3699  verifyGoogleFormat("int f(int a, char&& b) {}");
3700  verifyGoogleFormat("void f() { int&& a = b; }");
3701
3702  verifyIndependentOfContext("A<int &&> a;");
3703  verifyIndependentOfContext("A<int &&, int &&> a;");
3704  verifyGoogleFormat("A<int&&> a;");
3705  verifyGoogleFormat("A<int&&, int&&> a;");
3706
3707  // Not rvalue references:
3708  verifyFormat("template <bool B, bool C> class A {\n"
3709               "  static_assert(B && C, \"Something is wrong\");\n"
3710               "};");
3711}
3712
3713TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
3714  verifyFormat("void f() {\n"
3715               "  x[aaaaaaaaa -\n"
3716               "    b] = 23;\n"
3717               "}",
3718               getLLVMStyleWithColumns(15));
3719}
3720
3721TEST_F(FormatTest, FormatsCasts) {
3722  verifyFormat("Type *A = static_cast<Type *>(P);");
3723  verifyFormat("Type *A = (Type *)P;");
3724  verifyFormat("Type *A = (vector<Type *, int *>)P;");
3725  verifyFormat("int a = (int)(2.0f);");
3726  verifyFormat("int a = (int)2.0f;");
3727  verifyFormat("x[(int32)y];");
3728  verifyFormat("x = (int32)y;");
3729  verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
3730  verifyFormat("int a = (int)*b;");
3731  verifyFormat("int a = (int)2.0f;");
3732  verifyFormat("int a = (int)~0;");
3733  verifyFormat("int a = (int)++a;");
3734  verifyFormat("int a = (int)sizeof(int);");
3735  verifyFormat("int a = (int)+2;");
3736  verifyFormat("my_int a = (my_int)2.0f;");
3737  verifyFormat("my_int a = (my_int)sizeof(int);");
3738  verifyFormat("return (my_int)aaa;");
3739  verifyFormat("#define x ((int)-1)");
3740  verifyFormat("#define p(q) ((int *)&q)");
3741
3742  // FIXME: Without type knowledge, this can still fall apart miserably.
3743  verifyFormat("void f() { my_int a = (my_int) * b; }");
3744  verifyFormat("void f() { return P ? (my_int) * P : (my_int)0; }");
3745  verifyFormat("my_int a = (my_int) ~0;");
3746  verifyFormat("my_int a = (my_int)++ a;");
3747  verifyFormat("my_int a = (my_int) + 2;");
3748
3749  // Don't break after a cast's
3750  verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3751               "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
3752               "                                   bbbbbbbbbbbbbbbbbbbbbb);");
3753
3754  // These are not casts.
3755  verifyFormat("void f(int *) {}");
3756  verifyFormat("f(foo)->b;");
3757  verifyFormat("f(foo).b;");
3758  verifyFormat("f(foo)(b);");
3759  verifyFormat("f(foo)[b];");
3760  verifyFormat("[](foo) { return 4; }(bar)];");
3761  verifyFormat("(*funptr)(foo)[4];");
3762  verifyFormat("funptrs[4](foo)[4];");
3763  verifyFormat("void f(int *);");
3764  verifyFormat("void f(int *) = 0;");
3765  verifyFormat("void f(SmallVector<int>) {}");
3766  verifyFormat("void f(SmallVector<int>);");
3767  verifyFormat("void f(SmallVector<int>) = 0;");
3768  verifyFormat("void f(int i = (kValue) * kMask) {}");
3769  verifyFormat("void f(int i = (kA * kB) & kMask) {}");
3770  verifyFormat("int a = sizeof(int) * b;");
3771  verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
3772  verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
3773  verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
3774  verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
3775
3776  // These are not casts, but at some point were confused with casts.
3777  verifyFormat("virtual void foo(int *) override;");
3778  verifyFormat("virtual void foo(char &) const;");
3779  verifyFormat("virtual void foo(int *a, char *) const;");
3780  verifyFormat("int a = sizeof(int *) + b;");
3781  verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
3782
3783  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
3784               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
3785  // FIXME: The indentation here is not ideal.
3786  verifyFormat(
3787      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3788      "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
3789      "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
3790}
3791
3792TEST_F(FormatTest, FormatsFunctionTypes) {
3793  verifyFormat("A<bool()> a;");
3794  verifyFormat("A<SomeType()> a;");
3795  verifyFormat("A<void (*)(int, std::string)> a;");
3796  verifyFormat("A<void *(int)>;");
3797  verifyFormat("void *(*a)(int *, SomeType *);");
3798  verifyFormat("int (*func)(void *);");
3799  verifyFormat("void f() { int (*func)(void *); }");
3800
3801  verifyGoogleFormat("A<void*(int*, SomeType*)>;");
3802  verifyGoogleFormat("void* (*a)(int);");
3803
3804  // Other constructs can look somewhat like function types:
3805  verifyFormat("A<sizeof(*x)> a;");
3806  verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
3807  verifyFormat("some_var = function(*some_pointer_var)[0];");
3808  verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
3809}
3810
3811TEST_F(FormatTest, BreaksLongDeclarations) {
3812  verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
3813               "    AnotherNameForTheLongType;",
3814               getGoogleStyle());
3815  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
3816               "    LoooooooooooooooooooooooooooooooooooooooongVariable;",
3817               getGoogleStyle());
3818  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
3819               "    LoooooooooooooooooooooooooooooooooooooooongVariable;",
3820               getGoogleStyle());
3821  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
3822               "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
3823               getGoogleStyle());
3824  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
3825               "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
3826  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
3827               "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
3828
3829  // FIXME: Without the comment, this breaks after "(".
3830  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
3831               "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
3832               getGoogleStyle());
3833
3834  verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
3835               "                  int LoooooooooooooooooooongParam2) {}");
3836  verifyFormat(
3837      "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
3838      "                                   SourceLocation L, IdentifierIn *II,\n"
3839      "                                   Type *T) {}");
3840  verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
3841               "ReallyReallyLongFunctionName(\n"
3842               "    const std::string &SomeParameter,\n"
3843               "    const SomeType<string, SomeOtherTemplateParameter> &\n"
3844               "        ReallyReallyLongParameterName,\n"
3845               "    const SomeType<string, SomeOtherTemplateParameter> &\n"
3846               "        AnotherLongParameterName) {}");
3847  verifyFormat("template <typename A>\n"
3848               "SomeLoooooooooooooooooooooongType<\n"
3849               "    typename some_namespace::SomeOtherType<A>::Type>\n"
3850               "Function() {}");
3851  verifyFormat(
3852      "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
3853      "    aaaaaaaaaaaaaaaaaaaaaaa;",
3854      getGoogleStyle());
3855
3856  verifyGoogleFormat(
3857      "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
3858      "                                   SourceLocation L) {}");
3859  verifyGoogleFormat(
3860      "some_namespace::LongReturnType\n"
3861      "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
3862      "    int first_long_parameter, int second_parameter) {}");
3863
3864  verifyGoogleFormat("template <typename T>\n"
3865                     "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
3866                     "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
3867  verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3868                     "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
3869}
3870
3871TEST_F(FormatTest, FormatsArrays) {
3872  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3873               "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
3874  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3875               "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
3876  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3877               "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
3878  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3879               "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3880               "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
3881  verifyFormat(
3882      "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
3883      "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3884      "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
3885}
3886
3887TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
3888  verifyFormat("(a)->b();");
3889  verifyFormat("--a;");
3890}
3891
3892TEST_F(FormatTest, HandlesIncludeDirectives) {
3893  verifyFormat("#include <string>\n"
3894               "#include <a/b/c.h>\n"
3895               "#include \"a/b/string\"\n"
3896               "#include \"string.h\"\n"
3897               "#include \"string.h\"\n"
3898               "#include <a-a>\n"
3899               "#include < path with space >\n"
3900               "#include \"abc.h\" // this is included for ABC\n"
3901               "#include \"some long include\" // with a comment\n"
3902               "#include \"some very long include paaaaaaaaaaaaaaaaaaaaaaath\"",
3903               getLLVMStyleWithColumns(35));
3904
3905  verifyFormat("#import <string>");
3906  verifyFormat("#import <a/b/c.h>");
3907  verifyFormat("#import \"a/b/string\"");
3908  verifyFormat("#import \"string.h\"");
3909  verifyFormat("#import \"string.h\"");
3910}
3911
3912//===----------------------------------------------------------------------===//
3913// Error recovery tests.
3914//===----------------------------------------------------------------------===//
3915
3916TEST_F(FormatTest, IncompleteParameterLists) {
3917  FormatStyle NoBinPacking = getLLVMStyle();
3918  NoBinPacking.BinPackParameters = false;
3919  verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
3920               "                        double *min_x,\n"
3921               "                        double *max_x,\n"
3922               "                        double *min_y,\n"
3923               "                        double *max_y,\n"
3924               "                        double *min_z,\n"
3925               "                        double *max_z, ) {}",
3926               NoBinPacking);
3927}
3928
3929TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
3930  verifyFormat("void f() { return; }\n42");
3931  verifyFormat("void f() {\n"
3932               "  if (0)\n"
3933               "    return;\n"
3934               "}\n"
3935               "42");
3936  verifyFormat("void f() { return }\n42");
3937  verifyFormat("void f() {\n"
3938               "  if (0)\n"
3939               "    return\n"
3940               "}\n"
3941               "42");
3942}
3943
3944TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
3945  EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
3946  EXPECT_EQ("void f() {\n"
3947            "  if (a)\n"
3948            "    return\n"
3949            "}",
3950            format("void  f  (  )  {  if  ( a )  return  }"));
3951  EXPECT_EQ("namespace N {\n"
3952            "void f()\n"
3953            "}",
3954            format("namespace  N  {  void f()  }"));
3955  EXPECT_EQ("namespace N {\n"
3956            "void f() {}\n"
3957            "void g()\n"
3958            "}",
3959            format("namespace N  { void f( ) { } void g( ) }"));
3960}
3961
3962TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
3963  verifyFormat("int aaaaaaaa =\n"
3964               "    // Overlylongcomment\n"
3965               "    b;",
3966               getLLVMStyleWithColumns(20));
3967  verifyFormat("function(\n"
3968               "    ShortArgument,\n"
3969               "    LoooooooooooongArgument);\n",
3970               getLLVMStyleWithColumns(20));
3971}
3972
3973TEST_F(FormatTest, IncorrectAccessSpecifier) {
3974  verifyFormat("public:");
3975  verifyFormat("class A {\n"
3976               "public\n"
3977               "  void f() {}\n"
3978               "};");
3979  verifyFormat("public\n"
3980               "int qwerty;");
3981  verifyFormat("public\n"
3982               "B {}");
3983  verifyFormat("public\n"
3984               "{}");
3985  verifyFormat("public\n"
3986               "B { int x; }");
3987}
3988
3989TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
3990  verifyFormat("{");
3991  verifyFormat("#})");
3992}
3993
3994TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
3995  verifyFormat("do {\n}");
3996  verifyFormat("do {\n}\n"
3997               "f();");
3998  verifyFormat("do {\n}\n"
3999               "wheeee(fun);");
4000  verifyFormat("do {\n"
4001               "  f();\n"
4002               "}");
4003}
4004
4005TEST_F(FormatTest, IncorrectCodeMissingParens) {
4006  verifyFormat("if {\n  foo;\n  foo();\n}");
4007  verifyFormat("switch {\n  foo;\n  foo();\n}");
4008  verifyFormat("for {\n  foo;\n  foo();\n}");
4009  verifyFormat("while {\n  foo;\n  foo();\n}");
4010  verifyFormat("do {\n  foo;\n  foo();\n} while;");
4011}
4012
4013TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
4014  verifyFormat("namespace {\n"
4015               "class Foo {  Foo  (\n"
4016               "};\n"
4017               "} // comment");
4018}
4019
4020TEST_F(FormatTest, IncorrectCodeErrorDetection) {
4021  EXPECT_EQ("{\n{}\n", format("{\n{\n}\n"));
4022  EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
4023  EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
4024  EXPECT_EQ("{\n  {}\n  }\n}\n", format("{\n  {\n    }\n  }\n}\n"));
4025
4026  EXPECT_EQ("{\n"
4027            "    {\n"
4028            " breakme(\n"
4029            "     qwe);\n"
4030            "}\n",
4031            format("{\n"
4032                   "    {\n"
4033                   " breakme(qwe);\n"
4034                   "}\n",
4035                   getLLVMStyleWithColumns(10)));
4036}
4037
4038TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
4039  verifyFormat("int x = {\n"
4040               "  avariable,\n"
4041               "  b(alongervariable)\n"
4042               "};",
4043               getLLVMStyleWithColumns(25));
4044}
4045
4046TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
4047  verifyFormat("return (a)(b) { 1, 2, 3 };");
4048}
4049
4050TEST_F(FormatTest, LayoutCxx11ConstructorBraceInitializers) {
4051    verifyFormat("vector<int> x{ 1, 2, 3, 4 };");
4052    verifyFormat("vector<T> x{ {}, {}, {}, {} };");
4053    verifyFormat("f({ 1, 2 });");
4054    verifyFormat("auto v = Foo{ 1 };");
4055    verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });");
4056    verifyFormat("Class::Class : member{ 1, 2, 3 } {}");
4057    verifyFormat("new vector<int>{ 1, 2, 3 };");
4058    verifyFormat("new int[3]{ 1, 2, 3 };");
4059    verifyFormat("return { arg1, arg2 };");
4060    verifyFormat("return { arg1, SomeType{ parameter } };");
4061    verifyFormat("new T{ arg1, arg2 };");
4062    verifyFormat("class Class {\n"
4063                 "  T member = { arg1, arg2 };\n"
4064                 "};");
4065    verifyFormat(
4066        "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4067        "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
4068        "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4069        "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };");
4070    verifyFormat("DoSomethingWithVector({} /* No data */);");
4071    verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });");
4072    verifyFormat(
4073        "someFunction(OtherParam, BracedList{\n"
4074        "                           // comment 1 (Forcing interesting break)\n"
4075        "                           param1, param2,\n"
4076        "                           // comment 2\n"
4077        "                           param3, param4\n"
4078        "                         });");
4079
4080    FormatStyle NoSpaces = getLLVMStyle();
4081    NoSpaces.Cpp11BracedListStyle = true;
4082    verifyFormat("vector<int> x{1, 2, 3, 4};", NoSpaces);
4083    verifyFormat("vector<T> x{{}, {}, {}, {}};", NoSpaces);
4084    verifyFormat("f({1, 2});", NoSpaces);
4085    verifyFormat("auto v = Foo{-1};", NoSpaces);
4086    verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});", NoSpaces);
4087    verifyFormat("Class::Class : member{1, 2, 3} {}", NoSpaces);
4088    verifyFormat("new vector<int>{1, 2, 3};", NoSpaces);
4089    verifyFormat("new int[3]{1, 2, 3};", NoSpaces);
4090    verifyFormat("return {arg1, arg2};", NoSpaces);
4091    verifyFormat("return {arg1, SomeType{parameter}};", NoSpaces);
4092    verifyFormat("new T{arg1, arg2};", NoSpaces);
4093    verifyFormat("class Class {\n"
4094                 "  T member = {arg1, arg2};\n"
4095                 "};",
4096                 NoSpaces);
4097}
4098
4099TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
4100  verifyFormat("void f() { return 42; }");
4101  verifyFormat("void f() {\n"
4102               "  // Comment\n"
4103               "}");
4104  verifyFormat("{\n"
4105               "#error {\n"
4106               "  int a;\n"
4107               "}");
4108  verifyFormat("{\n"
4109               "  int a;\n"
4110               "#error {\n"
4111               "}");
4112  verifyFormat("void f() {} // comment");
4113  verifyFormat("void f() { int a; } // comment");
4114  verifyFormat("void f() {\n"
4115               "} // comment",
4116               getLLVMStyleWithColumns(15));
4117
4118  verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
4119  verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
4120
4121  verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
4122  verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
4123}
4124
4125TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
4126  // Elaborate type variable declarations.
4127  verifyFormat("struct foo a = { bar };\nint n;");
4128  verifyFormat("class foo a = { bar };\nint n;");
4129  verifyFormat("union foo a = { bar };\nint n;");
4130
4131  // Elaborate types inside function definitions.
4132  verifyFormat("struct foo f() {}\nint n;");
4133  verifyFormat("class foo f() {}\nint n;");
4134  verifyFormat("union foo f() {}\nint n;");
4135
4136  // Templates.
4137  verifyFormat("template <class X> void f() {}\nint n;");
4138  verifyFormat("template <struct X> void f() {}\nint n;");
4139  verifyFormat("template <union X> void f() {}\nint n;");
4140
4141  // Actual definitions...
4142  verifyFormat("struct {\n} n;");
4143  verifyFormat(
4144      "template <template <class T, class Y>, class Z> class X {\n} n;");
4145  verifyFormat("union Z {\n  int n;\n} x;");
4146  verifyFormat("class MACRO Z {\n} n;");
4147  verifyFormat("class MACRO(X) Z {\n} n;");
4148  verifyFormat("class __attribute__(X) Z {\n} n;");
4149  verifyFormat("class __declspec(X) Z {\n} n;");
4150  verifyFormat("class A##B##C {\n} n;");
4151
4152  // Redefinition from nested context:
4153  verifyFormat("class A::B::C {\n} n;");
4154
4155  // Template definitions.
4156  verifyFormat(
4157      "template <typename F>\n"
4158      "Matcher(const Matcher<F> &Other,\n"
4159      "        typename enable_if_c<is_base_of<F, T>::value &&\n"
4160      "                             !is_same<F, T>::value>::type * = 0)\n"
4161      "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
4162
4163  // FIXME: This is still incorrectly handled at the formatter side.
4164  verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
4165
4166  // FIXME:
4167  // This now gets parsed incorrectly as class definition.
4168  // verifyFormat("class A<int> f() {\n}\nint n;");
4169
4170  // Elaborate types where incorrectly parsing the structural element would
4171  // break the indent.
4172  verifyFormat("if (true)\n"
4173               "  class X x;\n"
4174               "else\n"
4175               "  f();\n");
4176
4177  // This is simply incomplete. Formatting is not important, but must not crash.
4178  verifyFormat("class A:");
4179}
4180
4181TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
4182  verifyFormat("#error Leave     all         white!!!!! space* alone!\n");
4183  verifyFormat("#warning Leave     all         white!!!!! space* alone!\n");
4184  EXPECT_EQ("#error 1", format("  #  error   1"));
4185  EXPECT_EQ("#warning 1", format("  #  warning 1"));
4186}
4187
4188TEST_F(FormatTest, FormatHashIfExpressions) {
4189  // FIXME: Come up with a better indentation for #elif.
4190  verifyFormat(
4191      "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
4192      "    defined(BBBBBBBB)\n"
4193      "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
4194      "    defined(BBBBBBBB)\n"
4195      "#endif",
4196      getLLVMStyleWithColumns(65));
4197}
4198
4199TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
4200  FormatStyle AllowsMergedIf = getGoogleStyle();
4201  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
4202  verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
4203  verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
4204  verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
4205  EXPECT_EQ("if (true) return 42;",
4206            format("if (true)\nreturn 42;", AllowsMergedIf));
4207  FormatStyle ShortMergedIf = AllowsMergedIf;
4208  ShortMergedIf.ColumnLimit = 25;
4209  verifyFormat("#define A \\\n"
4210               "  if (true) return 42;",
4211               ShortMergedIf);
4212  verifyFormat("#define A \\\n"
4213               "  f();    \\\n"
4214               "  if (true)\n"
4215               "#define B",
4216               ShortMergedIf);
4217  verifyFormat("#define A \\\n"
4218               "  f();    \\\n"
4219               "  if (true)\n"
4220               "g();",
4221               ShortMergedIf);
4222  verifyFormat("{\n"
4223               "#ifdef A\n"
4224               "  // Comment\n"
4225               "  if (true) continue;\n"
4226               "#endif\n"
4227               "  // Comment\n"
4228               "  if (true) continue;",
4229               ShortMergedIf);
4230}
4231
4232TEST_F(FormatTest, BlockCommentsInControlLoops) {
4233  verifyFormat("if (0) /* a comment in a strange place */ {\n"
4234               "  f();\n"
4235               "}");
4236  verifyFormat("if (0) /* a comment in a strange place */ {\n"
4237               "  f();\n"
4238               "} /* another comment */ else /* comment #3 */ {\n"
4239               "  g();\n"
4240               "}");
4241  verifyFormat("while (0) /* a comment in a strange place */ {\n"
4242               "  f();\n"
4243               "}");
4244  verifyFormat("for (;;) /* a comment in a strange place */ {\n"
4245               "  f();\n"
4246               "}");
4247  verifyFormat("do /* a comment in a strange place */ {\n"
4248               "  f();\n"
4249               "} /* another comment */ while (0);");
4250}
4251
4252TEST_F(FormatTest, BlockComments) {
4253  EXPECT_EQ("/* */ /* */ /* */\n/* */ /* */ /* */",
4254            format("/* *//* */  /* */\n/* *//* */  /* */"));
4255  EXPECT_EQ("/* */ a /* */ b;", format("  /* */  a/* */  b;"));
4256  EXPECT_EQ("#define A /*123*/\\\n"
4257            "  b\n"
4258            "/* */\n"
4259            "someCall(\n"
4260            "    parameter);",
4261            format("#define A /*123*/ b\n"
4262                   "/* */\n"
4263                   "someCall(parameter);",
4264                   getLLVMStyleWithColumns(15)));
4265
4266  EXPECT_EQ("#define A\n"
4267            "/* */ someCall(\n"
4268            "    parameter);",
4269            format("#define A\n"
4270                   "/* */someCall(parameter);",
4271                   getLLVMStyleWithColumns(15)));
4272  EXPECT_EQ("/*\n**\n*/", format("/*\n**\n*/"));
4273  EXPECT_EQ("/*\n"
4274            "*\n"
4275            " * aaaaaa\n"
4276            "*aaaaaa\n"
4277            "*/",
4278            format("/*\n"
4279                   "*\n"
4280                   " * aaaaaa aaaaaa\n"
4281                   "*/",
4282                   getLLVMStyleWithColumns(10)));
4283  EXPECT_EQ("/*\n"
4284            "**\n"
4285            "* aaaaaa\n"
4286            "*aaaaaa\n"
4287            "*/",
4288            format("/*\n"
4289                   "**\n"
4290                   "* aaaaaa aaaaaa\n"
4291                   "*/",
4292                   getLLVMStyleWithColumns(10)));
4293
4294  FormatStyle NoBinPacking = getLLVMStyle();
4295  NoBinPacking.BinPackParameters = false;
4296  EXPECT_EQ("someFunction(1, /* comment 1 */\n"
4297            "             2, /* comment 2 */\n"
4298            "             3, /* comment 3 */\n"
4299            "             aaaa,\n"
4300            "             bbbb);",
4301            format("someFunction (1,   /* comment 1 */\n"
4302                   "                2, /* comment 2 */  \n"
4303                   "               3,   /* comment 3 */\n"
4304                   "aaaa, bbbb );",
4305                   NoBinPacking));
4306  verifyFormat(
4307      "bool aaaaaaaaaaaaa = /* comment: */ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4308      "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4309  EXPECT_EQ(
4310      "bool aaaaaaaaaaaaa = /* trailing comment */\n"
4311      "    aaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4312      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;",
4313      format(
4314          "bool       aaaaaaaaaaaaa =       /* trailing comment */\n"
4315          "    aaaaaaaaaaaaaaaaaaaaaaaaaaa||aaaaaaaaaaaaaaaaaaaaaaaaa    ||\n"
4316          "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa   || aaaaaaaaaaaaaaaaaaaaaaaaaa;"));
4317  EXPECT_EQ(
4318      "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
4319      "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   /* comment */\n"
4320      "int cccccccccccccccccccccccccccccc;       /* comment */\n",
4321      format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
4322             "int      bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n"
4323             "int    cccccccccccccccccccccccccccccc;  /* comment */\n"));
4324
4325  verifyFormat("void f(int * /* unused */) {}");
4326
4327  EXPECT_EQ("/*\n"
4328            " **\n"
4329            " */",
4330            format("/*\n"
4331                   " **\n"
4332                   " */"));
4333  EXPECT_EQ("/*\n"
4334            " *q\n"
4335            " */",
4336            format("/*\n"
4337                   " *q\n"
4338                   " */"));
4339  EXPECT_EQ("/*\n"
4340            " * q\n"
4341            " */",
4342            format("/*\n"
4343                   " * q\n"
4344                   " */"));
4345  EXPECT_EQ("/*\n"
4346            " **/",
4347            format("/*\n"
4348                   " **/"));
4349  EXPECT_EQ("/*\n"
4350            " ***/",
4351            format("/*\n"
4352                   " ***/"));
4353}
4354
4355TEST_F(FormatTest, BlockCommentsInMacros) {
4356  EXPECT_EQ("#define A          \\\n"
4357            "  {                \\\n"
4358            "    /* one line */ \\\n"
4359            "    someCall();",
4360            format("#define A {        \\\n"
4361                   "  /* one line */   \\\n"
4362                   "  someCall();",
4363                   getLLVMStyleWithColumns(20)));
4364  EXPECT_EQ("#define A          \\\n"
4365            "  {                \\\n"
4366            "    /* previous */ \\\n"
4367            "    /* one line */ \\\n"
4368            "    someCall();",
4369            format("#define A {        \\\n"
4370                   "  /* previous */   \\\n"
4371                   "  /* one line */   \\\n"
4372                   "  someCall();",
4373                   getLLVMStyleWithColumns(20)));
4374}
4375
4376TEST_F(FormatTest, BlockCommentsAtEndOfLine) {
4377  EXPECT_EQ("a = {\n"
4378            "  1111 /*    */\n"
4379            "};",
4380            format("a = {1111 /*    */\n"
4381                   "};",
4382                   getLLVMStyleWithColumns(15)));
4383  EXPECT_EQ("a = {\n"
4384            "  1111 /*      */\n"
4385            "};",
4386            format("a = {1111 /*      */\n"
4387                   "};",
4388                   getLLVMStyleWithColumns(15)));
4389
4390  // FIXME: The formatting is still wrong here.
4391  EXPECT_EQ("a = {\n"
4392            "  1111 /*      a\n"
4393            "          */\n"
4394            "};",
4395            format("a = {1111 /*      a */\n"
4396                   "};",
4397                   getLLVMStyleWithColumns(15)));
4398}
4399
4400TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
4401  // FIXME: This is not what we want...
4402  verifyFormat("{\n"
4403               "// a"
4404               "// b");
4405}
4406
4407TEST_F(FormatTest, FormatStarDependingOnContext) {
4408  verifyFormat("void f(int *a);");
4409  verifyFormat("void f() { f(fint * b); }");
4410  verifyFormat("class A {\n  void f(int *a);\n};");
4411  verifyFormat("class A {\n  int *a;\n};");
4412  verifyFormat("namespace a {\n"
4413               "namespace b {\n"
4414               "class A {\n"
4415               "  void f() {}\n"
4416               "  int *a;\n"
4417               "};\n"
4418               "}\n"
4419               "}");
4420}
4421
4422TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
4423  verifyFormat("while");
4424  verifyFormat("operator");
4425}
4426
4427//===----------------------------------------------------------------------===//
4428// Objective-C tests.
4429//===----------------------------------------------------------------------===//
4430
4431TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
4432  verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
4433  EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
4434            format("-(NSUInteger)indexOfObject:(id)anObject;"));
4435  EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
4436  EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
4437  EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
4438            format("-(NSInteger)Method3:(id)anObject;"));
4439  EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
4440            format("-(NSInteger)Method4:(id)anObject;"));
4441  EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
4442            format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
4443  EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
4444            format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
4445  EXPECT_EQ(
4446      "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;",
4447      format(
4448          "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;"));
4449
4450  // Very long objectiveC method declaration.
4451  verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
4452               "                    inRange:(NSRange)range\n"
4453               "                   outRange:(NSRange)out_range\n"
4454               "                  outRange1:(NSRange)out_range1\n"
4455               "                  outRange2:(NSRange)out_range2\n"
4456               "                  outRange3:(NSRange)out_range3\n"
4457               "                  outRange4:(NSRange)out_range4\n"
4458               "                  outRange5:(NSRange)out_range5\n"
4459               "                  outRange6:(NSRange)out_range6\n"
4460               "                  outRange7:(NSRange)out_range7\n"
4461               "                  outRange8:(NSRange)out_range8\n"
4462               "                  outRange9:(NSRange)out_range9;");
4463
4464  verifyFormat("- (int)sum:(vector<int>)numbers;");
4465  verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
4466  // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
4467  // protocol lists (but not for template classes):
4468  //verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
4469
4470  verifyFormat("- (int (*)())foo:(int (*)())f;");
4471  verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
4472
4473  // If there's no return type (very rare in practice!), LLVM and Google style
4474  // agree.
4475  verifyFormat("- foo;");
4476  verifyFormat("- foo:(int)f;");
4477  verifyGoogleFormat("- foo:(int)foo;");
4478}
4479
4480TEST_F(FormatTest, FormatObjCBlocks) {
4481  verifyFormat("int (^Block)(int, int);");
4482  verifyFormat("int (^Block1)(int, int) = ^(int i, int j)");
4483}
4484
4485TEST_F(FormatTest, FormatObjCInterface) {
4486  verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
4487               "@public\n"
4488               "  int field1;\n"
4489               "@protected\n"
4490               "  int field2;\n"
4491               "@private\n"
4492               "  int field3;\n"
4493               "@package\n"
4494               "  int field4;\n"
4495               "}\n"
4496               "+ (id)init;\n"
4497               "@end");
4498
4499  verifyGoogleFormat("@interface Foo : NSObject<NSSomeDelegate> {\n"
4500                     " @public\n"
4501                     "  int field1;\n"
4502                     " @protected\n"
4503                     "  int field2;\n"
4504                     " @private\n"
4505                     "  int field3;\n"
4506                     " @package\n"
4507                     "  int field4;\n"
4508                     "}\n"
4509                     "+ (id)init;\n"
4510                     "@end");
4511
4512  verifyFormat("@interface /* wait for it */ Foo\n"
4513               "+ (id)init;\n"
4514               "// Look, a comment!\n"
4515               "- (int)answerWith:(int)i;\n"
4516               "@end");
4517
4518  verifyFormat("@interface Foo\n"
4519               "@end\n"
4520               "@interface Bar\n"
4521               "@end");
4522
4523  verifyFormat("@interface Foo : Bar\n"
4524               "+ (id)init;\n"
4525               "@end");
4526
4527  verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
4528               "+ (id)init;\n"
4529               "@end");
4530
4531  verifyGoogleFormat("@interface Foo : Bar<Baz, Quux>\n"
4532                     "+ (id)init;\n"
4533                     "@end");
4534
4535  verifyFormat("@interface Foo (HackStuff)\n"
4536               "+ (id)init;\n"
4537               "@end");
4538
4539  verifyFormat("@interface Foo ()\n"
4540               "+ (id)init;\n"
4541               "@end");
4542
4543  verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
4544               "+ (id)init;\n"
4545               "@end");
4546
4547  verifyGoogleFormat("@interface Foo (HackStuff)<MyProtocol>\n"
4548                     "+ (id)init;\n"
4549                     "@end");
4550
4551  verifyFormat("@interface Foo {\n"
4552               "  int _i;\n"
4553               "}\n"
4554               "+ (id)init;\n"
4555               "@end");
4556
4557  verifyFormat("@interface Foo : Bar {\n"
4558               "  int _i;\n"
4559               "}\n"
4560               "+ (id)init;\n"
4561               "@end");
4562
4563  verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
4564               "  int _i;\n"
4565               "}\n"
4566               "+ (id)init;\n"
4567               "@end");
4568
4569  verifyFormat("@interface Foo (HackStuff) {\n"
4570               "  int _i;\n"
4571               "}\n"
4572               "+ (id)init;\n"
4573               "@end");
4574
4575  verifyFormat("@interface Foo () {\n"
4576               "  int _i;\n"
4577               "}\n"
4578               "+ (id)init;\n"
4579               "@end");
4580
4581  verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
4582               "  int _i;\n"
4583               "}\n"
4584               "+ (id)init;\n"
4585               "@end");
4586}
4587
4588TEST_F(FormatTest, FormatObjCImplementation) {
4589  verifyFormat("@implementation Foo : NSObject {\n"
4590               "@public\n"
4591               "  int field1;\n"
4592               "@protected\n"
4593               "  int field2;\n"
4594               "@private\n"
4595               "  int field3;\n"
4596               "@package\n"
4597               "  int field4;\n"
4598               "}\n"
4599               "+ (id)init {\n}\n"
4600               "@end");
4601
4602  verifyGoogleFormat("@implementation Foo : NSObject {\n"
4603                     " @public\n"
4604                     "  int field1;\n"
4605                     " @protected\n"
4606                     "  int field2;\n"
4607                     " @private\n"
4608                     "  int field3;\n"
4609                     " @package\n"
4610                     "  int field4;\n"
4611                     "}\n"
4612                     "+ (id)init {\n}\n"
4613                     "@end");
4614
4615  verifyFormat("@implementation Foo\n"
4616               "+ (id)init {\n"
4617               "  if (true)\n"
4618               "    return nil;\n"
4619               "}\n"
4620               "// Look, a comment!\n"
4621               "- (int)answerWith:(int)i {\n"
4622               "  return i;\n"
4623               "}\n"
4624               "+ (int)answerWith:(int)i {\n"
4625               "  return i;\n"
4626               "}\n"
4627               "@end");
4628
4629  verifyFormat("@implementation Foo\n"
4630               "@end\n"
4631               "@implementation Bar\n"
4632               "@end");
4633
4634  verifyFormat("@implementation Foo : Bar\n"
4635               "+ (id)init {\n}\n"
4636               "- (void)foo {\n}\n"
4637               "@end");
4638
4639  verifyFormat("@implementation Foo {\n"
4640               "  int _i;\n"
4641               "}\n"
4642               "+ (id)init {\n}\n"
4643               "@end");
4644
4645  verifyFormat("@implementation Foo : Bar {\n"
4646               "  int _i;\n"
4647               "}\n"
4648               "+ (id)init {\n}\n"
4649               "@end");
4650
4651  verifyFormat("@implementation Foo (HackStuff)\n"
4652               "+ (id)init {\n}\n"
4653               "@end");
4654}
4655
4656TEST_F(FormatTest, FormatObjCProtocol) {
4657  verifyFormat("@protocol Foo\n"
4658               "@property(weak) id delegate;\n"
4659               "- (NSUInteger)numberOfThings;\n"
4660               "@end");
4661
4662  verifyFormat("@protocol MyProtocol <NSObject>\n"
4663               "- (NSUInteger)numberOfThings;\n"
4664               "@end");
4665
4666  verifyGoogleFormat("@protocol MyProtocol<NSObject>\n"
4667                     "- (NSUInteger)numberOfThings;\n"
4668                     "@end");
4669
4670  verifyFormat("@protocol Foo;\n"
4671               "@protocol Bar;\n");
4672
4673  verifyFormat("@protocol Foo\n"
4674               "@end\n"
4675               "@protocol Bar\n"
4676               "@end");
4677
4678  verifyFormat("@protocol myProtocol\n"
4679               "- (void)mandatoryWithInt:(int)i;\n"
4680               "@optional\n"
4681               "- (void)optional;\n"
4682               "@required\n"
4683               "- (void)required;\n"
4684               "@optional\n"
4685               "@property(assign) int madProp;\n"
4686               "@end\n");
4687
4688  verifyFormat("@property(nonatomic, assign, readonly)\n"
4689               "    int *looooooooooooooooooooooooooooongNumber;\n"
4690               "@property(nonatomic, assign, readonly)\n"
4691               "    NSString *looooooooooooooooooooooooooooongName;");
4692}
4693
4694TEST_F(FormatTest, FormatObjCMethodDeclarations) {
4695  verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
4696               "                   rect:(NSRect)theRect\n"
4697               "               interval:(float)theInterval {\n"
4698               "}");
4699  verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
4700               "          longKeyword:(NSRect)theRect\n"
4701               "    evenLongerKeyword:(float)theInterval\n"
4702               "                error:(NSError **)theError {\n"
4703               "}");
4704}
4705
4706TEST_F(FormatTest, FormatObjCMethodExpr) {
4707  verifyFormat("[foo bar:baz];");
4708  verifyFormat("return [foo bar:baz];");
4709  verifyFormat("f([foo bar:baz]);");
4710  verifyFormat("f(2, [foo bar:baz]);");
4711  verifyFormat("f(2, a ? b : c);");
4712  verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
4713
4714  // Unary operators.
4715  verifyFormat("int a = +[foo bar:baz];");
4716  verifyFormat("int a = -[foo bar:baz];");
4717  verifyFormat("int a = ![foo bar:baz];");
4718  verifyFormat("int a = ~[foo bar:baz];");
4719  verifyFormat("int a = ++[foo bar:baz];");
4720  verifyFormat("int a = --[foo bar:baz];");
4721  verifyFormat("int a = sizeof [foo bar:baz];");
4722  verifyFormat("int a = alignof [foo bar:baz];", getGoogleStyle());
4723  verifyFormat("int a = &[foo bar:baz];");
4724  verifyFormat("int a = *[foo bar:baz];");
4725  // FIXME: Make casts work, without breaking f()[4].
4726  //verifyFormat("int a = (int)[foo bar:baz];");
4727  //verifyFormat("return (int)[foo bar:baz];");
4728  //verifyFormat("(void)[foo bar:baz];");
4729  verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
4730
4731  // Binary operators.
4732  verifyFormat("[foo bar:baz], [foo bar:baz];");
4733  verifyFormat("[foo bar:baz] = [foo bar:baz];");
4734  verifyFormat("[foo bar:baz] *= [foo bar:baz];");
4735  verifyFormat("[foo bar:baz] /= [foo bar:baz];");
4736  verifyFormat("[foo bar:baz] %= [foo bar:baz];");
4737  verifyFormat("[foo bar:baz] += [foo bar:baz];");
4738  verifyFormat("[foo bar:baz] -= [foo bar:baz];");
4739  verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
4740  verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
4741  verifyFormat("[foo bar:baz] &= [foo bar:baz];");
4742  verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
4743  verifyFormat("[foo bar:baz] |= [foo bar:baz];");
4744  verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
4745  verifyFormat("[foo bar:baz] || [foo bar:baz];");
4746  verifyFormat("[foo bar:baz] && [foo bar:baz];");
4747  verifyFormat("[foo bar:baz] | [foo bar:baz];");
4748  verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
4749  verifyFormat("[foo bar:baz] & [foo bar:baz];");
4750  verifyFormat("[foo bar:baz] == [foo bar:baz];");
4751  verifyFormat("[foo bar:baz] != [foo bar:baz];");
4752  verifyFormat("[foo bar:baz] >= [foo bar:baz];");
4753  verifyFormat("[foo bar:baz] <= [foo bar:baz];");
4754  verifyFormat("[foo bar:baz] > [foo bar:baz];");
4755  verifyFormat("[foo bar:baz] < [foo bar:baz];");
4756  verifyFormat("[foo bar:baz] >> [foo bar:baz];");
4757  verifyFormat("[foo bar:baz] << [foo bar:baz];");
4758  verifyFormat("[foo bar:baz] - [foo bar:baz];");
4759  verifyFormat("[foo bar:baz] + [foo bar:baz];");
4760  verifyFormat("[foo bar:baz] * [foo bar:baz];");
4761  verifyFormat("[foo bar:baz] / [foo bar:baz];");
4762  verifyFormat("[foo bar:baz] % [foo bar:baz];");
4763  // Whew!
4764
4765  verifyFormat("return in[42];");
4766  verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
4767               "}");
4768
4769  verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
4770  verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
4771  verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
4772  verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
4773  verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
4774  verifyFormat("[button setAction:@selector(zoomOut:)];");
4775  verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
4776
4777  verifyFormat("arr[[self indexForFoo:a]];");
4778  verifyFormat("throw [self errorFor:a];");
4779  verifyFormat("@throw [self errorFor:a];");
4780
4781  verifyFormat("[(id)foo bar:(id)baz quux:(id)snorf];");
4782  verifyFormat("[(id)foo bar:(id) ? baz : quux];");
4783  verifyFormat("4 > 4 ? (id)a : (id)baz;");
4784
4785  // This tests that the formatter doesn't break after "backing" but before ":",
4786  // which would be at 80 columns.
4787  verifyFormat(
4788      "void f() {\n"
4789      "  if ((self = [super initWithContentRect:contentRect\n"
4790      "                               styleMask:styleMask ?: otherMask\n"
4791      "                                 backing:NSBackingStoreBuffered\n"
4792      "                                   defer:YES]))");
4793
4794  verifyFormat(
4795      "[foo checkThatBreakingAfterColonWorksOk:\n"
4796      "         [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
4797
4798  verifyFormat("[myObj short:arg1 // Force line break\n"
4799               "          longKeyword:arg2 != nil ? arg2 : @\"longKeyword\"\n"
4800               "    evenLongerKeyword:arg3 ?: @\"evenLongerKeyword\"\n"
4801               "                error:arg4];");
4802  verifyFormat(
4803      "void f() {\n"
4804      "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
4805      "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
4806      "                                     pos.width(), pos.height())\n"
4807      "                styleMask:NSBorderlessWindowMask\n"
4808      "                  backing:NSBackingStoreBuffered\n"
4809      "                    defer:NO]);\n"
4810      "}");
4811  verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
4812               "                             with:contentsNativeView];");
4813
4814  verifyFormat(
4815      "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
4816      "           owner:nillllll];");
4817
4818  verifyFormat(
4819      "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
4820      "        forType:kBookmarkButtonDragType];");
4821
4822  verifyFormat("[defaultCenter addObserver:self\n"
4823               "                  selector:@selector(willEnterFullscreen)\n"
4824               "                      name:kWillEnterFullscreenNotification\n"
4825               "                    object:nil];");
4826  verifyFormat("[image_rep drawInRect:drawRect\n"
4827               "             fromRect:NSZeroRect\n"
4828               "            operation:NSCompositeCopy\n"
4829               "             fraction:1.0\n"
4830               "       respectFlipped:NO\n"
4831               "                hints:nil];");
4832
4833  verifyFormat(
4834      "scoped_nsobject<NSTextField> message(\n"
4835      "    // The frame will be fixed up when |-setMessageText:| is called.\n"
4836      "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
4837  verifyFormat("[self aaaaaa:bbbbbbbbbbbbb\n"
4838               "    aaaaaaaaaa:bbbbbbbbbbbbbbbbb\n"
4839               "         aaaaa:bbbbbbbbbbb + bbbbbbbbbbbb\n"
4840               "          aaaa:bbb];");
4841}
4842
4843TEST_F(FormatTest, ObjCAt) {
4844  verifyFormat("@autoreleasepool");
4845  verifyFormat("@catch");
4846  verifyFormat("@class");
4847  verifyFormat("@compatibility_alias");
4848  verifyFormat("@defs");
4849  verifyFormat("@dynamic");
4850  verifyFormat("@encode");
4851  verifyFormat("@end");
4852  verifyFormat("@finally");
4853  verifyFormat("@implementation");
4854  verifyFormat("@import");
4855  verifyFormat("@interface");
4856  verifyFormat("@optional");
4857  verifyFormat("@package");
4858  verifyFormat("@private");
4859  verifyFormat("@property");
4860  verifyFormat("@protected");
4861  verifyFormat("@protocol");
4862  verifyFormat("@public");
4863  verifyFormat("@required");
4864  verifyFormat("@selector");
4865  verifyFormat("@synchronized");
4866  verifyFormat("@synthesize");
4867  verifyFormat("@throw");
4868  verifyFormat("@try");
4869
4870  EXPECT_EQ("@interface", format("@ interface"));
4871
4872  // The precise formatting of this doesn't matter, nobody writes code like
4873  // this.
4874  verifyFormat("@ /*foo*/ interface");
4875}
4876
4877TEST_F(FormatTest, ObjCSnippets) {
4878  verifyFormat("@autoreleasepool {\n"
4879               "  foo();\n"
4880               "}");
4881  verifyFormat("@class Foo, Bar;");
4882  verifyFormat("@compatibility_alias AliasName ExistingClass;");
4883  verifyFormat("@dynamic textColor;");
4884  verifyFormat("char *buf1 = @encode(int *);");
4885  verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
4886  verifyFormat("char *buf1 = @encode(int **);");
4887  verifyFormat("Protocol *proto = @protocol(p1);");
4888  verifyFormat("SEL s = @selector(foo:);");
4889  verifyFormat("@synchronized(self) {\n"
4890               "  f();\n"
4891               "}");
4892
4893  verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
4894  verifyGoogleFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
4895
4896  verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
4897  verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
4898  verifyGoogleFormat("@property(assign, getter=isEditable) BOOL editable;");
4899
4900  verifyFormat("@import foo.bar;\n"
4901               "@import baz;");
4902}
4903
4904TEST_F(FormatTest, ObjCLiterals) {
4905  verifyFormat("@\"String\"");
4906  verifyFormat("@1");
4907  verifyFormat("@+4.8");
4908  verifyFormat("@-4");
4909  verifyFormat("@1LL");
4910  verifyFormat("@.5");
4911  verifyFormat("@'c'");
4912  verifyFormat("@true");
4913
4914  verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
4915  verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
4916  verifyFormat("NSNumber *favoriteColor = @(Green);");
4917  verifyFormat("NSString *path = @(getenv(\"PATH\"));");
4918
4919  verifyFormat("@[");
4920  verifyFormat("@[]");
4921  verifyFormat(
4922      "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
4923  verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
4924
4925  verifyFormat("@{");
4926  verifyFormat("@{}");
4927  verifyFormat("@{ @\"one\" : @1 }");
4928  verifyFormat("return @{ @\"one\" : @1 };");
4929  verifyFormat("@{ @\"one\" : @1, }");
4930
4931  verifyFormat("@{ @\"one\" : @{ @2 : @1 } }");
4932  verifyFormat("@{ @\"one\" : @{ @2 : @1 }, }");
4933
4934  verifyFormat("@{ 1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2 }");
4935  verifyFormat("[self setDict:@{}");
4936  verifyFormat("[self setDict:@{ @1 : @2 }");
4937  verifyFormat("NSLog(@\"%@\", @{ @1 : @2, @2 : @3 }[@1]);");
4938  verifyFormat(
4939      "NSDictionary *masses = @{ @\"H\" : @1.0078, @\"He\" : @4.0026 };");
4940  verifyFormat(
4941      "NSDictionary *settings = @{ AVEncoderKey : @(AVAudioQualityMax) };");
4942
4943  // FIXME: Nested and multi-line array and dictionary literals need more work.
4944  verifyFormat(
4945      "NSDictionary *d = @{ @\"nam\" : NSUserNam(), @\"dte\" : [NSDate date],\n"
4946      "                     @\"processInfo\" : [NSProcessInfo processInfo] };");
4947  verifyFormat(
4948      "@{ NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :\n"
4949      "   regularFont, };");
4950
4951}
4952
4953TEST_F(FormatTest, ReformatRegionAdjustsIndent) {
4954  EXPECT_EQ("{\n"
4955            "{\n"
4956            "a;\n"
4957            "b;\n"
4958            "}\n"
4959            "}",
4960            format("{\n"
4961                   "{\n"
4962                   "a;\n"
4963                   "     b;\n"
4964                   "}\n"
4965                   "}",
4966                   13, 2, getLLVMStyle()));
4967  EXPECT_EQ("{\n"
4968            "{\n"
4969            "  a;\n"
4970            "b;\n"
4971            "}\n"
4972            "}",
4973            format("{\n"
4974                   "{\n"
4975                   "     a;\n"
4976                   "b;\n"
4977                   "}\n"
4978                   "}",
4979                   9, 2, getLLVMStyle()));
4980  EXPECT_EQ("{\n"
4981            "{\n"
4982            "public:\n"
4983            "  b;\n"
4984            "}\n"
4985            "}",
4986            format("{\n"
4987                   "{\n"
4988                   "public:\n"
4989                   "     b;\n"
4990                   "}\n"
4991                   "}",
4992                   17, 2, getLLVMStyle()));
4993  EXPECT_EQ("{\n"
4994            "{\n"
4995            "a;\n"
4996            "}\n"
4997            "{\n"
4998            "  b; //\n"
4999            "}\n"
5000            "}",
5001            format("{\n"
5002                   "{\n"
5003                   "a;\n"
5004                   "}\n"
5005                   "{\n"
5006                   "           b; //\n"
5007                   "}\n"
5008                   "}",
5009                   22, 2, getLLVMStyle()));
5010  EXPECT_EQ("  {\n"
5011            "    a; //\n"
5012            "  }",
5013            format("  {\n"
5014                   "a; //\n"
5015                   "  }",
5016                   4, 2, getLLVMStyle()));
5017  EXPECT_EQ("void f() {}\n"
5018            "void g() {}",
5019            format("void f() {}\n"
5020                   "void g() {}",
5021                   13, 0, getLLVMStyle()));
5022  EXPECT_EQ("int a; // comment\n"
5023            "       // line 2\n"
5024            "int b;",
5025            format("int a; // comment\n"
5026                   "       // line 2\n"
5027                   "  int b;",
5028                   35, 0, getLLVMStyle()));
5029  EXPECT_EQ("  int a;\n"
5030            "  void\n"
5031            "  ffffff() {\n"
5032            "  }",
5033            format("  int a;\n"
5034                   "void ffffff() {}",
5035                   11, 0, getLLVMStyleWithColumns(11)));
5036}
5037
5038TEST_F(FormatTest, BreakStringLiterals) {
5039  EXPECT_EQ("\"some text \"\n"
5040            "\"other\";",
5041            format("\"some text other\";", getLLVMStyleWithColumns(12)));
5042  EXPECT_EQ("\"some text \"\n"
5043            "\"other\";",
5044            format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
5045  EXPECT_EQ(
5046      "#define A  \\\n"
5047      "  \"some \"  \\\n"
5048      "  \"text \"  \\\n"
5049      "  \"other\";",
5050      format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
5051  EXPECT_EQ(
5052      "#define A  \\\n"
5053      "  \"so \"    \\\n"
5054      "  \"text \"  \\\n"
5055      "  \"other\";",
5056      format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
5057
5058  EXPECT_EQ("\"some text\"",
5059            format("\"some text\"", getLLVMStyleWithColumns(1)));
5060  EXPECT_EQ("\"some text\"",
5061            format("\"some text\"", getLLVMStyleWithColumns(11)));
5062  EXPECT_EQ("\"some \"\n"
5063            "\"text\"",
5064            format("\"some text\"", getLLVMStyleWithColumns(10)));
5065  EXPECT_EQ("\"some \"\n"
5066            "\"text\"",
5067            format("\"some text\"", getLLVMStyleWithColumns(7)));
5068  EXPECT_EQ("\"some\"\n"
5069            "\" tex\"\n"
5070            "\"t\"",
5071            format("\"some text\"", getLLVMStyleWithColumns(6)));
5072  EXPECT_EQ("\"some\"\n"
5073            "\" tex\"\n"
5074            "\" and\"",
5075            format("\"some tex and\"", getLLVMStyleWithColumns(6)));
5076  EXPECT_EQ("\"some\"\n"
5077            "\"/tex\"\n"
5078            "\"/and\"",
5079            format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
5080
5081  EXPECT_EQ("variable =\n"
5082            "    \"long string \"\n"
5083            "    \"literal\";",
5084            format("variable = \"long string literal\";",
5085                   getLLVMStyleWithColumns(20)));
5086
5087  EXPECT_EQ("variable = f(\n"
5088            "    \"long string \"\n"
5089            "    \"literal\",\n"
5090            "    short,\n"
5091            "    loooooooooooooooooooong);",
5092            format("variable = f(\"long string literal\", short, "
5093                   "loooooooooooooooooooong);",
5094                   getLLVMStyleWithColumns(20)));
5095
5096  EXPECT_EQ("f(g(\"long string \"\n"
5097            "    \"literal\"),\n"
5098            "  b);",
5099            format("f(g(\"long string literal\"), b);",
5100                   getLLVMStyleWithColumns(20)));
5101  EXPECT_EQ("f(g(\"long string \"\n"
5102            "    \"literal\",\n"
5103            "    a),\n"
5104            "  b);",
5105            format("f(g(\"long string literal\", a), b);",
5106                   getLLVMStyleWithColumns(20)));
5107  EXPECT_EQ(
5108      "f(\"one two\".split(\n"
5109      "    variable));",
5110      format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
5111  EXPECT_EQ("f(\"one two three four five six \"\n"
5112            "  \"seven\".split(\n"
5113            "      really_looooong_variable));",
5114            format("f(\"one two three four five six seven\"."
5115                   "split(really_looooong_variable));",
5116                   getLLVMStyleWithColumns(33)));
5117
5118  EXPECT_EQ("f(\"some \"\n"
5119            "  \"text\",\n"
5120            "  other);",
5121            format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
5122
5123  // Only break as a last resort.
5124  verifyFormat(
5125      "aaaaaaaaaaaaaaaaaaaa(\n"
5126      "    aaaaaaaaaaaaaaaaaaaa,\n"
5127      "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
5128
5129  EXPECT_EQ(
5130      "\"splitmea\"\n"
5131      "\"trandomp\"\n"
5132      "\"oint\"",
5133      format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
5134
5135  EXPECT_EQ(
5136      "\"split/\"\n"
5137      "\"pathat/\"\n"
5138      "\"slashes\"",
5139      format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
5140
5141  EXPECT_EQ(
5142      "\"split/\"\n"
5143      "\"pathat/\"\n"
5144      "\"slashes\"",
5145      format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
5146  EXPECT_EQ("\"split at \"\n"
5147            "\"spaces/at/\"\n"
5148            "\"slashes.at.any$\"\n"
5149            "\"non-alphanumeric%\"\n"
5150            "\"1111111111characte\"\n"
5151            "\"rs\"",
5152            format("\"split at "
5153                   "spaces/at/"
5154                   "slashes.at."
5155                   "any$non-"
5156                   "alphanumeric%"
5157                   "1111111111characte"
5158                   "rs\"",
5159                   getLLVMStyleWithColumns(20)));
5160
5161  // Verify that splitting the strings understands
5162  // Style::AlwaysBreakBeforeMultilineStrings.
5163  EXPECT_EQ("aaaaaaaaaaaa(aaaaaaaaaaaaa,\n"
5164            "             \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
5165            "             \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
5166            format("aaaaaaaaaaaa(aaaaaaaaaaaaa, \"aaaaaaaaaaaaaaaaaaaaaa "
5167                   "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa "
5168                   "aaaaaaaaaaaaaaaaaaaaaa\");",
5169                   getGoogleStyle()));
5170  EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
5171            "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
5172            format("llvm::outs() << "
5173                   "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
5174                   "aaaaaaaaaaaaaaaaaaa\";"));
5175
5176  FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
5177  AlignLeft.AlignEscapedNewlinesLeft = true;
5178  EXPECT_EQ(
5179      "#define A \\\n"
5180      "  \"some \" \\\n"
5181      "  \"text \" \\\n"
5182      "  \"other\";",
5183      format("#define A \"some text other\";", AlignLeft));
5184}
5185
5186TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
5187  EXPECT_EQ("aaaaaaaaaaa =\n"
5188            "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
5189            "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
5190            "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
5191            format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
5192                   "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
5193                   "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
5194}
5195
5196TEST_F(FormatTest, SkipsUnknownStringLiterals) {
5197  EXPECT_EQ(
5198      "u8\"unsupported literal\";",
5199      format("u8\"unsupported literal\";", getGoogleStyleWithColumns(15)));
5200  EXPECT_EQ("u\"unsupported literal\";",
5201            format("u\"unsupported literal\";", getGoogleStyleWithColumns(15)));
5202  EXPECT_EQ("U\"unsupported literal\";",
5203            format("U\"unsupported literal\";", getGoogleStyleWithColumns(15)));
5204  EXPECT_EQ("L\"unsupported literal\";",
5205            format("L\"unsupported literal\";", getGoogleStyleWithColumns(15)));
5206  EXPECT_EQ("R\"x(raw literal)x\";",
5207            format("R\"x(raw literal)x\";", getGoogleStyleWithColumns(15)));
5208  verifyFormat("string a = \"unterminated;");
5209  EXPECT_EQ("function(\"unterminated,\n"
5210            "         OtherParameter);",
5211            format("function(  \"unterminated,\n"
5212                   "    OtherParameter);"));
5213}
5214
5215TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
5216  EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
5217            format("#define x(_a) printf(\"foo\"_a);", getLLVMStyle()));
5218}
5219
5220TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
5221  EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
5222            "             \"ddeeefff\");",
5223            format("someFunction(\"aaabbbcccdddeeefff\");",
5224                   getLLVMStyleWithColumns(25)));
5225  EXPECT_EQ("someFunction1234567890(\n"
5226            "    \"aaabbbcccdddeeefff\");",
5227            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
5228                   getLLVMStyleWithColumns(26)));
5229  EXPECT_EQ("someFunction1234567890(\n"
5230            "    \"aaabbbcccdddeeeff\"\n"
5231            "    \"f\");",
5232            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
5233                   getLLVMStyleWithColumns(25)));
5234  EXPECT_EQ("someFunction1234567890(\n"
5235            "    \"aaabbbcccdddeeeff\"\n"
5236            "    \"f\");",
5237            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
5238                   getLLVMStyleWithColumns(24)));
5239  EXPECT_EQ("someFunction(\n"
5240            "    \"aaabbbcc \"\n"
5241            "    \"dddeeefff\");",
5242            format("someFunction(\"aaabbbcc dddeeefff\");",
5243                   getLLVMStyleWithColumns(25)));
5244  EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
5245            "             \"ddeeefff\");",
5246            format("someFunction(\"aaabbbccc ddeeefff\");",
5247                   getLLVMStyleWithColumns(25)));
5248  EXPECT_EQ("someFunction1234567890(\n"
5249            "    \"aaabb \"\n"
5250            "    \"cccdddeeefff\");",
5251            format("someFunction1234567890(\"aaabb cccdddeeefff\");",
5252                   getLLVMStyleWithColumns(25)));
5253  EXPECT_EQ("#define A          \\\n"
5254            "  string s =       \\\n"
5255            "      \"123456789\"  \\\n"
5256            "      \"0\";         \\\n"
5257            "  int i;",
5258            format("#define A string s = \"1234567890\"; int i;",
5259                   getLLVMStyleWithColumns(20)));
5260}
5261
5262TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
5263  EXPECT_EQ("\"\\a\"",
5264            format("\"\\a\"", getLLVMStyleWithColumns(3)));
5265  EXPECT_EQ("\"\\\"",
5266            format("\"\\\"", getLLVMStyleWithColumns(2)));
5267  EXPECT_EQ("\"test\"\n"
5268            "\"\\n\"",
5269            format("\"test\\n\"", getLLVMStyleWithColumns(7)));
5270  EXPECT_EQ("\"tes\\\\\"\n"
5271            "\"n\"",
5272            format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
5273  EXPECT_EQ("\"\\\\\\\\\"\n"
5274            "\"\\n\"",
5275            format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
5276  EXPECT_EQ("\"\\uff01\"",
5277            format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
5278  EXPECT_EQ("\"\\uff01\"\n"
5279            "\"test\"",
5280            format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
5281  EXPECT_EQ("\"\\Uff01ff02\"",
5282            format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
5283  EXPECT_EQ("\"\\x000000000001\"\n"
5284            "\"next\"",
5285            format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
5286  EXPECT_EQ("\"\\x000000000001next\"",
5287            format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
5288  EXPECT_EQ("\"\\x000000000001\"",
5289            format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
5290  EXPECT_EQ("\"test\"\n"
5291            "\"\\000000\"\n"
5292            "\"000001\"",
5293            format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
5294  EXPECT_EQ("\"test\\000\"\n"
5295            "\"00000000\"\n"
5296            "\"1\"",
5297            format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
5298  EXPECT_EQ("R\"(\\x\\x00)\"\n",
5299            format("R\"(\\x\\x00)\"\n", getGoogleStyleWithColumns(7)));
5300}
5301
5302TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
5303  verifyFormat("void f() {\n"
5304               "  return g() {}\n"
5305               "  void h() {}");
5306  verifyFormat("if (foo)\n"
5307               "  return { forgot_closing_brace();\n"
5308               "test();");
5309  verifyFormat("int a[] = { void forgot_closing_brace() { f();\n"
5310               "g();\n"
5311               "}");
5312}
5313
5314TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
5315  verifyFormat("class X {\n"
5316               "  void f() {\n"
5317               "  }\n"
5318               "};",
5319               getLLVMStyleWithColumns(12));
5320}
5321
5322TEST_F(FormatTest, ConfigurableIndentWidth) {
5323  FormatStyle EightIndent = getLLVMStyleWithColumns(18);
5324  EightIndent.IndentWidth = 8;
5325  verifyFormat("void f() {\n"
5326               "        someFunction();\n"
5327               "        if (true) {\n"
5328               "                f();\n"
5329               "        }\n"
5330               "}",
5331               EightIndent);
5332  verifyFormat("class X {\n"
5333               "        void f() {\n"
5334               "        }\n"
5335               "};",
5336               EightIndent);
5337  verifyFormat("int x[] = {\n"
5338               "        call(),\n"
5339               "        call(),\n"
5340               "};",
5341               EightIndent);
5342}
5343
5344TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
5345  verifyFormat("void\n"
5346               "f();",
5347               getLLVMStyleWithColumns(8));
5348}
5349
5350TEST_F(FormatTest, ConfigurableUseOfTab) {
5351  FormatStyle Tab = getLLVMStyleWithColumns(42);
5352  Tab.IndentWidth = 8;
5353  Tab.UseTab = true;
5354  Tab.AlignEscapedNewlinesLeft = true;
5355  verifyFormat("class X {\n"
5356               "\tvoid f() {\n"
5357               "\t\tsomeFunction(parameter1,\n"
5358               "\t\t\t     parameter2);\n"
5359               "\t}\n"
5360               "};",
5361               Tab);
5362  verifyFormat("#define A                        \\\n"
5363               "\tvoid f() {               \\\n"
5364               "\t\tsomeFunction(    \\\n"
5365               "\t\t    parameter1,  \\\n"
5366               "\t\t    parameter2); \\\n"
5367               "\t}",
5368               Tab);
5369
5370
5371  // FIXME: To correctly count mixed whitespace we need to
5372  // also correctly count mixed whitespace in front of the comment.
5373  //
5374  // EXPECT_EQ("/*\n"
5375  //           "\t      a\t\tcomment\n"
5376  //           "\t      in multiple lines\n"
5377  //           "       */",
5378  //           format("   /*\t \t \n"
5379  //                  " \t \t a\t\tcomment\t \t\n"
5380  //                  " \t \t in multiple lines\t\n"
5381  //                  " \t  */",
5382  //                  Tab));
5383  // Tab.UseTab = false;
5384  // EXPECT_EQ("/*\n"
5385  //           "              a\t\tcomment\n"
5386  //           "              in multiple lines\n"
5387  //           "       */",
5388  //           format("   /*\t \t \n"
5389  //                  " \t \t a\t\tcomment\t \t\n"
5390  //                  " \t \t in multiple lines\t\n"
5391  //                  " \t  */",
5392  //                  Tab));
5393  // EXPECT_EQ("/* some\n"
5394  //           "   comment */",
5395  //          format(" \t \t /* some\n"
5396  //                 " \t \t    comment */",
5397  //                 Tab));
5398
5399  EXPECT_EQ("{\n"
5400            "  /*\n"
5401            "   * Comment\n"
5402            "   */\n"
5403            "  int i;\n"
5404            "}",
5405            format("{\n"
5406                   "\t/*\n"
5407                   "\t * Comment\n"
5408                   "\t */\n"
5409                   "\t int i;\n"
5410                   "}"));
5411}
5412
5413TEST_F(FormatTest, LinuxBraceBreaking) {
5414  FormatStyle BreakBeforeBrace = getLLVMStyle();
5415  BreakBeforeBrace.BreakBeforeBraces = FormatStyle::BS_Linux;
5416  verifyFormat("namespace a\n"
5417               "{\n"
5418               "class A\n"
5419               "{\n"
5420               "  void f()\n"
5421               "  {\n"
5422               "    if (true) {\n"
5423               "      a();\n"
5424               "      b();\n"
5425               "    }\n"
5426               "  }\n"
5427               "  void g()\n"
5428               "  {\n"
5429               "    return;\n"
5430               "  }\n"
5431               "}\n"
5432               "}",
5433               BreakBeforeBrace);
5434}
5435
5436TEST_F(FormatTest, StroustrupBraceBreaking) {
5437  FormatStyle BreakBeforeBrace = getLLVMStyle();
5438  BreakBeforeBrace.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
5439  verifyFormat("namespace a {\n"
5440               "class A {\n"
5441               "  void f()\n"
5442               "  {\n"
5443               "    if (true) {\n"
5444               "      a();\n"
5445               "      b();\n"
5446               "    }\n"
5447               "  }\n"
5448               "  void g()\n"
5449               "  {\n"
5450               "    return;\n"
5451               "  }\n"
5452               "}\n"
5453               "}",
5454               BreakBeforeBrace);
5455}
5456
5457TEST_F(FormatTest, AllmanBraceBreaking) {
5458  FormatStyle BreakBeforeBrace = getLLVMStyle();
5459  BreakBeforeBrace.BreakBeforeBraces = FormatStyle::BS_Allman;
5460  verifyFormat("namespace a\n"
5461               "{\n"
5462               "class A\n"
5463               "{\n"
5464               "  void f()\n"
5465               "  {\n"
5466               "    if (true)\n"
5467               "    {\n"
5468               "      a();\n"
5469               "      b();\n"
5470               "    }\n"
5471               "  }\n"
5472               "  void g()\n"
5473               "  {\n"
5474               "    return;\n"
5475               "  }\n"
5476               "}\n"
5477               "}",
5478               BreakBeforeBrace);
5479
5480  verifyFormat("void f()\n"
5481               "{\n"
5482               "  if (true)\n"
5483               "  {\n"
5484               "    a();\n"
5485               "  }\n"
5486               "  else if (false)\n"
5487               "  {\n"
5488               "    b();\n"
5489               "  }\n"
5490               "  else\n"
5491               "  {\n"
5492               "    c();\n"
5493               "  }\n"
5494               "}\n",
5495               BreakBeforeBrace);
5496
5497  verifyFormat("void f()\n"
5498               "{\n"
5499               "  for (int i = 0; i < 10; ++i)\n"
5500               "  {\n"
5501               "    a();\n"
5502               "  }\n"
5503               "  while (false)\n"
5504               "  {\n"
5505               "    b();\n"
5506               "  }\n"
5507               "  do\n"
5508               "  {\n"
5509               "    c();\n"
5510               "  } while (false)\n"
5511               "}\n",
5512               BreakBeforeBrace);
5513
5514  verifyFormat("void f(int a)\n"
5515               "{\n"
5516               "  switch (a)\n"
5517               "  {\n"
5518               "  case 0:\n"
5519               "    break;\n"
5520               "  case 1:\n"
5521               "  {\n"
5522               "    break;\n"
5523               "  }\n"
5524               "  case 2:\n"
5525               "  {\n"
5526               "  }\n"
5527               "  break;\n"
5528               "  default:\n"
5529               "    break;\n"
5530               "  }\n"
5531               "}\n",
5532               BreakBeforeBrace);
5533
5534  verifyFormat("enum X\n"
5535               "{\n"
5536               "  Y = 0,\n"
5537               "}\n",
5538               BreakBeforeBrace);
5539
5540  FormatStyle BreakBeforeBraceShortIfs = BreakBeforeBrace;
5541  BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine = true;
5542  BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
5543  verifyFormat("void f(bool b)\n"
5544               "{\n"
5545               "  if (b)\n"
5546               "  {\n"
5547               "    return;\n"
5548               "  }\n"
5549               "}\n",
5550               BreakBeforeBraceShortIfs);
5551  verifyFormat("void f(bool b)\n"
5552               "{\n"
5553               "  if (b) return;\n"
5554               "}\n",
5555               BreakBeforeBraceShortIfs);
5556  verifyFormat("void f(bool b)\n"
5557               "{\n"
5558               "  while (b)\n"
5559               "  {\n"
5560               "    return;\n"
5561               "  }\n"
5562               "}\n",
5563               BreakBeforeBraceShortIfs);
5564}
5565
5566TEST_F(FormatTest, UnderstandsPragmas) {
5567  verifyFormat("#pragma omp reduction(| : var)");
5568  verifyFormat("#pragma omp reduction(+ : var)");
5569}
5570
5571bool allStylesEqual(ArrayRef<FormatStyle> Styles) {
5572  for (size_t i = 1; i < Styles.size(); ++i)
5573    if (!(Styles[0] == Styles[i]))
5574      return false;
5575  return true;
5576}
5577
5578TEST_F(FormatTest, GetsPredefinedStyleByName) {
5579  FormatStyle Styles[3];
5580
5581  Styles[0] = getLLVMStyle();
5582  EXPECT_TRUE(getPredefinedStyle("LLVM", &Styles[1]));
5583  EXPECT_TRUE(getPredefinedStyle("lLvM", &Styles[2]));
5584  EXPECT_TRUE(allStylesEqual(Styles));
5585
5586  Styles[0] = getGoogleStyle();
5587  EXPECT_TRUE(getPredefinedStyle("Google", &Styles[1]));
5588  EXPECT_TRUE(getPredefinedStyle("gOOgle", &Styles[2]));
5589  EXPECT_TRUE(allStylesEqual(Styles));
5590
5591  Styles[0] = getChromiumStyle();
5592  EXPECT_TRUE(getPredefinedStyle("Chromium", &Styles[1]));
5593  EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", &Styles[2]));
5594  EXPECT_TRUE(allStylesEqual(Styles));
5595
5596  Styles[0] = getMozillaStyle();
5597  EXPECT_TRUE(getPredefinedStyle("Mozilla", &Styles[1]));
5598  EXPECT_TRUE(getPredefinedStyle("moZILla", &Styles[2]));
5599  EXPECT_TRUE(allStylesEqual(Styles));
5600
5601  Styles[0] = getWebKitStyle();
5602  EXPECT_TRUE(getPredefinedStyle("WebKit", &Styles[1]));
5603  EXPECT_TRUE(getPredefinedStyle("wEbKit", &Styles[2]));
5604  EXPECT_TRUE(allStylesEqual(Styles));
5605
5606  EXPECT_FALSE(getPredefinedStyle("qwerty", &Styles[0]));
5607}
5608
5609TEST_F(FormatTest, ParsesConfiguration) {
5610  FormatStyle Style = {};
5611#define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
5612  EXPECT_NE(VALUE, Style.FIELD);                                               \
5613  EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
5614  EXPECT_EQ(VALUE, Style.FIELD)
5615
5616#define CHECK_PARSE_BOOL(FIELD)                                                \
5617  Style.FIELD = false;                                                         \
5618  EXPECT_EQ(0, parseConfiguration(#FIELD ": true", &Style).value());           \
5619  EXPECT_TRUE(Style.FIELD);                                                    \
5620  EXPECT_EQ(0, parseConfiguration(#FIELD ": false", &Style).value());          \
5621  EXPECT_FALSE(Style.FIELD);
5622
5623  CHECK_PARSE_BOOL(AlignEscapedNewlinesLeft);
5624  CHECK_PARSE_BOOL(AlignTrailingComments);
5625  CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
5626  CHECK_PARSE_BOOL(AllowShortIfStatementsOnASingleLine);
5627  CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
5628  CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
5629  CHECK_PARSE_BOOL(BinPackParameters);
5630  CHECK_PARSE_BOOL(BreakBeforeBinaryOperators);
5631  CHECK_PARSE_BOOL(BreakConstructorInitializersBeforeComma);
5632  CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
5633  CHECK_PARSE_BOOL(DerivePointerBinding);
5634  CHECK_PARSE_BOOL(IndentCaseLabels);
5635  CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
5636  CHECK_PARSE_BOOL(PointerBindsToType);
5637  CHECK_PARSE_BOOL(Cpp11BracedListStyle);
5638  CHECK_PARSE_BOOL(UseTab);
5639  CHECK_PARSE_BOOL(IndentFunctionDeclarationAfterType);
5640
5641  CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
5642  CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
5643  CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
5644  CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
5645  CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
5646              PenaltyReturnTypeOnItsOwnLine, 1234u);
5647  CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
5648              SpacesBeforeTrailingComments, 1234u);
5649  CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
5650
5651  Style.Standard = FormatStyle::LS_Auto;
5652  CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
5653  CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
5654  CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
5655
5656  Style.ColumnLimit = 123;
5657  FormatStyle BaseStyle = getLLVMStyle();
5658  CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
5659  CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
5660
5661  Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
5662  CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
5663              FormatStyle::BS_Attach);
5664  CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
5665              FormatStyle::BS_Linux);
5666  CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
5667              FormatStyle::BS_Stroustrup);
5668
5669  Style.NamespaceIndentation = FormatStyle::NI_All;
5670  CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
5671              FormatStyle::NI_None);
5672  CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
5673              FormatStyle::NI_Inner);
5674  CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
5675              FormatStyle::NI_All);
5676
5677#undef CHECK_PARSE
5678#undef CHECK_PARSE_BOOL
5679}
5680
5681TEST_F(FormatTest, ConfigurationRoundTripTest) {
5682  FormatStyle Style = getLLVMStyle();
5683  std::string YAML = configurationAsText(Style);
5684  FormatStyle ParsedStyle = {};
5685  EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
5686  EXPECT_EQ(Style, ParsedStyle);
5687}
5688
5689TEST_F(FormatTest, WorksFor8bitEncodings) {
5690  EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
5691            "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
5692            "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
5693            "\"\xef\xee\xf0\xf3...\"",
5694            format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
5695                   "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
5696                   "\xef\xee\xf0\xf3...\"",
5697                   getLLVMStyleWithColumns(12)));
5698}
5699
5700// FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
5701#if !defined(_MSC_VER)
5702
5703TEST_F(FormatTest, CountsUTF8CharactersProperly) {
5704  verifyFormat("\"Однажды в студёную зимнюю пору...\"",
5705               getLLVMStyleWithColumns(35));
5706  verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
5707               getLLVMStyleWithColumns(21));
5708  verifyFormat("// Однажды в студёную зимнюю пору...",
5709               getLLVMStyleWithColumns(36));
5710  verifyFormat("// 一 二 三 四 五 六 七 八 九 十",
5711               getLLVMStyleWithColumns(22));
5712  verifyFormat("/* Однажды в студёную зимнюю пору... */",
5713               getLLVMStyleWithColumns(39));
5714  verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
5715               getLLVMStyleWithColumns(25));
5716}
5717
5718TEST_F(FormatTest, SplitsUTF8Strings) {
5719  EXPECT_EQ(
5720      "\"Однажды, в \"\n"
5721      "\"студёную \"\n"
5722      "\"зимнюю \"\n"
5723      "\"пору,\"",
5724      format("\"Однажды, в студёную зимнюю пору,\"",
5725             getLLVMStyleWithColumns(13)));
5726  EXPECT_EQ("\"一 二 三 四 \"\n"
5727            "\"五 六 七 八 \"\n"
5728            "\"九 十\"",
5729            format("\"一 二 三 四 五 六 七 八 九 十\"",
5730                   getLLVMStyleWithColumns(10)));
5731}
5732
5733TEST_F(FormatTest, SplitsUTF8LineComments) {
5734  EXPECT_EQ("// Я из лесу\n"
5735            "// вышел; был\n"
5736            "// сильный\n"
5737            "// мороз.",
5738            format("// Я из лесу вышел; был сильный мороз.",
5739                   getLLVMStyleWithColumns(13)));
5740  EXPECT_EQ("// 一二三\n"
5741            "// 四五六七\n"
5742            "// 八\n"
5743            "// 九 十",
5744            format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(6)));
5745}
5746
5747TEST_F(FormatTest, SplitsUTF8BlockComments) {
5748  EXPECT_EQ("/* Гляжу,\n"
5749            " * поднимается\n"
5750            " * медленно в\n"
5751            " * гору\n"
5752            " * Лошадка,\n"
5753            " * везущая\n"
5754            " * хворосту\n"
5755            " * воз. */",
5756            format("/* Гляжу, поднимается медленно в гору\n"
5757                   " * Лошадка, везущая хворосту воз. */",
5758                   getLLVMStyleWithColumns(13)));
5759  EXPECT_EQ("/* 一二三\n"
5760            " * 四五六七\n"
5761            " * 八\n"
5762            " * 九 十\n"
5763            " */",
5764            format("/* 一二三 四五六七 八  九 十 */", getLLVMStyleWithColumns(6)));
5765  EXPECT_EQ("/* �������� ��������\n"
5766            " * ��������\n"
5767            " * ������-�� */",
5768            format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
5769}
5770
5771TEST_F(FormatTest, FormatsWithWebKitStyle) {
5772  FormatStyle Style = getWebKitStyle();
5773
5774  // Don't indent in outer namespaces.
5775  verifyFormat("namespace outer {\n"
5776               "int i;\n"
5777               "namespace inner {\n"
5778               "    int i;\n"
5779               "} // namespace inner\n"
5780               "} // namespace outer\n"
5781               "namespace other_outer {\n"
5782               "int i;\n"
5783               "}",
5784               Style);
5785
5786  // Don't indent case labels.
5787  verifyFormat("switch (variable) {\n"
5788               "case 1:\n"
5789               "case 2:\n"
5790               "    doSomething();\n"
5791               "    break;\n"
5792               "default:\n"
5793               "    ++variable;\n"
5794               "}",
5795               Style);
5796
5797  // Wrap before binary operators.
5798  EXPECT_EQ(
5799      "void f()\n"
5800      "{\n"
5801      "    if (aaaaaaaaaaaaaaaa\n"
5802      "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
5803      "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
5804      "        return;\n"
5805      "}",
5806      format(
5807          "void f() {\n"
5808          "if (aaaaaaaaaaaaaaaa\n"
5809          "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
5810          "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
5811          "return;\n"
5812          "}",
5813          Style));
5814
5815  // Constructor initializers are formatted one per line with the "," on the
5816  // new line.
5817  verifyFormat("Constructor()\n"
5818               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5819               "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
5820               "                               aaaaaaaaaaaaaa)\n"
5821               "    , aaaaaaaaaaaaaaaaaaaaaaa()\n{\n}",
5822               Style);
5823
5824  // Access specifiers should be aligned left.
5825  verifyFormat("class C {\n"
5826               "public:\n"
5827               "    int i;\n"
5828               "};",
5829               Style);
5830
5831  // Do not align comments.
5832  verifyFormat("int a; // Do not\n"
5833               "double b; // align comments.",
5834               Style);
5835
5836  // Accept input's line breaks.
5837  EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
5838            "    || bbbbbbbbbbbbbbb) {\n"
5839            "    i++;\n"
5840            "}",
5841            format("if (aaaaaaaaaaaaaaa\n"
5842                   "|| bbbbbbbbbbbbbbb) { i++; }",
5843                   Style));
5844  EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
5845            "    i++;\n"
5846            "}",
5847            format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
5848}
5849
5850#endif
5851
5852} // end namespace tooling
5853} // end namespace clang
5854