FormatTest.cpp revision e8b10d3d5b90efaf60ad89e96f6500f971ceec41
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 inentation.\n"
846            "*/",
847            format("  /*\n"
848                   " Don't try to outdent if there's not enough inentation.\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
1570TEST_F(FormatTest, FormatsExternC) { verifyFormat("extern \"C\" {\nint a;"); }
1571
1572TEST_F(FormatTest, FormatsInlineASM) {
1573  verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
1574  verifyFormat(
1575      "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
1576      "    \"cpuid\\n\\t\"\n"
1577      "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
1578      "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
1579      "    : \"a\"(value));");
1580}
1581
1582TEST_F(FormatTest, FormatTryCatch) {
1583  // FIXME: Handle try-catch explicitly in the UnwrappedLineParser, then we'll
1584  // also not create single-line-blocks.
1585  verifyFormat("try {\n"
1586               "  throw a * b;\n"
1587               "}\n"
1588               "catch (int a) {\n"
1589               "  // Do nothing.\n"
1590               "}\n"
1591               "catch (...) {\n"
1592               "  exit(42);\n"
1593               "}");
1594
1595  // Function-level try statements.
1596  verifyFormat("int f() try { return 4; }\n"
1597               "catch (...) {\n"
1598               "  return 5;\n"
1599               "}");
1600  verifyFormat("class A {\n"
1601               "  int a;\n"
1602               "  A() try : a(0) {}\n"
1603               "  catch (...) {\n"
1604               "    throw;\n"
1605               "  }\n"
1606               "};\n");
1607}
1608
1609TEST_F(FormatTest, FormatObjCTryCatch) {
1610  verifyFormat("@try {\n"
1611               "  f();\n"
1612               "}\n"
1613               "@catch (NSException e) {\n"
1614               "  @throw;\n"
1615               "}\n"
1616               "@finally {\n"
1617               "  exit(42);\n"
1618               "}");
1619}
1620
1621TEST_F(FormatTest, StaticInitializers) {
1622  verifyFormat("static SomeClass SC = { 1, 'a' };");
1623
1624  verifyFormat(
1625      "static SomeClass WithALoooooooooooooooooooongName = {\n"
1626      "  100000000, \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
1627      "};");
1628
1629  verifyFormat(
1630      "static SomeClass = { a, b, c, d, e, f, g, h, i, j,\n"
1631      "                     looooooooooooooooooooooooooooooooooongname,\n"
1632      "                     looooooooooooooooooooooooooooooong };");
1633  // Allow bin-packing in static initializers as this would often lead to
1634  // terrible results, e.g.:
1635  verifyGoogleFormat(
1636      "static SomeClass = {a, b, c, d, e, f, g, h, i, j,\n"
1637      "                    looooooooooooooooooooooooooooooooooongname,\n"
1638      "                    looooooooooooooooooooooooooooooong};");
1639  // Here, everything other than the "}" would fit on a line.
1640  verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
1641               "  100000000000000000000000\n"
1642               "};");
1643  EXPECT_EQ("S s = { a, b };", format("S s = {\n"
1644                                      "  a,\n"
1645                                      "\n"
1646                                      "  b\n"
1647                                      "};"));
1648
1649  // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
1650  // line. However, the formatting looks a bit off and this probably doesn't
1651  // happen often in practice.
1652  verifyFormat("static int Variable[1] = {\n"
1653               "  { 1000000000000000000000000000000000000 }\n"
1654               "};",
1655               getLLVMStyleWithColumns(40));
1656}
1657
1658TEST_F(FormatTest, DesignatedInitializers) {
1659  verifyFormat("const struct A a = { .a = 1, .b = 2 };");
1660  verifyFormat("const struct A a = { .aaaaaaaaaa = 1,\n"
1661               "                     .bbbbbbbbbb = 2,\n"
1662               "                     .cccccccccc = 3,\n"
1663               "                     .dddddddddd = 4,\n"
1664               "                     .eeeeeeeeee = 5 };");
1665  verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
1666               "  .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
1667               "  .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
1668               "  .ccccccccccccccccccccccccccc = 3,\n"
1669               "  .ddddddddddddddddddddddddddd = 4,\n"
1670               "  .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5\n"
1671               "};");
1672
1673  verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
1674}
1675
1676TEST_F(FormatTest, NestedStaticInitializers) {
1677  verifyFormat("static A x = { { {} } };\n");
1678  verifyFormat("static A x = { { { init1, init2, init3, init4 },\n"
1679               "                 { init1, init2, init3, init4 } } };");
1680
1681  verifyFormat("somes Status::global_reps[3] = {\n"
1682               "  { kGlobalRef, OK_CODE, NULL, NULL, NULL },\n"
1683               "  { kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL },\n"
1684               "  { kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL }\n"
1685               "};");
1686  verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
1687                     "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
1688                     "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
1689                     "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
1690  verifyFormat(
1691      "CGRect cg_rect = { { rect.fLeft, rect.fTop },\n"
1692      "                   { rect.fRight - rect.fLeft, rect.fBottom - rect.fTop"
1693      " } };");
1694
1695  verifyFormat(
1696      "SomeArrayOfSomeType a = { { { 1, 2, 3 }, { 1, 2, 3 },\n"
1697      "                            { 111111111111111111111111111111,\n"
1698      "                              222222222222222222222222222222,\n"
1699      "                              333333333333333333333333333333 },\n"
1700      "                            { 1, 2, 3 }, { 1, 2, 3 } } };");
1701  verifyFormat(
1702      "SomeArrayOfSomeType a = { { { 1, 2, 3 } }, { { 1, 2, 3 } },\n"
1703      "                          { { 111111111111111111111111111111,\n"
1704      "                              222222222222222222222222222222,\n"
1705      "                              333333333333333333333333333333 } },\n"
1706      "                          { { 1, 2, 3 } }, { { 1, 2, 3 } } };");
1707  verifyGoogleFormat(
1708      "SomeArrayOfSomeType a = {\n"
1709      "    {{1, 2, 3}}, {{1, 2, 3}},\n"
1710      "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
1711      "      333333333333333333333333333333}},\n"
1712      "    {{1, 2, 3}}, {{1, 2, 3}}};");
1713
1714  // FIXME: We might at some point want to handle this similar to parameter
1715  // lists, where we have an option to put each on a single line.
1716  verifyFormat(
1717      "struct {\n"
1718      "  unsigned bit;\n"
1719      "  const char *const name;\n"
1720      "} kBitsToOs[] = { { kOsMac, \"Mac\" }, { kOsWin, \"Windows\" },\n"
1721      "                  { kOsLinux, \"Linux\" }, { kOsCrOS, \"Chrome OS\" } };");
1722}
1723
1724TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
1725  verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
1726               "                      \\\n"
1727               "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
1728}
1729
1730TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
1731  verifyFormat(
1732      "virtual void write(ELFWriter *writerrr,\n"
1733      "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
1734}
1735
1736TEST_F(FormatTest, LayoutUnknownPPDirective) {
1737  EXPECT_EQ("#123 \"A string literal\"",
1738            format("   #     123    \"A string literal\""));
1739  EXPECT_EQ("#;", format("#;"));
1740  verifyFormat("#\n;\n;\n;");
1741}
1742
1743TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
1744  EXPECT_EQ("#line 42 \"test\"\n",
1745            format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
1746  EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
1747                                    getLLVMStyleWithColumns(12)));
1748}
1749
1750TEST_F(FormatTest, EndOfFileEndsPPDirective) {
1751  EXPECT_EQ("#line 42 \"test\"",
1752            format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
1753  EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
1754}
1755
1756TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
1757  verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
1758  verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
1759  verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
1760  // FIXME: We never break before the macro name.
1761  verifyFormat("#define AA(\\\n    B)", getLLVMStyleWithColumns(12));
1762
1763  verifyFormat("#define A A\n#define A A");
1764  verifyFormat("#define A(X) A\n#define A A");
1765
1766  verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
1767  verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
1768}
1769
1770TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
1771  EXPECT_EQ("// somecomment\n"
1772            "#include \"a.h\"\n"
1773            "#define A(  \\\n"
1774            "    A, B)\n"
1775            "#include \"b.h\"\n"
1776            "// somecomment\n",
1777            format("  // somecomment\n"
1778                   "  #include \"a.h\"\n"
1779                   "#define A(A,\\\n"
1780                   "    B)\n"
1781                   "    #include \"b.h\"\n"
1782                   " // somecomment\n",
1783                   getLLVMStyleWithColumns(13)));
1784}
1785
1786TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
1787
1788TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
1789  EXPECT_EQ("#define A    \\\n"
1790            "  c;         \\\n"
1791            "  e;\n"
1792            "f;",
1793            format("#define A c; e;\n"
1794                   "f;",
1795                   getLLVMStyleWithColumns(14)));
1796}
1797
1798TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
1799
1800TEST_F(FormatTest, AlwaysFormatsEntireMacroDefinitions) {
1801  EXPECT_EQ("int  i;\n"
1802            "#define A \\\n"
1803            "  int i;  \\\n"
1804            "  int j\n"
1805            "int  k;",
1806            format("int  i;\n"
1807                   "#define A  \\\n"
1808                   " int   i    ;  \\\n"
1809                   " int   j\n"
1810                   "int  k;",
1811                   8, 0, getGoogleStyle())); // 8: position of "#define".
1812  EXPECT_EQ("int  i;\n"
1813            "#define A \\\n"
1814            "  int i;  \\\n"
1815            "  int j\n"
1816            "int  k;",
1817            format("int  i;\n"
1818                   "#define A  \\\n"
1819                   " int   i    ;  \\\n"
1820                   " int   j\n"
1821                   "int  k;",
1822                   45, 0, getGoogleStyle())); // 45: position of "j".
1823}
1824
1825TEST_F(FormatTest, MacroDefinitionInsideStatement) {
1826  EXPECT_EQ("int x,\n"
1827            "#define A\n"
1828            "    y;",
1829            format("int x,\n#define A\ny;"));
1830}
1831
1832TEST_F(FormatTest, HashInMacroDefinition) {
1833  verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
1834  verifyFormat("#define A \\\n"
1835               "  {       \\\n"
1836               "    f(#c);\\\n"
1837               "  }",
1838               getLLVMStyleWithColumns(11));
1839
1840  verifyFormat("#define A(X)         \\\n"
1841               "  void function##X()",
1842               getLLVMStyleWithColumns(22));
1843
1844  verifyFormat("#define A(a, b, c)   \\\n"
1845               "  void a##b##c()",
1846               getLLVMStyleWithColumns(22));
1847
1848  verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
1849}
1850
1851TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
1852  verifyFormat("#define A (1)");
1853}
1854
1855TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
1856  EXPECT_EQ("#define A b;", format("#define A \\\n"
1857                                   "          \\\n"
1858                                   "  b;",
1859                                   getLLVMStyleWithColumns(25)));
1860  EXPECT_EQ("#define A \\\n"
1861            "          \\\n"
1862            "  a;      \\\n"
1863            "  b;",
1864            format("#define A \\\n"
1865                   "          \\\n"
1866                   "  a;      \\\n"
1867                   "  b;",
1868                   getLLVMStyleWithColumns(11)));
1869  EXPECT_EQ("#define A \\\n"
1870            "  a;      \\\n"
1871            "          \\\n"
1872            "  b;",
1873            format("#define A \\\n"
1874                   "  a;      \\\n"
1875                   "          \\\n"
1876                   "  b;",
1877                   getLLVMStyleWithColumns(11)));
1878}
1879
1880TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
1881  verifyFormat("#define A :");
1882  verifyFormat("#define SOMECASES  \\\n"
1883               "  case 1:          \\\n"
1884               "  case 2\n",
1885               getLLVMStyleWithColumns(20));
1886  verifyFormat("#define A template <typename T>");
1887  verifyFormat("#define STR(x) #x\n"
1888               "f(STR(this_is_a_string_literal{));");
1889}
1890
1891TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
1892  verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
1893  EXPECT_EQ("class A : public QObject {\n"
1894            "  Q_OBJECT\n"
1895            "\n"
1896            "  A() {}\n"
1897            "};",
1898            format("class A  :  public QObject {\n"
1899                   "     Q_OBJECT\n"
1900                   "\n"
1901                   "  A() {\n}\n"
1902                   "}  ;"));
1903  EXPECT_EQ("SOME_MACRO\n"
1904            "namespace {\n"
1905            "void f();\n"
1906            "}",
1907            format("SOME_MACRO\n"
1908                   "  namespace    {\n"
1909                   "void   f(  );\n"
1910                   "}"));
1911  // Only if the identifier contains at least 5 characters.
1912  EXPECT_EQ("HTTP f();",
1913            format("HTTP\nf();"));
1914  EXPECT_EQ("MACRO\nf();",
1915            format("MACRO\nf();"));
1916  // Only if everything is upper case.
1917  EXPECT_EQ("class A : public QObject {\n"
1918            "  Q_Object A() {}\n"
1919            "};",
1920            format("class A  :  public QObject {\n"
1921                   "     Q_Object\n"
1922                   "\n"
1923                   "  A() {\n}\n"
1924                   "}  ;"));
1925}
1926
1927TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
1928  EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
1929            "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
1930            "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
1931            "class X {};\n"
1932            "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
1933            "int *createScopDetectionPass() { return 0; }",
1934            format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
1935                   "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
1936                   "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
1937                   "  class X {};\n"
1938                   "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
1939                   "  int *createScopDetectionPass() { return 0; }"));
1940  // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
1941  // braces, so that inner block is indented one level more.
1942  EXPECT_EQ("int q() {\n"
1943            "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
1944            "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
1945            "  IPC_END_MESSAGE_MAP()\n"
1946            "}",
1947            format("int q() {\n"
1948                   "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
1949                   "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
1950                   "  IPC_END_MESSAGE_MAP()\n"
1951                   "}"));
1952  EXPECT_EQ("int q() {\n"
1953            "  f(x);\n"
1954            "  f(x) {}\n"
1955            "  f(x)->g();\n"
1956            "  f(x)->*g();\n"
1957            "  f(x).g();\n"
1958            "  f(x) = x;\n"
1959            "  f(x) += x;\n"
1960            "  f(x) -= x;\n"
1961            "  f(x) *= x;\n"
1962            "  f(x) /= x;\n"
1963            "  f(x) %= x;\n"
1964            "  f(x) &= x;\n"
1965            "  f(x) |= x;\n"
1966            "  f(x) ^= x;\n"
1967            "  f(x) >>= x;\n"
1968            "  f(x) <<= x;\n"
1969            "  f(x)[y].z();\n"
1970            "  LOG(INFO) << x;\n"
1971            "  ifstream(x) >> x;\n"
1972            "}\n",
1973            format("int q() {\n"
1974                   "  f(x)\n;\n"
1975                   "  f(x)\n {}\n"
1976                   "  f(x)\n->g();\n"
1977                   "  f(x)\n->*g();\n"
1978                   "  f(x)\n.g();\n"
1979                   "  f(x)\n = x;\n"
1980                   "  f(x)\n += x;\n"
1981                   "  f(x)\n -= x;\n"
1982                   "  f(x)\n *= x;\n"
1983                   "  f(x)\n /= x;\n"
1984                   "  f(x)\n %= x;\n"
1985                   "  f(x)\n &= x;\n"
1986                   "  f(x)\n |= x;\n"
1987                   "  f(x)\n ^= x;\n"
1988                   "  f(x)\n >>= x;\n"
1989                   "  f(x)\n <<= x;\n"
1990                   "  f(x)\n[y].z();\n"
1991                   "  LOG(INFO)\n << x;\n"
1992                   "  ifstream(x)\n >> x;\n"
1993                   "}\n"));
1994  EXPECT_EQ("int q() {\n"
1995            "  f(x)\n"
1996            "  if (1) {\n"
1997            "  }\n"
1998            "  f(x)\n"
1999            "  while (1) {\n"
2000            "  }\n"
2001            "  f(x)\n"
2002            "  g(x);\n"
2003            "  f(x)\n"
2004            "  try {\n"
2005            "    q();\n"
2006            "  }\n"
2007            "  catch (...) {\n"
2008            "  }\n"
2009            "}\n",
2010            format("int q() {\n"
2011                   "f(x)\n"
2012                   "if (1) {}\n"
2013                   "f(x)\n"
2014                   "while (1) {}\n"
2015                   "f(x)\n"
2016                   "g(x);\n"
2017                   "f(x)\n"
2018                   "try { q(); } catch (...) {}\n"
2019                   "}\n"));
2020  EXPECT_EQ("class A {\n"
2021            "  A() : t(0) {}\n"
2022            "  A(X x)\n" // FIXME: function-level try blocks are broken.
2023            "  try : t(0) {\n"
2024            "  }\n"
2025            "  catch (...) {\n"
2026            "  }\n"
2027            "};",
2028            format("class A {\n"
2029                   "  A()\n : t(0) {}\n"
2030                   "  A(X x)\n"
2031                   "  try : t(0) {} catch (...) {}\n"
2032                   "};"));
2033}
2034
2035TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
2036  verifyFormat("#define A \\\n"
2037               "  f({     \\\n"
2038               "    g();  \\\n"
2039               "  });", getLLVMStyleWithColumns(11));
2040}
2041
2042TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
2043  EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
2044}
2045
2046TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
2047  verifyFormat("{\n  { a #c; }\n}");
2048}
2049
2050TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
2051  EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
2052            format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
2053  EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
2054            format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
2055}
2056
2057TEST_F(FormatTest, EscapedNewlineAtStartOfToken) {
2058  EXPECT_EQ(
2059      "#define A \\\n  int i;  \\\n  int j;",
2060      format("#define A \\\nint i;\\\n  int j;", getLLVMStyleWithColumns(11)));
2061  EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
2062}
2063
2064TEST_F(FormatTest, NoEscapedNewlineHandlingInBlockComments) {
2065  EXPECT_EQ("/* \\  \\  \\\n*/", format("\\\n/* \\  \\  \\\n*/"));
2066}
2067
2068TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
2069  verifyFormat("#define A \\\n"
2070               "  int v(  \\\n"
2071               "      a); \\\n"
2072               "  int i;",
2073               getLLVMStyleWithColumns(11));
2074}
2075
2076TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
2077  EXPECT_EQ(
2078      "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
2079      "                      \\\n"
2080      "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
2081      "\n"
2082      "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
2083      "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
2084      format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
2085             "\\\n"
2086             "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
2087             "  \n"
2088             "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
2089             "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
2090}
2091
2092TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
2093  EXPECT_EQ("int\n"
2094            "#define A\n"
2095            "    a;",
2096            format("int\n#define A\na;", getGoogleStyle()));
2097  verifyFormat("functionCallTo(\n"
2098               "    someOtherFunction(\n"
2099               "        withSomeParameters, whichInSequence,\n"
2100               "        areLongerThanALine(andAnotherCall,\n"
2101               "#define A B\n"
2102               "                           withMoreParamters,\n"
2103               "                           whichStronglyInfluenceTheLayout),\n"
2104               "        andMoreParameters),\n"
2105               "    trailing);",
2106               getLLVMStyleWithColumns(69));
2107}
2108
2109TEST_F(FormatTest, LayoutBlockInsideParens) {
2110  EXPECT_EQ("functionCall({\n"
2111            "  int i;\n"
2112            "});",
2113            format(" functionCall ( {int i;} );"));
2114
2115  // FIXME: This is bad, find a better and more generic solution.
2116  EXPECT_EQ("functionCall({\n"
2117            "  int i;\n"
2118            "},\n"
2119            "             aaaa, bbbb, cccc);",
2120            format(" functionCall ( {int i;},  aaaa,   bbbb, cccc);"));
2121  verifyFormat(
2122      "Aaa({\n"
2123      "  int i;\n"
2124      "},\n"
2125      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
2126      "                                     ccccccccccccccccc));");
2127}
2128
2129TEST_F(FormatTest, LayoutBlockInsideStatement) {
2130  EXPECT_EQ("SOME_MACRO { int i; }\n"
2131            "int i;",
2132            format("  SOME_MACRO  {int i;}  int i;"));
2133}
2134
2135TEST_F(FormatTest, LayoutNestedBlocks) {
2136  verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
2137               "  struct s {\n"
2138               "    int i;\n"
2139               "  };\n"
2140               "  s kBitsToOs[] = { { 10 } };\n"
2141               "  for (int i = 0; i < 10; ++i)\n"
2142               "    return;\n"
2143               "}");
2144}
2145
2146TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
2147  EXPECT_EQ("{}", format("{}"));
2148  verifyFormat("enum E {};");
2149  verifyFormat("enum E {}");
2150}
2151
2152//===----------------------------------------------------------------------===//
2153// Line break tests.
2154//===----------------------------------------------------------------------===//
2155
2156TEST_F(FormatTest, FormatsAwesomeMethodCall) {
2157  verifyFormat(
2158      "SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
2159      "                       parameter, parameter, parameter)),\n"
2160      "                   SecondLongCall(parameter));");
2161}
2162
2163TEST_F(FormatTest, PreventConfusingIndents) {
2164  verifyFormat(
2165      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2166      "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
2167      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2168      "    aaaaaaaaaaaaaaaaaaaaaaaa);");
2169  verifyFormat(
2170      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2171      "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
2172      "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
2173      "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
2174  verifyFormat(
2175      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
2176      "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
2177      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
2178      "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
2179  verifyFormat("int a = bbbb && ccc && fffff(\n"
2180               "#define A Just forcing a new line\n"
2181               "                           ddd);");
2182}
2183
2184TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
2185  verifyFormat(
2186      "bool aaaaaaa =\n"
2187      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
2188      "    bbbbbbbb();");
2189  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
2190               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
2191               "    ccccccccc == ddddddddddd;");
2192
2193  verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
2194               "                 aaaaaa) &&\n"
2195               "         bbbbbb && cccccc;");
2196  verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
2197               "                 aaaaaa) >>\n"
2198               "         bbbbbb;");
2199  verifyFormat("Whitespaces.addUntouchableComment(\n"
2200               "    SourceMgr.getSpellingColumnNumber(\n"
2201               "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
2202               "    1);");
2203
2204  verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2205               "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
2206               "    cccccc) {\n}");
2207
2208  // If the LHS of a comparison is not a binary expression itself, the
2209  // additional linebreak confuses many people.
2210  verifyFormat(
2211      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2212      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
2213      "}");
2214  verifyFormat(
2215      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2216      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
2217      "}");
2218  // Even explicit parentheses stress the precedence enough to make the
2219  // additional break unnecessary.
2220  verifyFormat(
2221      "if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2222      "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
2223      "}");
2224  // This cases is borderline, but with the indentation it is still readable.
2225  verifyFormat(
2226      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2227      "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2228      "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
2229      "}",
2230      getLLVMStyleWithColumns(75));
2231
2232  // If the LHS is a binary expression, we should still use the additional break
2233  // as otherwise the formatting hides the operator precedence.
2234  verifyFormat(
2235      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2236      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2237      "    5) {\n"
2238      "}");
2239
2240  FormatStyle OnePerLine = getLLVMStyle();
2241  OnePerLine.BinPackParameters = false;
2242  verifyFormat(
2243      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2244      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2245      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
2246      OnePerLine);
2247}
2248
2249TEST_F(FormatTest, ExpressionIndentation) {
2250  verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2251               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2252               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2253               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2254               "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
2255               "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
2256               "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2257               "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
2258               "                 ccccccccccccccccccccccccccccccccccccccccc;");
2259  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2260               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2261               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2262               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2263  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2264               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2265               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2266               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2267  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
2268               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
2269               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2270               "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
2271  verifyFormat("if () {\n"
2272               "} else if (aaaaa && bbbbb > // break\n"
2273               "                        ccccc) {\n"
2274               "}");
2275
2276  // Presence of a trailing comment used to change indentation of b.
2277  verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
2278               "       b;\n"
2279               "return aaaaaaaaaaaaaaaaaaa +\n"
2280               "       b; //",
2281               getLLVMStyleWithColumns(30));
2282}
2283
2284TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
2285  // Not sure what the best system is here. Like this, the LHS can be found
2286  // immediately above an operator (everything with the same or a higher
2287  // indent). The RHS is aligned right of the operator and so compasses
2288  // everything until something with the same indent as the operator is found.
2289  // FIXME: Is this a good system?
2290  FormatStyle Style = getLLVMStyle();
2291  Style.BreakBeforeBinaryOperators = true;
2292  verifyFormat(
2293      "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2294      "             + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2295      "             + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2296      "             == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2297      "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
2298      "                + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
2299      "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2300      "                * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2301      "                > ccccccccccccccccccccccccccccccccccccccccc;",
2302      Style);
2303  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2304               "    * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2305               "    + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2306               "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
2307               Style);
2308  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2309               "    + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2310               "      * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2311               "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
2312               Style);
2313  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2314               "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2315               "       * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2316               "       + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
2317               Style);
2318  verifyFormat("if () {\n"
2319               "} else if (aaaaa && bbbbb // break\n"
2320               "                    > ccccc) {\n"
2321               "}",
2322               Style);
2323}
2324
2325TEST_F(FormatTest, ConstructorInitializers) {
2326  verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
2327  verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
2328               getLLVMStyleWithColumns(45));
2329  verifyFormat("Constructor()\n"
2330               "    : Inttializer(FitsOnTheLine) {}",
2331               getLLVMStyleWithColumns(44));
2332  verifyFormat("Constructor()\n"
2333               "    : Inttializer(FitsOnTheLine) {}",
2334               getLLVMStyleWithColumns(43));
2335
2336  verifyFormat(
2337      "SomeClass::Constructor()\n"
2338      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
2339
2340  verifyFormat(
2341      "SomeClass::Constructor()\n"
2342      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2343      "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
2344  verifyFormat(
2345      "SomeClass::Constructor()\n"
2346      "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2347      "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
2348
2349  verifyFormat("Constructor()\n"
2350               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2351               "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2352               "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2353               "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
2354
2355  verifyFormat("Constructor()\n"
2356               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2357               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2358
2359  verifyFormat("Constructor(int Parameter = 0)\n"
2360               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
2361               "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
2362
2363  // Here a line could be saved by splitting the second initializer onto two
2364  // lines, but that is not desireable.
2365  verifyFormat("Constructor()\n"
2366               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
2367               "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
2368               "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2369
2370  FormatStyle OnePerLine = getLLVMStyle();
2371  OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
2372  verifyFormat("SomeClass::Constructor()\n"
2373               "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2374               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2375               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
2376               OnePerLine);
2377  verifyFormat("SomeClass::Constructor()\n"
2378               "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
2379               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
2380               "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
2381               OnePerLine);
2382  verifyFormat("MyClass::MyClass(int var)\n"
2383               "    : some_var_(var),            // 4 space indent\n"
2384               "      some_other_var_(var + 1) { // lined up\n"
2385               "}",
2386               OnePerLine);
2387  verifyFormat("Constructor()\n"
2388               "    : aaaaa(aaaaaa),\n"
2389               "      aaaaa(aaaaaa),\n"
2390               "      aaaaa(aaaaaa),\n"
2391               "      aaaaa(aaaaaa),\n"
2392               "      aaaaa(aaaaaa) {}",
2393               OnePerLine);
2394  verifyFormat("Constructor()\n"
2395               "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
2396               "            aaaaaaaaaaaaaaaaaaaaaa) {}",
2397               OnePerLine);
2398}
2399
2400TEST_F(FormatTest, MemoizationTests) {
2401  // This breaks if the memoization lookup does not take \c Indent and
2402  // \c LastSpace into account.
2403  verifyFormat(
2404      "extern CFRunLoopTimerRef\n"
2405      "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
2406      "                     CFTimeInterval interval, CFOptionFlags flags,\n"
2407      "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
2408      "                     CFRunLoopTimerContext *context) {}");
2409
2410  // Deep nesting somewhat works around our memoization.
2411  verifyFormat(
2412      "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2413      "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2414      "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2415      "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
2416      "                aaaaa())))))))))))))))))))))))))))))))))))))));",
2417      getLLVMStyleWithColumns(65));
2418  verifyFormat(
2419      "aaaaa(\n"
2420      "    aaaaa,\n"
2421      "    aaaaa(\n"
2422      "        aaaaa,\n"
2423      "        aaaaa(\n"
2424      "            aaaaa,\n"
2425      "            aaaaa(\n"
2426      "                aaaaa,\n"
2427      "                aaaaa(\n"
2428      "                    aaaaa,\n"
2429      "                    aaaaa(\n"
2430      "                        aaaaa,\n"
2431      "                        aaaaa(\n"
2432      "                            aaaaa,\n"
2433      "                            aaaaa(\n"
2434      "                                aaaaa,\n"
2435      "                                aaaaa(\n"
2436      "                                    aaaaa,\n"
2437      "                                    aaaaa(\n"
2438      "                                        aaaaa,\n"
2439      "                                        aaaaa(\n"
2440      "                                            aaaaa,\n"
2441      "                                            aaaaa(\n"
2442      "                                                aaaaa,\n"
2443      "                                                aaaaa))))))))))));",
2444      getLLVMStyleWithColumns(65));
2445  verifyFormat(
2446      "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"
2447      "                                  a),\n"
2448      "                                a),\n"
2449      "                              a),\n"
2450      "                            a),\n"
2451      "                          a),\n"
2452      "                        a),\n"
2453      "                      a),\n"
2454      "                    a),\n"
2455      "                  a),\n"
2456      "                a),\n"
2457      "              a),\n"
2458      "            a),\n"
2459      "          a),\n"
2460      "        a),\n"
2461      "      a),\n"
2462      "    a),\n"
2463      "  a)",
2464      getLLVMStyleWithColumns(65));
2465
2466  // This test takes VERY long when memoization is broken.
2467  FormatStyle OnePerLine = getLLVMStyle();
2468  OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
2469  OnePerLine.BinPackParameters = false;
2470  std::string input = "Constructor()\n"
2471                      "    : aaaa(a,\n";
2472  for (unsigned i = 0, e = 80; i != e; ++i) {
2473    input += "           a,\n";
2474  }
2475  input += "           a) {}";
2476  verifyFormat(input, OnePerLine);
2477}
2478
2479TEST_F(FormatTest, BreaksAsHighAsPossible) {
2480  verifyFormat(
2481      "void f() {\n"
2482      "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
2483      "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
2484      "    f();\n"
2485      "}");
2486  verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
2487               "    Intervals[i - 1].getRange().getLast()) {\n}");
2488}
2489
2490TEST_F(FormatTest, BreaksFunctionDeclarations) {
2491  // Principially, we break function declarations in a certain order:
2492  // 1) break amongst arguments.
2493  verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
2494               "                              Cccccccccccccc cccccccccccccc);");
2495
2496  // 2) break after return type.
2497  verifyFormat(
2498      "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2499      "    bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
2500      getGoogleStyle());
2501
2502  // 3) break after (.
2503  verifyFormat(
2504      "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
2505      "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
2506      getGoogleStyle());
2507
2508  // 4) break before after nested name specifiers.
2509  verifyFormat(
2510      "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2511      "    SomeClasssssssssssssssssssssssssssssssssssssss::\n"
2512      "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
2513      getGoogleStyle());
2514
2515  // However, there are exceptions, if a sufficient amount of lines can be
2516  // saved.
2517  // FIXME: The precise cut-offs wrt. the number of saved lines might need some
2518  // more adjusting.
2519  verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
2520               "                                  Cccccccccccccc cccccccccc,\n"
2521               "                                  Cccccccccccccc cccccccccc,\n"
2522               "                                  Cccccccccccccc cccccccccc,\n"
2523               "                                  Cccccccccccccc cccccccccc);");
2524  verifyFormat(
2525      "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2526      "    bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2527      "                Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2528      "                Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
2529      getGoogleStyle());
2530  verifyFormat(
2531      "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
2532      "                                          Cccccccccccccc cccccccccc,\n"
2533      "                                          Cccccccccccccc cccccccccc,\n"
2534      "                                          Cccccccccccccc cccccccccc,\n"
2535      "                                          Cccccccccccccc cccccccccc,\n"
2536      "                                          Cccccccccccccc cccccccccc,\n"
2537      "                                          Cccccccccccccc cccccccccc);");
2538  verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
2539               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2540               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2541               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
2542               "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
2543
2544  // Break after multi-line parameters.
2545  verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2546               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2547               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2548               "    bbbb bbbb);");
2549
2550  // Treat overloaded operators like other functions.
2551  verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
2552               "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
2553  verifyGoogleFormat(
2554      "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
2555      "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
2556}
2557
2558TEST_F(FormatTest, TrailingReturnType) {
2559  verifyFormat("auto foo() -> int;\n");
2560  verifyFormat("struct S {\n"
2561               "  auto bar() const -> int;\n"
2562               "};");
2563  verifyFormat("template <size_t Order, typename T>\n"
2564               "auto load_img(const std::string &filename)\n"
2565               "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
2566
2567  // Not trailing return types.
2568  verifyFormat("void f() { auto a = b->c(); }");
2569}
2570
2571TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
2572  // Avoid breaking before trailing 'const'.
2573  verifyFormat("void someLongFunction(\n"
2574               "    int someLongParameter) const {}",
2575               getLLVMStyleWithColumns(46));
2576  FormatStyle Style = getGoogleStyle();
2577  Style.ColumnLimit = 47;
2578  verifyFormat("void\n"
2579               "someLongFunction(int someLongParameter) const {\n}",
2580               getLLVMStyleWithColumns(47));
2581  verifyFormat("void someLongFunction(\n"
2582               "    int someLongParameter) const {}",
2583               Style);
2584  verifyFormat("LoooooongReturnType\n"
2585               "someLoooooooongFunction() const {}",
2586               getLLVMStyleWithColumns(47));
2587  verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
2588               "    const {}",
2589               Style);
2590
2591  // Avoid breaking before other trailing annotations, if they are not
2592  // function-like.
2593  verifyFormat("void SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2594               "                  aaaaaaaaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
2595
2596  // Breaking before function-like trailing annotations is fine to keep them
2597  // close to their arguments.
2598  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2599               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
2600  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
2601               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
2602  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
2603               "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
2604
2605  verifyFormat(
2606      "void aaaaaaaaaaaaaaaaaa()\n"
2607      "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
2608      "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
2609  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2610               "    __attribute__((unused));");
2611  verifyFormat(
2612      "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2613      "    GUARDED_BY(aaaaaaaaaaaa);",
2614      getGoogleStyle());
2615  verifyFormat(
2616      "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2617      "    GUARDED_BY(aaaaaaaaaaaa);",
2618      getGoogleStyle());
2619}
2620
2621TEST_F(FormatTest, BreaksDesireably) {
2622  verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
2623               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
2624               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
2625  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2626               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
2627               "}");
2628
2629  verifyFormat(
2630      "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2631      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
2632
2633  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2634               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2635               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2636
2637  verifyFormat(
2638      "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2639      "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
2640      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2641      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
2642
2643  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2644               "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2645
2646  verifyFormat(
2647      "void f() {\n"
2648      "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
2649      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2650      "}");
2651  verifyFormat(
2652      "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2653      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2654  verifyFormat(
2655      "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2656      "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
2657  verifyFormat(
2658      "aaaaaaaaaaaaaaaaa(\n"
2659      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2660      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2661
2662  // This test case breaks on an incorrect memoization, i.e. an optimization not
2663  // taking into account the StopAt value.
2664  verifyFormat(
2665      "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2666      "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2667      "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
2668      "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2669
2670  verifyFormat("{\n  {\n    {\n"
2671               "      Annotation.SpaceRequiredBefore =\n"
2672               "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
2673               "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
2674               "    }\n  }\n}");
2675
2676  // Break on an outer level if there was a break on an inner level.
2677  EXPECT_EQ("f(g(h(a, // comment\n"
2678            "      b, c),\n"
2679            "    d, e),\n"
2680            "  x, y);",
2681            format("f(g(h(a, // comment\n"
2682                   "    b, c), d, e), x, y);"));
2683
2684  // Prefer breaking similar line breaks.
2685  verifyFormat(
2686      "const int kTrackingOptions = NSTrackingMouseMoved |\n"
2687      "                             NSTrackingMouseEnteredAndExited |\n"
2688      "                             NSTrackingActiveAlways;");
2689}
2690
2691TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
2692  FormatStyle NoBinPacking = getGoogleStyle();
2693  NoBinPacking.BinPackParameters = false;
2694  verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
2695               "  aaaaaaaaaaaaaaaaaaaa,\n"
2696               "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
2697               NoBinPacking);
2698  verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
2699               "        aaaaaaaaaaaaa,\n"
2700               "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
2701               NoBinPacking);
2702  verifyFormat(
2703      "aaaaaaaa(aaaaaaaaaaaaa,\n"
2704      "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2705      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
2706      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2707      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
2708      NoBinPacking);
2709  verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
2710               "    .aaaaaaaaaaaaaaaaaa();",
2711               NoBinPacking);
2712  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2713               "    aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);",
2714               NoBinPacking);
2715
2716  verifyFormat(
2717      "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2718      "             aaaaaaaaaaaa,\n"
2719      "             aaaaaaaaaaaa);",
2720      NoBinPacking);
2721  verifyFormat(
2722      "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
2723      "                               ddddddddddddddddddddddddddddd),\n"
2724      "             test);",
2725      NoBinPacking);
2726
2727  verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
2728               "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
2729               "            aaaaaaaaaaaaaaaaaaaaaaa> aaaaaaaaaaaaaaaaaa;",
2730               NoBinPacking);
2731  verifyFormat("a(\"a\"\n"
2732               "  \"a\",\n"
2733               "  a);");
2734
2735  NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
2736  verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
2737               "                aaaaaaaaa,\n"
2738               "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
2739               NoBinPacking);
2740  verifyFormat(
2741      "void f() {\n"
2742      "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
2743      "      .aaaaaaa();\n"
2744      "}",
2745      NoBinPacking);
2746  verifyFormat(
2747      "template <class SomeType, class SomeOtherType>\n"
2748      "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
2749      NoBinPacking);
2750}
2751
2752TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
2753  FormatStyle Style = getLLVMStyleWithColumns(15);
2754  Style.ExperimentalAutoDetectBinPacking = true;
2755  EXPECT_EQ("aaa(aaaa,\n"
2756            "    aaaa,\n"
2757            "    aaaa);\n"
2758            "aaa(aaaa,\n"
2759            "    aaaa,\n"
2760            "    aaaa);",
2761            format("aaa(aaaa,\n" // one-per-line
2762                   "  aaaa,\n"
2763                   "    aaaa  );\n"
2764                   "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
2765                   Style));
2766  EXPECT_EQ("aaa(aaaa, aaaa,\n"
2767            "    aaaa);\n"
2768            "aaa(aaaa, aaaa,\n"
2769            "    aaaa);",
2770            format("aaa(aaaa,  aaaa,\n" // bin-packed
2771                   "    aaaa  );\n"
2772                   "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
2773                   Style));
2774}
2775
2776TEST_F(FormatTest, FormatsBuilderPattern) {
2777  verifyFormat(
2778      "return llvm::StringSwitch<Reference::Kind>(name)\n"
2779      "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
2780      "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME).StartsWith(\".init\", ORDER_INIT)\n"
2781      "    .StartsWith(\".fini\", ORDER_FINI).StartsWith(\".hash\", ORDER_HASH)\n"
2782      "    .Default(ORDER_TEXT);\n");
2783
2784  verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
2785               "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
2786  verifyFormat(
2787      "aaaaaaa->aaaaaaa\n"
2788      "    ->aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2789      "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
2790  verifyFormat(
2791      "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
2792      "    aaaaaaaaaaaaaa);");
2793  verifyFormat(
2794      "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa = aaaaaa->aaaaaaaaaaaa()\n"
2795      "    ->aaaaaaaaaaaaaaaa(\n"
2796      "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2797      "    ->aaaaaaaaaaaaaaaaa();");
2798}
2799
2800TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
2801  verifyFormat(
2802      "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2803      "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
2804  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
2805               "    ccccccccccccccccccccccccc) {\n}");
2806  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
2807               "    ccccccccccccccccccccccccc) {\n}");
2808  verifyFormat(
2809      "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
2810      "    ccccccccccccccccccccccccc) {\n}");
2811  verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
2812               "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
2813               "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
2814               "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
2815  verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
2816               "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
2817               "    aaaaaaaaaaaaaaa != aa) {\n}");
2818}
2819
2820TEST_F(FormatTest, BreaksAfterAssignments) {
2821  verifyFormat(
2822      "unsigned Cost =\n"
2823      "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
2824      "                        SI->getPointerAddressSpaceee());\n");
2825  verifyFormat(
2826      "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
2827      "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
2828
2829  verifyFormat(
2830      "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa()\n"
2831      "    .aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
2832  verifyFormat("unsigned OriginalStartColumn =\n"
2833               "    SourceMgr.getSpellingColumnNumber(\n"
2834               "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
2835               "    1;");
2836}
2837
2838TEST_F(FormatTest, AlignsAfterAssignments) {
2839  verifyFormat(
2840      "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2841      "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
2842  verifyFormat(
2843      "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2844      "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
2845  verifyFormat(
2846      "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2847      "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
2848  verifyFormat(
2849      "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2850      "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
2851  verifyFormat(
2852      "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
2853      "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
2854      "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
2855}
2856
2857TEST_F(FormatTest, AlignsAfterReturn) {
2858  verifyFormat(
2859      "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2860      "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
2861  verifyFormat(
2862      "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
2863      "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
2864  verifyFormat(
2865      "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
2866      "       aaaaaaaaaaaaaaaaaaaaaa();");
2867  verifyFormat(
2868      "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
2869      "        aaaaaaaaaaaaaaaaaaaaaa());");
2870  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2871               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2872  verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2873               "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
2874               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2875}
2876
2877TEST_F(FormatTest, BreaksConditionalExpressions) {
2878  verifyFormat(
2879      "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2880      "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2881      "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2882  verifyFormat(
2883      "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2884      "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2885  verifyFormat(
2886      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
2887      "                                                    : aaaaaaaaaaaaa);");
2888  verifyFormat(
2889      "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2890      "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2891      "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2892      "                   aaaaaaaaaaaaa);");
2893  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2894               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2895               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2896               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2897               "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2898  verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2899               "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2900               "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2901               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
2902               "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2903               "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
2904               "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
2905
2906  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2907               "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2908               "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
2909  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
2910               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2911               "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2912               "        : aaaaaaaaaaaaaaaa;");
2913  verifyFormat(
2914      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2915      "    ? aaaaaaaaaaaaaaa\n"
2916      "    : aaaaaaaaaaaaaaa;");
2917  verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
2918               "          aaaaaaaaa\n"
2919               "      ? b\n"
2920               "      : c);");
2921  verifyFormat(
2922      "unsigned Indent =\n"
2923      "    format(TheLine.First, IndentForLevel[TheLine.Level] >= 0\n"
2924      "                              ? IndentForLevel[TheLine.Level]\n"
2925      "                              : TheLine * 2,\n"
2926      "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
2927      getLLVMStyleWithColumns(70));
2928  verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
2929               "                  ? aaaaaaaaaaaaaaa\n"
2930               "                  : bbbbbbbbbbbbbbb //\n"
2931               "                        ? ccccccccccccccc\n"
2932               "                        : ddddddddddddddd;");
2933  verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
2934               "                  ? aaaaaaaaaaaaaaa\n"
2935               "                  : (bbbbbbbbbbbbbbb //\n"
2936               "                         ? ccccccccccccccc\n"
2937               "                         : ddddddddddddddd);");
2938
2939  FormatStyle NoBinPacking = getLLVMStyle();
2940  NoBinPacking.BinPackParameters = false;
2941  verifyFormat(
2942      "void f() {\n"
2943      "  g(aaa,\n"
2944      "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
2945      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
2946      "        ? aaaaaaaaaaaaaaa\n"
2947      "        : aaaaaaaaaaaaaaa);\n"
2948      "}",
2949      NoBinPacking);
2950}
2951
2952TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
2953  verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
2954               "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
2955  verifyFormat("bool a = true, b = false;");
2956
2957  verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
2958               "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
2959               "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
2960               "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
2961  verifyFormat(
2962      "bool aaaaaaaaaaaaaaaaaaaaa =\n"
2963      "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
2964      "     d = e && f;");
2965  verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
2966               "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
2967  verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
2968               "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
2969  verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
2970               "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
2971  // FIXME: If multiple variables are defined, the "*" needs to move to the new
2972  // line. Also fix indent for breaking after the type, this looks bad.
2973  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
2974               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
2975               "    *b = bbbbbbbbbbbbbbbbbbb;",
2976               getGoogleStyle());
2977
2978  // Not ideal, but pointer-with-type does not allow much here.
2979  verifyGoogleFormat(
2980      "aaaaaaaaa* a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
2981      "           *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;");
2982}
2983
2984TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
2985  verifyFormat("arr[foo ? bar : baz];");
2986  verifyFormat("f()[foo ? bar : baz];");
2987  verifyFormat("(a + b)[foo ? bar : baz];");
2988  verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
2989}
2990
2991TEST_F(FormatTest, AlignsStringLiterals) {
2992  verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
2993               "                                      \"short literal\");");
2994  verifyFormat(
2995      "looooooooooooooooooooooooongFunction(\n"
2996      "    \"short literal\"\n"
2997      "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
2998  verifyFormat("someFunction(\"Always break between multi-line\"\n"
2999               "             \" string literals\",\n"
3000               "             and, other, parameters);");
3001  EXPECT_EQ("fun + \"1243\" /* comment */\n"
3002            "      \"5678\";",
3003            format("fun + \"1243\" /* comment */\n"
3004                   "      \"5678\";",
3005                   getLLVMStyleWithColumns(28)));
3006  EXPECT_EQ(
3007      "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
3008      "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
3009      "         \"aaaaaaaaaaaaaaaa\";",
3010      format("aaaaaa ="
3011             "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
3012             "aaaaaaaaaaaaaaaaaaaaa\" "
3013             "\"aaaaaaaaaaaaaaaa\";"));
3014  verifyFormat("a = a + \"a\"\n"
3015               "        \"a\"\n"
3016               "        \"a\";");
3017  verifyFormat("f(\"a\", \"b\"\n"
3018               "       \"c\");");
3019
3020  verifyFormat(
3021      "#define LL_FORMAT \"ll\"\n"
3022      "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
3023      "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
3024
3025  verifyFormat("#define A(X)          \\\n"
3026               "  \"aaaaa\" #X \"bbbbbb\" \\\n"
3027               "  \"ccccc\"",
3028               getLLVMStyleWithColumns(23));
3029  verifyFormat("#define A \"def\"\n"
3030               "f(\"abc\" A \"ghi\"\n"
3031               "  \"jkl\");");
3032}
3033
3034TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
3035  FormatStyle NoBreak = getLLVMStyle();
3036  NoBreak.AlwaysBreakBeforeMultilineStrings = false;
3037  FormatStyle Break = getLLVMStyle();
3038  Break.AlwaysBreakBeforeMultilineStrings = true;
3039  verifyFormat("aaaa = \"bbbb\"\n"
3040               "       \"cccc\";",
3041               NoBreak);
3042  verifyFormat("aaaa =\n"
3043               "    \"bbbb\"\n"
3044               "    \"cccc\";",
3045               Break);
3046  verifyFormat("aaaa(\"bbbb\"\n"
3047               "     \"cccc\");",
3048               NoBreak);
3049  verifyFormat("aaaa(\n"
3050               "    \"bbbb\"\n"
3051               "    \"cccc\");",
3052               Break);
3053  verifyFormat("aaaa(qqq, \"bbbb\"\n"
3054               "          \"cccc\");",
3055               NoBreak);
3056  verifyFormat("aaaa(qqq,\n"
3057               "     \"bbbb\"\n"
3058               "     \"cccc\");",
3059               Break);
3060
3061  // Don't break if there is no column gain.
3062  verifyFormat("f(\"aaaa\"\n"
3063               "  \"bbbb\");",
3064               Break);
3065
3066  // Treat literals with escaped newlines like multi-line string literals.
3067  EXPECT_EQ("x = \"a\\\n"
3068            "b\\\n"
3069            "c\";",
3070            format("x = \"a\\\n"
3071                   "b\\\n"
3072                   "c\";",
3073                   NoBreak));
3074  EXPECT_EQ("x =\n"
3075            "    \"a\\\n"
3076            "b\\\n"
3077            "c\";",
3078            format("x = \"a\\\n"
3079                   "b\\\n"
3080                   "c\";",
3081                   Break));
3082}
3083
3084TEST_F(FormatTest, AlignsPipes) {
3085  verifyFormat(
3086      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3087      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3088      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3089  verifyFormat(
3090      "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
3091      "                     << aaaaaaaaaaaaaaaaaaaa;");
3092  verifyFormat(
3093      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3094      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3095  verifyFormat(
3096      "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
3097      "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
3098      "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
3099  verifyFormat(
3100      "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3101      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3102      "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3103
3104  verifyFormat("return out << \"somepacket = {\\n\"\n"
3105               "           << \"  aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
3106               "           << \"  bbbb = \" << pkt.bbbb << \"\\n\"\n"
3107               "           << \"  cccccc = \" << pkt.cccccc << \"\\n\"\n"
3108               "           << \"  ddd = [\" << pkt.ddd << \"]\\n\"\n"
3109               "           << \"}\";");
3110
3111  verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
3112               "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
3113               "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
3114  verifyFormat(
3115      "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
3116      "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
3117      "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
3118      "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
3119      "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
3120  verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
3121               "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
3122  verifyFormat(
3123      "void f() {\n"
3124      "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
3125      "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
3126      "}");
3127
3128  // Breaking before the first "<<" is generally not desirable.
3129  verifyFormat(
3130      "llvm::errs()\n"
3131      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3132      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3133      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3134      "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
3135      getLLVMStyleWithColumns(70));
3136  verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
3137               "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3138               "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
3139               "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3140               "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
3141               "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
3142               getLLVMStyleWithColumns(70));
3143
3144  // But sometimes, breaking before the first "<<" is necessary.
3145  verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
3146               "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3147               "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3148
3149  verifyFormat(
3150      "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3151      "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3152}
3153
3154TEST_F(FormatTest, UnderstandsEquals) {
3155  verifyFormat(
3156      "aaaaaaaaaaaaaaaaa =\n"
3157      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
3158  verifyFormat(
3159      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3160      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
3161  verifyFormat(
3162      "if (a) {\n"
3163      "  f();\n"
3164      "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3165      "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
3166      "}");
3167
3168  verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3169               "        100000000 + 10000000) {\n}");
3170}
3171
3172TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
3173  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
3174               "    .looooooooooooooooooooooooooooooooooooooongFunction();");
3175
3176  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
3177               "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
3178
3179  verifyFormat(
3180      "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
3181      "                                                          Parameter2);");
3182
3183  verifyFormat(
3184      "ShortObject->shortFunction(\n"
3185      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
3186      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
3187
3188  verifyFormat("loooooooooooooongFunction(\n"
3189               "    LoooooooooooooongObject->looooooooooooooooongFunction());");
3190
3191  verifyFormat(
3192      "function(LoooooooooooooooooooooooooooooooooooongObject\n"
3193      "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
3194
3195  verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
3196               "    .WillRepeatedly(Return(SomeValue));");
3197  verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)]\n"
3198               "    .insert(ccccccccccccccccccccccc);");
3199  verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3200               "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).aaaaa(aaaaa),\n"
3201               "      aaaaaaaaaaaaaaaaaaaaa);");
3202  verifyFormat(
3203      "aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3204      "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
3205      "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3206      "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3207      "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
3208  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3209               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3210               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3211               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
3212               "}");
3213
3214  // Here, it is not necessary to wrap at "." or "->".
3215  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
3216               "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
3217  verifyFormat(
3218      "aaaaaaaaaaa->aaaaaaaaa(\n"
3219      "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3220      "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
3221
3222  verifyFormat(
3223      "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3224      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
3225  verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
3226               "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
3227  verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
3228               "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
3229
3230  // FIXME: Should we break before .a()?
3231  verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3232               "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa).a();");
3233
3234  FormatStyle NoBinPacking = getLLVMStyle();
3235  NoBinPacking.BinPackParameters = false;
3236  verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
3237               "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
3238               "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
3239               "                         aaaaaaaaaaaaaaaaaaa,\n"
3240               "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
3241               NoBinPacking);
3242
3243  // If there is a subsequent call, change to hanging indentation.
3244  verifyFormat(
3245      "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3246      "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
3247      "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3248  verifyFormat(
3249      "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3250      "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
3251}
3252
3253TEST_F(FormatTest, WrapsTemplateDeclarations) {
3254  verifyFormat("template <typename T>\n"
3255               "virtual void loooooooooooongFunction(int Param1, int Param2);");
3256  verifyFormat(
3257      "template <typename T>\n"
3258      "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
3259  verifyFormat("template <typename T>\n"
3260               "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
3261               "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
3262  verifyFormat(
3263      "template <typename T>\n"
3264      "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
3265      "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
3266  verifyFormat(
3267      "template <typename T>\n"
3268      "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
3269      "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
3270      "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3271  verifyFormat("template <typename T>\n"
3272               "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3273               "    int aaaaaaaaaaaaaaaaaaaaaa);");
3274  verifyFormat(
3275      "template <typename T1, typename T2 = char, typename T3 = char,\n"
3276      "          typename T4 = char>\n"
3277      "void f();");
3278  verifyFormat(
3279      "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
3280      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3281
3282  verifyFormat("a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
3283               "    a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));");
3284
3285  verifyFormat("template <typename T> class C {};");
3286  verifyFormat("template <typename T> void f();");
3287  verifyFormat("template <typename T> void f() {}");
3288
3289  FormatStyle AlwaysBreak = getLLVMStyle();
3290  AlwaysBreak.AlwaysBreakTemplateDeclarations = true;
3291  verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
3292  verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
3293  verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
3294  verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3295               "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
3296               "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
3297  verifyFormat(
3298      "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
3299      "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3300      "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
3301      "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
3302      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3303      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
3304      "        bbbbbbbbbbbbbbbbbbbbbbbb);",
3305      getLLVMStyleWithColumns(72));
3306}
3307
3308TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
3309  verifyFormat(
3310      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3311      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3312  verifyFormat(
3313      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3314      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3315      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
3316
3317  // FIXME: Should we have the extra indent after the second break?
3318  verifyFormat(
3319      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3320      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3321      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3322
3323  verifyFormat(
3324      "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
3325      "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
3326
3327  // Breaking at nested name specifiers is generally not desirable.
3328  verifyFormat(
3329      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3330      "    aaaaaaaaaaaaaaaaaaaaaaa);");
3331
3332  verifyFormat(
3333      "aaaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3334      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3335      "                   aaaaaaaaaaaaaaaaaaaaa);",
3336      getLLVMStyleWithColumns(74));
3337
3338  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
3339               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3340               "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
3341}
3342
3343TEST_F(FormatTest, UnderstandsTemplateParameters) {
3344  verifyFormat("A<int> a;");
3345  verifyFormat("A<A<A<int> > > a;");
3346  verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
3347  verifyFormat("bool x = a < 1 || 2 > a;");
3348  verifyFormat("bool x = 5 < f<int>();");
3349  verifyFormat("bool x = f<int>() > 5;");
3350  verifyFormat("bool x = 5 < a<int>::x;");
3351  verifyFormat("bool x = a < 4 ? a > 2 : false;");
3352  verifyFormat("bool x = f() ? a < 2 : a > 2;");
3353
3354  verifyGoogleFormat("A<A<int>> a;");
3355  verifyGoogleFormat("A<A<A<int>>> a;");
3356  verifyGoogleFormat("A<A<A<A<int>>>> a;");
3357  verifyGoogleFormat("A<A<int> > a;");
3358  verifyGoogleFormat("A<A<A<int> > > a;");
3359  verifyGoogleFormat("A<A<A<A<int> > > > a;");
3360  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
3361  EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
3362
3363  verifyFormat("test >> a >> b;");
3364  verifyFormat("test << a >> b;");
3365
3366  verifyFormat("f<int>();");
3367  verifyFormat("template <typename T> void f() {}");
3368
3369  // Not template parameters.
3370  verifyFormat("return a < b && c > d;");
3371  verifyFormat("void f() {\n"
3372               "  while (a < b && c > d) {\n"
3373               "  }\n"
3374               "}");
3375}
3376
3377TEST_F(FormatTest, UnderstandsBinaryOperators) {
3378  verifyFormat("COMPARE(a, ==, b);");
3379}
3380
3381TEST_F(FormatTest, UnderstandsPointersToMembers) {
3382  verifyFormat("int A::*x;");
3383  verifyFormat("int (S::*func)(void *);");
3384  verifyFormat("void f() { int (S::*func)(void *); }");
3385  verifyFormat("typedef bool *(Class::*Member)() const;");
3386  verifyFormat("void f() {\n"
3387               "  (a->*f)();\n"
3388               "  a->*x;\n"
3389               "  (a.*f)();\n"
3390               "  ((*a).*f)();\n"
3391               "  a.*x;\n"
3392               "}");
3393  verifyFormat("void f() {\n"
3394               "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
3395               "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
3396               "}");
3397  FormatStyle Style = getLLVMStyle();
3398  Style.PointerBindsToType = true;
3399  verifyFormat("typedef bool* (Class::*Member)() const;", Style);
3400}
3401
3402TEST_F(FormatTest, UnderstandsUnaryOperators) {
3403  verifyFormat("int a = -2;");
3404  verifyFormat("f(-1, -2, -3);");
3405  verifyFormat("a[-1] = 5;");
3406  verifyFormat("int a = 5 + -2;");
3407  verifyFormat("if (i == -1) {\n}");
3408  verifyFormat("if (i != -1) {\n}");
3409  verifyFormat("if (i > -1) {\n}");
3410  verifyFormat("if (i < -1) {\n}");
3411  verifyFormat("++(a->f());");
3412  verifyFormat("--(a->f());");
3413  verifyFormat("(a->f())++;");
3414  verifyFormat("a[42]++;");
3415  verifyFormat("if (!(a->f())) {\n}");
3416
3417  verifyFormat("a-- > b;");
3418  verifyFormat("b ? -a : c;");
3419  verifyFormat("n * sizeof char16;");
3420  verifyFormat("n * alignof char16;", getGoogleStyle());
3421  verifyFormat("sizeof(char);");
3422  verifyFormat("alignof(char);", getGoogleStyle());
3423
3424  verifyFormat("return -1;");
3425  verifyFormat("switch (a) {\n"
3426               "case -1:\n"
3427               "  break;\n"
3428               "}");
3429  verifyFormat("#define X -1");
3430  verifyFormat("#define X -kConstant");
3431
3432  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { -5, +3 };");
3433  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { +5, -3 };");
3434
3435  verifyFormat("int a = /* confusing comment */ -1;");
3436  // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
3437  verifyFormat("int a = i /* confusing comment */++;");
3438}
3439
3440TEST_F(FormatTest, UndestandsOverloadedOperators) {
3441  verifyFormat("bool operator<();");
3442  verifyFormat("bool operator>();");
3443  verifyFormat("bool operator=();");
3444  verifyFormat("bool operator==();");
3445  verifyFormat("bool operator!=();");
3446  verifyFormat("int operator+();");
3447  verifyFormat("int operator++();");
3448  verifyFormat("bool operator();");
3449  verifyFormat("bool operator()();");
3450  verifyFormat("bool operator[]();");
3451  verifyFormat("operator bool();");
3452  verifyFormat("operator int();");
3453  verifyFormat("operator void *();");
3454  verifyFormat("operator SomeType<int>();");
3455  verifyFormat("operator SomeType<int, int>();");
3456  verifyFormat("operator SomeType<SomeType<int> >();");
3457  verifyFormat("void *operator new(std::size_t size);");
3458  verifyFormat("void *operator new[](std::size_t size);");
3459  verifyFormat("void operator delete(void *ptr);");
3460  verifyFormat("void operator delete[](void *ptr);");
3461  verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
3462               "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
3463
3464  verifyFormat(
3465      "ostream &operator<<(ostream &OutputStream,\n"
3466      "                    SomeReallyLongType WithSomeReallyLongValue);");
3467  verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
3468               "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
3469               "  return left.group < right.group;\n"
3470               "}");
3471  verifyFormat("SomeType &operator=(const SomeType &S);");
3472
3473  verifyGoogleFormat("operator void*();");
3474  verifyGoogleFormat("operator SomeType<SomeType<int>>();");
3475}
3476
3477TEST_F(FormatTest, UnderstandsNewAndDelete) {
3478  verifyFormat("void f() {\n"
3479               "  A *a = new A;\n"
3480               "  A *a = new (placement) A;\n"
3481               "  delete a;\n"
3482               "  delete (A *)a;\n"
3483               "}");
3484}
3485
3486TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
3487  verifyFormat("int *f(int *a) {}");
3488  verifyFormat("int main(int argc, char **argv) {}");
3489  verifyFormat("Test::Test(int b) : a(b * b) {}");
3490  verifyIndependentOfContext("f(a, *a);");
3491  verifyFormat("void g() { f(*a); }");
3492  verifyIndependentOfContext("int a = b * 10;");
3493  verifyIndependentOfContext("int a = 10 * b;");
3494  verifyIndependentOfContext("int a = b * c;");
3495  verifyIndependentOfContext("int a += b * c;");
3496  verifyIndependentOfContext("int a -= b * c;");
3497  verifyIndependentOfContext("int a *= b * c;");
3498  verifyIndependentOfContext("int a /= b * c;");
3499  verifyIndependentOfContext("int a = *b;");
3500  verifyIndependentOfContext("int a = *b * c;");
3501  verifyIndependentOfContext("int a = b * *c;");
3502  verifyIndependentOfContext("return 10 * b;");
3503  verifyIndependentOfContext("return *b * *c;");
3504  verifyIndependentOfContext("return a & ~b;");
3505  verifyIndependentOfContext("f(b ? *c : *d);");
3506  verifyIndependentOfContext("int a = b ? *c : *d;");
3507  verifyIndependentOfContext("*b = a;");
3508  verifyIndependentOfContext("a * ~b;");
3509  verifyIndependentOfContext("a * !b;");
3510  verifyIndependentOfContext("a * +b;");
3511  verifyIndependentOfContext("a * -b;");
3512  verifyIndependentOfContext("a * ++b;");
3513  verifyIndependentOfContext("a * --b;");
3514  verifyIndependentOfContext("a[4] * b;");
3515  verifyIndependentOfContext("a[a * a] = 1;");
3516  verifyIndependentOfContext("f() * b;");
3517  verifyIndependentOfContext("a * [self dostuff];");
3518  verifyIndependentOfContext("int x = a * (a + b);");
3519  verifyIndependentOfContext("(a *)(a + b);");
3520  verifyIndependentOfContext("int *pa = (int *)&a;");
3521  verifyIndependentOfContext("return sizeof(int **);");
3522  verifyIndependentOfContext("return sizeof(int ******);");
3523  verifyIndependentOfContext("return (int **&)a;");
3524  verifyIndependentOfContext("f((*PointerToArray)[10]);");
3525  verifyFormat("void f(Type (*parameter)[10]) {}");
3526  verifyGoogleFormat("return sizeof(int**);");
3527  verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
3528  verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
3529  verifyFormat("auto a = [](int **&, int ***) {};");
3530
3531  verifyIndependentOfContext("InvalidRegions[*R] = 0;");
3532
3533  verifyIndependentOfContext("A<int *> a;");
3534  verifyIndependentOfContext("A<int **> a;");
3535  verifyIndependentOfContext("A<int *, int *> a;");
3536  verifyIndependentOfContext(
3537      "const char *const p = reinterpret_cast<const char *const>(q);");
3538  verifyIndependentOfContext("A<int **, int **> a;");
3539  verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
3540  verifyFormat("for (char **a = b; *a; ++a) {\n}");
3541  verifyFormat("for (; a && b;) {\n}");
3542
3543  verifyFormat(
3544      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
3545      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
3546
3547  verifyGoogleFormat("int main(int argc, char** argv) {}");
3548  verifyGoogleFormat("A<int*> a;");
3549  verifyGoogleFormat("A<int**> a;");
3550  verifyGoogleFormat("A<int*, int*> a;");
3551  verifyGoogleFormat("A<int**, int**> a;");
3552  verifyGoogleFormat("f(b ? *c : *d);");
3553  verifyGoogleFormat("int a = b ? *c : *d;");
3554  verifyGoogleFormat("Type* t = **x;");
3555  verifyGoogleFormat("Type* t = *++*x;");
3556  verifyGoogleFormat("*++*x;");
3557  verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
3558  verifyGoogleFormat("Type* t = x++ * y;");
3559  verifyGoogleFormat(
3560      "const char* const p = reinterpret_cast<const char* const>(q);");
3561
3562  verifyIndependentOfContext("a = *(x + y);");
3563  verifyIndependentOfContext("a = &(x + y);");
3564  verifyIndependentOfContext("*(x + y).call();");
3565  verifyIndependentOfContext("&(x + y)->call();");
3566  verifyFormat("void f() { &(*I).first; }");
3567
3568  verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
3569  verifyFormat(
3570      "int *MyValues = {\n"
3571      "  *A, // Operator detection might be confused by the '{'\n"
3572      "  *BB // Operator detection might be confused by previous comment\n"
3573      "};");
3574
3575  verifyIndependentOfContext("if (int *a = &b)");
3576  verifyIndependentOfContext("if (int &a = *b)");
3577  verifyIndependentOfContext("if (a & b[i])");
3578  verifyIndependentOfContext("if (a::b::c::d & b[i])");
3579  verifyIndependentOfContext("if (*b[i])");
3580  verifyIndependentOfContext("if (int *a = (&b))");
3581  verifyIndependentOfContext("while (int *a = &b)");
3582  verifyFormat("void f() {\n"
3583               "  for (const int &v : Values) {\n"
3584               "  }\n"
3585               "}");
3586  verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
3587  verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
3588
3589  verifyFormat("#define MACRO     \\\n"
3590               "  int *i = a * b; \\\n"
3591               "  void f(a *b);",
3592               getLLVMStyleWithColumns(19));
3593
3594  verifyIndependentOfContext("A = new SomeType *[Length];");
3595  verifyIndependentOfContext("A = new SomeType *[Length]();");
3596  verifyIndependentOfContext("T **t = new T *;");
3597  verifyIndependentOfContext("T **t = new T *();");
3598  verifyGoogleFormat("A = new SomeType* [Length]();");
3599  verifyGoogleFormat("A = new SomeType* [Length];");
3600  verifyGoogleFormat("T** t = new T*;");
3601  verifyGoogleFormat("T** t = new T*();");
3602
3603  FormatStyle PointerLeft = getLLVMStyle();
3604  PointerLeft.PointerBindsToType = true;
3605  verifyFormat("delete *x;", PointerLeft);
3606}
3607
3608TEST_F(FormatTest, UnderstandsAttributes) {
3609  verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
3610}
3611
3612TEST_F(FormatTest, UnderstandsEllipsis) {
3613  verifyFormat("int printf(const char *fmt, ...);");
3614  verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
3615  verifyFormat("template <class... Ts> void Foo(Ts *... ts) {}");
3616
3617  FormatStyle PointersLeft = getLLVMStyle();
3618  PointersLeft.PointerBindsToType = true;
3619  verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", PointersLeft);
3620}
3621
3622TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
3623  EXPECT_EQ("int *a;\n"
3624            "int *a;\n"
3625            "int *a;",
3626            format("int *a;\n"
3627                   "int* a;\n"
3628                   "int *a;",
3629                   getGoogleStyle()));
3630  EXPECT_EQ("int* a;\n"
3631            "int* a;\n"
3632            "int* a;",
3633            format("int* a;\n"
3634                   "int* a;\n"
3635                   "int *a;",
3636                   getGoogleStyle()));
3637  EXPECT_EQ("int *a;\n"
3638            "int *a;\n"
3639            "int *a;",
3640            format("int *a;\n"
3641                   "int * a;\n"
3642                   "int *  a;",
3643                   getGoogleStyle()));
3644}
3645
3646TEST_F(FormatTest, UnderstandsRvalueReferences) {
3647  verifyFormat("int f(int &&a) {}");
3648  verifyFormat("int f(int a, char &&b) {}");
3649  verifyFormat("void f() { int &&a = b; }");
3650  verifyGoogleFormat("int f(int a, char&& b) {}");
3651  verifyGoogleFormat("void f() { int&& a = b; }");
3652
3653  verifyIndependentOfContext("A<int &&> a;");
3654  verifyIndependentOfContext("A<int &&, int &&> a;");
3655  verifyGoogleFormat("A<int&&> a;");
3656  verifyGoogleFormat("A<int&&, int&&> a;");
3657}
3658
3659TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
3660  verifyFormat("void f() {\n"
3661               "  x[aaaaaaaaa -\n"
3662               "    b] = 23;\n"
3663               "}",
3664               getLLVMStyleWithColumns(15));
3665}
3666
3667TEST_F(FormatTest, FormatsCasts) {
3668  verifyFormat("Type *A = static_cast<Type *>(P);");
3669  verifyFormat("Type *A = (Type *)P;");
3670  verifyFormat("Type *A = (vector<Type *, int *>)P;");
3671  verifyFormat("int a = (int)(2.0f);");
3672  verifyFormat("int a = (int)2.0f;");
3673  verifyFormat("x[(int32)y];");
3674  verifyFormat("x = (int32)y;");
3675  verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
3676  verifyFormat("int a = (int)*b;");
3677  verifyFormat("int a = (int)2.0f;");
3678  verifyFormat("int a = (int)~0;");
3679  verifyFormat("int a = (int)++a;");
3680  verifyFormat("int a = (int)sizeof(int);");
3681  verifyFormat("int a = (int)+2;");
3682  verifyFormat("my_int a = (my_int)2.0f;");
3683  verifyFormat("my_int a = (my_int)sizeof(int);");
3684  verifyFormat("return (my_int)aaa;");
3685  verifyFormat("#define x ((int)-1)");
3686  verifyFormat("#define p(q) ((int *)&q)");
3687
3688  // FIXME: Without type knowledge, this can still fall apart miserably.
3689  verifyFormat("void f() { my_int a = (my_int) * b; }");
3690  verifyFormat("void f() { return P ? (my_int) * P : (my_int)0; }");
3691  verifyFormat("my_int a = (my_int) ~0;");
3692  verifyFormat("my_int a = (my_int)++ a;");
3693  verifyFormat("my_int a = (my_int) + 2;");
3694
3695  // Don't break after a cast's
3696  verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
3697               "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
3698               "                                   bbbbbbbbbbbbbbbbbbbbbb);");
3699
3700  // These are not casts.
3701  verifyFormat("void f(int *) {}");
3702  verifyFormat("f(foo)->b;");
3703  verifyFormat("f(foo).b;");
3704  verifyFormat("f(foo)(b);");
3705  verifyFormat("f(foo)[b];");
3706  verifyFormat("[](foo) { return 4; }(bar)];");
3707  verifyFormat("(*funptr)(foo)[4];");
3708  verifyFormat("funptrs[4](foo)[4];");
3709  verifyFormat("void f(int *);");
3710  verifyFormat("void f(int *) = 0;");
3711  verifyFormat("void f(SmallVector<int>) {}");
3712  verifyFormat("void f(SmallVector<int>);");
3713  verifyFormat("void f(SmallVector<int>) = 0;");
3714  verifyFormat("void f(int i = (kValue) * kMask) {}");
3715  verifyFormat("void f(int i = (kA * kB) & kMask) {}");
3716  verifyFormat("int a = sizeof(int) * b;");
3717  verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
3718  verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
3719  verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
3720  verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
3721
3722  // These are not casts, but at some point were confused with casts.
3723  verifyFormat("virtual void foo(int *) override;");
3724  verifyFormat("virtual void foo(char &) const;");
3725  verifyFormat("virtual void foo(int *a, char *) const;");
3726  verifyFormat("int a = sizeof(int *) + b;");
3727  verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
3728
3729  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
3730               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
3731  // FIXME: The indentation here is not ideal.
3732  verifyFormat(
3733      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3734      "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
3735      "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
3736}
3737
3738TEST_F(FormatTest, FormatsFunctionTypes) {
3739  verifyFormat("A<bool()> a;");
3740  verifyFormat("A<SomeType()> a;");
3741  verifyFormat("A<void (*)(int, std::string)> a;");
3742  verifyFormat("A<void *(int)>;");
3743  verifyFormat("void *(*a)(int *, SomeType *);");
3744  verifyFormat("int (*func)(void *);");
3745  verifyFormat("void f() { int (*func)(void *); }");
3746
3747  verifyGoogleFormat("A<void*(int*, SomeType*)>;");
3748  verifyGoogleFormat("void* (*a)(int);");
3749
3750  // Other constructs can look somewhat like function types:
3751  verifyFormat("A<sizeof(*x)> a;");
3752  verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
3753  verifyFormat("some_var = function(*some_pointer_var)[0];");
3754  verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
3755}
3756
3757TEST_F(FormatTest, BreaksLongDeclarations) {
3758  verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
3759               "    AnotherNameForTheLongType;",
3760               getGoogleStyle());
3761  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
3762               "    LoooooooooooooooooooooooooooooooooooooooongVariable;",
3763               getGoogleStyle());
3764  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
3765               "    LoooooooooooooooooooooooooooooooooooooooongVariable;",
3766               getGoogleStyle());
3767  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
3768               "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
3769               getGoogleStyle());
3770  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
3771               "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
3772  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
3773               "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
3774
3775  // FIXME: Without the comment, this breaks after "(".
3776  verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
3777               "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
3778               getGoogleStyle());
3779
3780  verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
3781               "                  int LoooooooooooooooooooongParam2) {}");
3782  verifyFormat(
3783      "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
3784      "                                   SourceLocation L, IdentifierIn *II,\n"
3785      "                                   Type *T) {}");
3786  verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
3787               "ReallyReallyLongFunctionName(\n"
3788               "    const std::string &SomeParameter,\n"
3789               "    const SomeType<string, SomeOtherTemplateParameter> &\n"
3790               "        ReallyReallyLongParameterName,\n"
3791               "    const SomeType<string, SomeOtherTemplateParameter> &\n"
3792               "        AnotherLongParameterName) {}");
3793  verifyFormat("template <typename A>\n"
3794               "SomeLoooooooooooooooooooooongType<\n"
3795               "    typename some_namespace::SomeOtherType<A>::Type>\n"
3796               "Function() {}");
3797  verifyFormat(
3798      "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
3799      "    aaaaaaaaaaaaaaaaaaaaaaa;",
3800      getGoogleStyle());
3801
3802  verifyGoogleFormat(
3803      "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
3804      "                                   SourceLocation L) {}");
3805  verifyGoogleFormat(
3806      "some_namespace::LongReturnType\n"
3807      "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
3808      "    int first_long_parameter, int second_parameter) {}");
3809
3810  verifyGoogleFormat("template <typename T>\n"
3811                     "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
3812                     "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
3813  verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
3814                     "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
3815}
3816
3817TEST_F(FormatTest, FormatsArrays) {
3818  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3819               "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
3820  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3821               "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
3822  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3823               "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
3824  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
3825               "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3826               "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
3827  verifyFormat(
3828      "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
3829      "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
3830      "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
3831}
3832
3833TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
3834  verifyFormat("(a)->b();");
3835  verifyFormat("--a;");
3836}
3837
3838TEST_F(FormatTest, HandlesIncludeDirectives) {
3839  verifyFormat("#include <string>\n"
3840               "#include <a/b/c.h>\n"
3841               "#include \"a/b/string\"\n"
3842               "#include \"string.h\"\n"
3843               "#include \"string.h\"\n"
3844               "#include <a-a>\n"
3845               "#include < path with space >\n"
3846               "#include \"abc.h\" // this is included for ABC\n"
3847               "#include \"some long include\" // with a comment\n"
3848               "#include \"some very long include paaaaaaaaaaaaaaaaaaaaaaath\"",
3849               getLLVMStyleWithColumns(35));
3850
3851  verifyFormat("#import <string>");
3852  verifyFormat("#import <a/b/c.h>");
3853  verifyFormat("#import \"a/b/string\"");
3854  verifyFormat("#import \"string.h\"");
3855  verifyFormat("#import \"string.h\"");
3856}
3857
3858//===----------------------------------------------------------------------===//
3859// Error recovery tests.
3860//===----------------------------------------------------------------------===//
3861
3862TEST_F(FormatTest, IncompleteParameterLists) {
3863  FormatStyle NoBinPacking = getLLVMStyle();
3864  NoBinPacking.BinPackParameters = false;
3865  verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
3866               "                        double *min_x,\n"
3867               "                        double *max_x,\n"
3868               "                        double *min_y,\n"
3869               "                        double *max_y,\n"
3870               "                        double *min_z,\n"
3871               "                        double *max_z, ) {}",
3872               NoBinPacking);
3873}
3874
3875TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
3876  verifyFormat("void f() { return; }\n42");
3877  verifyFormat("void f() {\n"
3878               "  if (0)\n"
3879               "    return;\n"
3880               "}\n"
3881               "42");
3882  verifyFormat("void f() { return }\n42");
3883  verifyFormat("void f() {\n"
3884               "  if (0)\n"
3885               "    return\n"
3886               "}\n"
3887               "42");
3888}
3889
3890TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
3891  EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
3892  EXPECT_EQ("void f() {\n"
3893            "  if (a)\n"
3894            "    return\n"
3895            "}",
3896            format("void  f  (  )  {  if  ( a )  return  }"));
3897  EXPECT_EQ("namespace N {\n"
3898            "void f()\n"
3899            "}",
3900            format("namespace  N  {  void f()  }"));
3901  EXPECT_EQ("namespace N {\n"
3902            "void f() {}\n"
3903            "void g()\n"
3904            "}",
3905            format("namespace N  { void f( ) { } void g( ) }"));
3906}
3907
3908TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
3909  verifyFormat("int aaaaaaaa =\n"
3910               "    // Overlylongcomment\n"
3911               "    b;",
3912               getLLVMStyleWithColumns(20));
3913  verifyFormat("function(\n"
3914               "    ShortArgument,\n"
3915               "    LoooooooooooongArgument);\n",
3916               getLLVMStyleWithColumns(20));
3917}
3918
3919TEST_F(FormatTest, IncorrectAccessSpecifier) {
3920  verifyFormat("public:");
3921  verifyFormat("class A {\n"
3922               "public\n"
3923               "  void f() {}\n"
3924               "};");
3925  verifyFormat("public\n"
3926               "int qwerty;");
3927  verifyFormat("public\n"
3928               "B {}");
3929  verifyFormat("public\n"
3930               "{}");
3931  verifyFormat("public\n"
3932               "B { int x; }");
3933}
3934
3935TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
3936  verifyFormat("{");
3937  verifyFormat("#})");
3938}
3939
3940TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
3941  verifyFormat("do {\n}");
3942  verifyFormat("do {\n}\n"
3943               "f();");
3944  verifyFormat("do {\n}\n"
3945               "wheeee(fun);");
3946  verifyFormat("do {\n"
3947               "  f();\n"
3948               "}");
3949}
3950
3951TEST_F(FormatTest, IncorrectCodeMissingParens) {
3952  verifyFormat("if {\n  foo;\n  foo();\n}");
3953  verifyFormat("switch {\n  foo;\n  foo();\n}");
3954  verifyFormat("for {\n  foo;\n  foo();\n}");
3955  verifyFormat("while {\n  foo;\n  foo();\n}");
3956  verifyFormat("do {\n  foo;\n  foo();\n} while;");
3957}
3958
3959TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
3960  verifyFormat("namespace {\n"
3961               "class Foo {  Foo  (\n"
3962               "};\n"
3963               "} // comment");
3964}
3965
3966TEST_F(FormatTest, IncorrectCodeErrorDetection) {
3967  EXPECT_EQ("{\n{}\n", format("{\n{\n}\n"));
3968  EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
3969  EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
3970  EXPECT_EQ("{\n  {}\n  }\n}\n", format("{\n  {\n    }\n  }\n}\n"));
3971
3972  EXPECT_EQ("{\n"
3973            "    {\n"
3974            " breakme(\n"
3975            "     qwe);\n"
3976            "}\n",
3977            format("{\n"
3978                   "    {\n"
3979                   " breakme(qwe);\n"
3980                   "}\n",
3981                   getLLVMStyleWithColumns(10)));
3982}
3983
3984TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
3985  verifyFormat("int x = {\n"
3986               "  avariable,\n"
3987               "  b(alongervariable)\n"
3988               "};",
3989               getLLVMStyleWithColumns(25));
3990}
3991
3992TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
3993  verifyFormat("return (a)(b) { 1, 2, 3 };");
3994}
3995
3996TEST_F(FormatTest, LayoutCxx11ConstructorBraceInitializers) {
3997    verifyFormat("vector<int> x{ 1, 2, 3, 4 };");
3998    verifyFormat("vector<T> x{ {}, {}, {}, {} };");
3999    verifyFormat("f({ 1, 2 });");
4000    verifyFormat("auto v = Foo{ 1 };");
4001    verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });");
4002    verifyFormat("Class::Class : member{ 1, 2, 3 } {}");
4003    verifyFormat("new vector<int>{ 1, 2, 3 };");
4004    verifyFormat("new int[3]{ 1, 2, 3 };");
4005    verifyFormat("return { arg1, arg2 };");
4006    verifyFormat("return { arg1, SomeType{ parameter } };");
4007    verifyFormat("new T{ arg1, arg2 };");
4008    verifyFormat("class Class {\n"
4009                 "  T member = { arg1, arg2 };\n"
4010                 "};");
4011    verifyFormat(
4012        "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4013        "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
4014        "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4015        "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };");
4016    verifyFormat("DoSomethingWithVector({} /* No data */);");
4017    verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });");
4018    verifyFormat(
4019        "someFunction(OtherParam, BracedList{\n"
4020        "                           // comment 1 (Forcing interesting break)\n"
4021        "                           param1, param2,\n"
4022        "                           // comment 2\n"
4023        "                           param3, param4\n"
4024        "                         });");
4025
4026    FormatStyle NoSpaces = getLLVMStyle();
4027    NoSpaces.Cpp11BracedListStyle = true;
4028    verifyFormat("vector<int> x{1, 2, 3, 4};", NoSpaces);
4029    verifyFormat("vector<T> x{{}, {}, {}, {}};", NoSpaces);
4030    verifyFormat("f({1, 2});", NoSpaces);
4031    verifyFormat("auto v = Foo{-1};", NoSpaces);
4032    verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});", NoSpaces);
4033    verifyFormat("Class::Class : member{1, 2, 3} {}", NoSpaces);
4034    verifyFormat("new vector<int>{1, 2, 3};", NoSpaces);
4035    verifyFormat("new int[3]{1, 2, 3};", NoSpaces);
4036    verifyFormat("return {arg1, arg2};", NoSpaces);
4037    verifyFormat("return {arg1, SomeType{parameter}};", NoSpaces);
4038    verifyFormat("new T{arg1, arg2};", NoSpaces);
4039    verifyFormat("class Class {\n"
4040                 "  T member = {arg1, arg2};\n"
4041                 "};",
4042                 NoSpaces);
4043}
4044
4045TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
4046  verifyFormat("void f() { return 42; }");
4047  verifyFormat("void f() {\n"
4048               "  // Comment\n"
4049               "}");
4050  verifyFormat("{\n"
4051               "#error {\n"
4052               "  int a;\n"
4053               "}");
4054  verifyFormat("{\n"
4055               "  int a;\n"
4056               "#error {\n"
4057               "}");
4058  verifyFormat("void f() {} // comment");
4059  verifyFormat("void f() { int a; } // comment");
4060  verifyFormat("void f() {\n"
4061               "} // comment",
4062               getLLVMStyleWithColumns(15));
4063
4064  verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
4065  verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
4066
4067  verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
4068  verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
4069}
4070
4071TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
4072  // Elaborate type variable declarations.
4073  verifyFormat("struct foo a = { bar };\nint n;");
4074  verifyFormat("class foo a = { bar };\nint n;");
4075  verifyFormat("union foo a = { bar };\nint n;");
4076
4077  // Elaborate types inside function definitions.
4078  verifyFormat("struct foo f() {}\nint n;");
4079  verifyFormat("class foo f() {}\nint n;");
4080  verifyFormat("union foo f() {}\nint n;");
4081
4082  // Templates.
4083  verifyFormat("template <class X> void f() {}\nint n;");
4084  verifyFormat("template <struct X> void f() {}\nint n;");
4085  verifyFormat("template <union X> void f() {}\nint n;");
4086
4087  // Actual definitions...
4088  verifyFormat("struct {\n} n;");
4089  verifyFormat(
4090      "template <template <class T, class Y>, class Z> class X {\n} n;");
4091  verifyFormat("union Z {\n  int n;\n} x;");
4092  verifyFormat("class MACRO Z {\n} n;");
4093  verifyFormat("class MACRO(X) Z {\n} n;");
4094  verifyFormat("class __attribute__(X) Z {\n} n;");
4095  verifyFormat("class __declspec(X) Z {\n} n;");
4096  verifyFormat("class A##B##C {\n} n;");
4097
4098  // Redefinition from nested context:
4099  verifyFormat("class A::B::C {\n} n;");
4100
4101  // Template definitions.
4102  verifyFormat(
4103      "template <typename F>\n"
4104      "Matcher(const Matcher<F> &Other,\n"
4105      "        typename enable_if_c<is_base_of<F, T>::value &&\n"
4106      "                             !is_same<F, T>::value>::type * = 0)\n"
4107      "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
4108
4109  // FIXME: This is still incorrectly handled at the formatter side.
4110  verifyFormat("template <> struct X < 15, i < 3 && 42 < 50 && 33<28> {};");
4111
4112  // FIXME:
4113  // This now gets parsed incorrectly as class definition.
4114  // verifyFormat("class A<int> f() {\n}\nint n;");
4115
4116  // Elaborate types where incorrectly parsing the structural element would
4117  // break the indent.
4118  verifyFormat("if (true)\n"
4119               "  class X x;\n"
4120               "else\n"
4121               "  f();\n");
4122
4123  // This is simply incomplete. Formatting is not important, but must not crash.
4124  verifyFormat("class A:");
4125}
4126
4127TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
4128  verifyFormat("#error Leave     all         white!!!!! space* alone!\n");
4129  verifyFormat("#warning Leave     all         white!!!!! space* alone!\n");
4130  EXPECT_EQ("#error 1", format("  #  error   1"));
4131  EXPECT_EQ("#warning 1", format("  #  warning 1"));
4132}
4133
4134TEST_F(FormatTest, FormatHashIfExpressions) {
4135  // FIXME: Come up with a better indentation for #elif.
4136  verifyFormat(
4137      "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
4138      "    defined(BBBBBBBB)\n"
4139      "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
4140      "    defined(BBBBBBBB)\n"
4141      "#endif",
4142      getLLVMStyleWithColumns(65));
4143}
4144
4145TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
4146  FormatStyle AllowsMergedIf = getGoogleStyle();
4147  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
4148  verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
4149  verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
4150  verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
4151  EXPECT_EQ("if (true) return 42;",
4152            format("if (true)\nreturn 42;", AllowsMergedIf));
4153  FormatStyle ShortMergedIf = AllowsMergedIf;
4154  ShortMergedIf.ColumnLimit = 25;
4155  verifyFormat("#define A \\\n"
4156               "  if (true) return 42;",
4157               ShortMergedIf);
4158  verifyFormat("#define A \\\n"
4159               "  f();    \\\n"
4160               "  if (true)\n"
4161               "#define B",
4162               ShortMergedIf);
4163  verifyFormat("#define A \\\n"
4164               "  f();    \\\n"
4165               "  if (true)\n"
4166               "g();",
4167               ShortMergedIf);
4168  verifyFormat("{\n"
4169               "#ifdef A\n"
4170               "  // Comment\n"
4171               "  if (true) continue;\n"
4172               "#endif\n"
4173               "  // Comment\n"
4174               "  if (true) continue;",
4175               ShortMergedIf);
4176}
4177
4178TEST_F(FormatTest, BlockCommentsInControlLoops) {
4179  verifyFormat("if (0) /* a comment in a strange place */ {\n"
4180               "  f();\n"
4181               "}");
4182  verifyFormat("if (0) /* a comment in a strange place */ {\n"
4183               "  f();\n"
4184               "} /* another comment */ else /* comment #3 */ {\n"
4185               "  g();\n"
4186               "}");
4187  verifyFormat("while (0) /* a comment in a strange place */ {\n"
4188               "  f();\n"
4189               "}");
4190  verifyFormat("for (;;) /* a comment in a strange place */ {\n"
4191               "  f();\n"
4192               "}");
4193  verifyFormat("do /* a comment in a strange place */ {\n"
4194               "  f();\n"
4195               "} /* another comment */ while (0);");
4196}
4197
4198TEST_F(FormatTest, BlockComments) {
4199  EXPECT_EQ("/* */ /* */ /* */\n/* */ /* */ /* */",
4200            format("/* *//* */  /* */\n/* *//* */  /* */"));
4201  EXPECT_EQ("/* */ a /* */ b;", format("  /* */  a/* */  b;"));
4202  EXPECT_EQ("#define A /*123*/\\\n"
4203            "  b\n"
4204            "/* */\n"
4205            "someCall(\n"
4206            "    parameter);",
4207            format("#define A /*123*/ b\n"
4208                   "/* */\n"
4209                   "someCall(parameter);",
4210                   getLLVMStyleWithColumns(15)));
4211
4212  EXPECT_EQ("#define A\n"
4213            "/* */ someCall(\n"
4214            "    parameter);",
4215            format("#define A\n"
4216                   "/* */someCall(parameter);",
4217                   getLLVMStyleWithColumns(15)));
4218  EXPECT_EQ("/*\n**\n*/", format("/*\n**\n*/"));
4219  EXPECT_EQ("/*\n"
4220            "*\n"
4221            " * aaaaaa\n"
4222            "*aaaaaa\n"
4223            "*/",
4224            format("/*\n"
4225                   "*\n"
4226                   " * aaaaaa aaaaaa\n"
4227                   "*/",
4228                   getLLVMStyleWithColumns(10)));
4229  EXPECT_EQ("/*\n"
4230            "**\n"
4231            "* aaaaaa\n"
4232            "*aaaaaa\n"
4233            "*/",
4234            format("/*\n"
4235                   "**\n"
4236                   "* aaaaaa aaaaaa\n"
4237                   "*/",
4238                   getLLVMStyleWithColumns(10)));
4239
4240  FormatStyle NoBinPacking = getLLVMStyle();
4241  NoBinPacking.BinPackParameters = false;
4242  EXPECT_EQ("someFunction(1, /* comment 1 */\n"
4243            "             2, /* comment 2 */\n"
4244            "             3, /* comment 3 */\n"
4245            "             aaaa,\n"
4246            "             bbbb);",
4247            format("someFunction (1,   /* comment 1 */\n"
4248                   "                2, /* comment 2 */  \n"
4249                   "               3,   /* comment 3 */\n"
4250                   "aaaa, bbbb );",
4251                   NoBinPacking));
4252  verifyFormat(
4253      "bool aaaaaaaaaaaaa = /* comment: */ aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4254      "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
4255  EXPECT_EQ(
4256      "bool aaaaaaaaaaaaa = /* trailing comment */\n"
4257      "    aaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4258      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaa;",
4259      format(
4260          "bool       aaaaaaaaaaaaa =       /* trailing comment */\n"
4261          "    aaaaaaaaaaaaaaaaaaaaaaaaaaa||aaaaaaaaaaaaaaaaaaaaaaaaa    ||\n"
4262          "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa   || aaaaaaaaaaaaaaaaaaaaaaaaaa;"));
4263  EXPECT_EQ(
4264      "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
4265      "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   /* comment */\n"
4266      "int cccccccccccccccccccccccccccccc;       /* comment */\n",
4267      format("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; /* comment */\n"
4268             "int      bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; /* comment */\n"
4269             "int    cccccccccccccccccccccccccccccc;  /* comment */\n"));
4270
4271  verifyFormat("void f(int * /* unused */) {}");
4272
4273  EXPECT_EQ("/*\n"
4274            " **\n"
4275            " */",
4276            format("/*\n"
4277                   " **\n"
4278                   " */"));
4279  EXPECT_EQ("/*\n"
4280            " *q\n"
4281            " */",
4282            format("/*\n"
4283                   " *q\n"
4284                   " */"));
4285  EXPECT_EQ("/*\n"
4286            " * q\n"
4287            " */",
4288            format("/*\n"
4289                   " * q\n"
4290                   " */"));
4291  EXPECT_EQ("/*\n"
4292            " **/",
4293            format("/*\n"
4294                   " **/"));
4295  EXPECT_EQ("/*\n"
4296            " ***/",
4297            format("/*\n"
4298                   " ***/"));
4299}
4300
4301TEST_F(FormatTest, BlockCommentsInMacros) {
4302  EXPECT_EQ("#define A          \\\n"
4303            "  {                \\\n"
4304            "    /* one line */ \\\n"
4305            "    someCall();",
4306            format("#define A {        \\\n"
4307                   "  /* one line */   \\\n"
4308                   "  someCall();",
4309                   getLLVMStyleWithColumns(20)));
4310  EXPECT_EQ("#define A          \\\n"
4311            "  {                \\\n"
4312            "    /* previous */ \\\n"
4313            "    /* one line */ \\\n"
4314            "    someCall();",
4315            format("#define A {        \\\n"
4316                   "  /* previous */   \\\n"
4317                   "  /* one line */   \\\n"
4318                   "  someCall();",
4319                   getLLVMStyleWithColumns(20)));
4320}
4321
4322TEST_F(FormatTest, BlockCommentsAtEndOfLine) {
4323  EXPECT_EQ("a = {\n"
4324            "  1111 /*    */\n"
4325            "};",
4326            format("a = {1111 /*    */\n"
4327                   "};",
4328                   getLLVMStyleWithColumns(15)));
4329  EXPECT_EQ("a = {\n"
4330            "  1111 /*      */\n"
4331            "};",
4332            format("a = {1111 /*      */\n"
4333                   "};",
4334                   getLLVMStyleWithColumns(15)));
4335
4336  // FIXME: The formatting is still wrong here.
4337  EXPECT_EQ("a = {\n"
4338            "  1111 /*      a\n"
4339            "          */\n"
4340            "};",
4341            format("a = {1111 /*      a */\n"
4342                   "};",
4343                   getLLVMStyleWithColumns(15)));
4344}
4345
4346TEST_F(FormatTest, IndentLineCommentsInStartOfBlockAtEndOfFile) {
4347  // FIXME: This is not what we want...
4348  verifyFormat("{\n"
4349               "// a"
4350               "// b");
4351}
4352
4353TEST_F(FormatTest, FormatStarDependingOnContext) {
4354  verifyFormat("void f(int *a);");
4355  verifyFormat("void f() { f(fint * b); }");
4356  verifyFormat("class A {\n  void f(int *a);\n};");
4357  verifyFormat("class A {\n  int *a;\n};");
4358  verifyFormat("namespace a {\n"
4359               "namespace b {\n"
4360               "class A {\n"
4361               "  void f() {}\n"
4362               "  int *a;\n"
4363               "};\n"
4364               "}\n"
4365               "}");
4366}
4367
4368TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
4369  verifyFormat("while");
4370  verifyFormat("operator");
4371}
4372
4373//===----------------------------------------------------------------------===//
4374// Objective-C tests.
4375//===----------------------------------------------------------------------===//
4376
4377TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
4378  verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
4379  EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
4380            format("-(NSUInteger)indexOfObject:(id)anObject;"));
4381  EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
4382  EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
4383  EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
4384            format("-(NSInteger)Method3:(id)anObject;"));
4385  EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
4386            format("-(NSInteger)Method4:(id)anObject;"));
4387  EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
4388            format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
4389  EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
4390            format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
4391  EXPECT_EQ(
4392      "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;",
4393      format(
4394          "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;"));
4395
4396  // Very long objectiveC method declaration.
4397  verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
4398               "                    inRange:(NSRange)range\n"
4399               "                   outRange:(NSRange)out_range\n"
4400               "                  outRange1:(NSRange)out_range1\n"
4401               "                  outRange2:(NSRange)out_range2\n"
4402               "                  outRange3:(NSRange)out_range3\n"
4403               "                  outRange4:(NSRange)out_range4\n"
4404               "                  outRange5:(NSRange)out_range5\n"
4405               "                  outRange6:(NSRange)out_range6\n"
4406               "                  outRange7:(NSRange)out_range7\n"
4407               "                  outRange8:(NSRange)out_range8\n"
4408               "                  outRange9:(NSRange)out_range9;");
4409
4410  verifyFormat("- (int)sum:(vector<int>)numbers;");
4411  verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
4412  // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
4413  // protocol lists (but not for template classes):
4414  //verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
4415
4416  verifyFormat("- (int (*)())foo:(int (*)())f;");
4417  verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
4418
4419  // If there's no return type (very rare in practice!), LLVM and Google style
4420  // agree.
4421  verifyFormat("- foo;");
4422  verifyFormat("- foo:(int)f;");
4423  verifyGoogleFormat("- foo:(int)foo;");
4424}
4425
4426TEST_F(FormatTest, FormatObjCBlocks) {
4427  verifyFormat("int (^Block)(int, int);");
4428  verifyFormat("int (^Block1)(int, int) = ^(int i, int j)");
4429}
4430
4431TEST_F(FormatTest, FormatObjCInterface) {
4432  verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
4433               "@public\n"
4434               "  int field1;\n"
4435               "@protected\n"
4436               "  int field2;\n"
4437               "@private\n"
4438               "  int field3;\n"
4439               "@package\n"
4440               "  int field4;\n"
4441               "}\n"
4442               "+ (id)init;\n"
4443               "@end");
4444
4445  verifyGoogleFormat("@interface Foo : NSObject<NSSomeDelegate> {\n"
4446                     " @public\n"
4447                     "  int field1;\n"
4448                     " @protected\n"
4449                     "  int field2;\n"
4450                     " @private\n"
4451                     "  int field3;\n"
4452                     " @package\n"
4453                     "  int field4;\n"
4454                     "}\n"
4455                     "+ (id)init;\n"
4456                     "@end");
4457
4458  verifyFormat("@interface /* wait for it */ Foo\n"
4459               "+ (id)init;\n"
4460               "// Look, a comment!\n"
4461               "- (int)answerWith:(int)i;\n"
4462               "@end");
4463
4464  verifyFormat("@interface Foo\n"
4465               "@end\n"
4466               "@interface Bar\n"
4467               "@end");
4468
4469  verifyFormat("@interface Foo : Bar\n"
4470               "+ (id)init;\n"
4471               "@end");
4472
4473  verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
4474               "+ (id)init;\n"
4475               "@end");
4476
4477  verifyGoogleFormat("@interface Foo : Bar<Baz, Quux>\n"
4478                     "+ (id)init;\n"
4479                     "@end");
4480
4481  verifyFormat("@interface Foo (HackStuff)\n"
4482               "+ (id)init;\n"
4483               "@end");
4484
4485  verifyFormat("@interface Foo ()\n"
4486               "+ (id)init;\n"
4487               "@end");
4488
4489  verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
4490               "+ (id)init;\n"
4491               "@end");
4492
4493  verifyGoogleFormat("@interface Foo (HackStuff)<MyProtocol>\n"
4494                     "+ (id)init;\n"
4495                     "@end");
4496
4497  verifyFormat("@interface Foo {\n"
4498               "  int _i;\n"
4499               "}\n"
4500               "+ (id)init;\n"
4501               "@end");
4502
4503  verifyFormat("@interface Foo : Bar {\n"
4504               "  int _i;\n"
4505               "}\n"
4506               "+ (id)init;\n"
4507               "@end");
4508
4509  verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
4510               "  int _i;\n"
4511               "}\n"
4512               "+ (id)init;\n"
4513               "@end");
4514
4515  verifyFormat("@interface Foo (HackStuff) {\n"
4516               "  int _i;\n"
4517               "}\n"
4518               "+ (id)init;\n"
4519               "@end");
4520
4521  verifyFormat("@interface Foo () {\n"
4522               "  int _i;\n"
4523               "}\n"
4524               "+ (id)init;\n"
4525               "@end");
4526
4527  verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
4528               "  int _i;\n"
4529               "}\n"
4530               "+ (id)init;\n"
4531               "@end");
4532}
4533
4534TEST_F(FormatTest, FormatObjCImplementation) {
4535  verifyFormat("@implementation Foo : NSObject {\n"
4536               "@public\n"
4537               "  int field1;\n"
4538               "@protected\n"
4539               "  int field2;\n"
4540               "@private\n"
4541               "  int field3;\n"
4542               "@package\n"
4543               "  int field4;\n"
4544               "}\n"
4545               "+ (id)init {\n}\n"
4546               "@end");
4547
4548  verifyGoogleFormat("@implementation Foo : NSObject {\n"
4549                     " @public\n"
4550                     "  int field1;\n"
4551                     " @protected\n"
4552                     "  int field2;\n"
4553                     " @private\n"
4554                     "  int field3;\n"
4555                     " @package\n"
4556                     "  int field4;\n"
4557                     "}\n"
4558                     "+ (id)init {\n}\n"
4559                     "@end");
4560
4561  verifyFormat("@implementation Foo\n"
4562               "+ (id)init {\n"
4563               "  if (true)\n"
4564               "    return nil;\n"
4565               "}\n"
4566               "// Look, a comment!\n"
4567               "- (int)answerWith:(int)i {\n"
4568               "  return i;\n"
4569               "}\n"
4570               "+ (int)answerWith:(int)i {\n"
4571               "  return i;\n"
4572               "}\n"
4573               "@end");
4574
4575  verifyFormat("@implementation Foo\n"
4576               "@end\n"
4577               "@implementation Bar\n"
4578               "@end");
4579
4580  verifyFormat("@implementation Foo : Bar\n"
4581               "+ (id)init {\n}\n"
4582               "- (void)foo {\n}\n"
4583               "@end");
4584
4585  verifyFormat("@implementation Foo {\n"
4586               "  int _i;\n"
4587               "}\n"
4588               "+ (id)init {\n}\n"
4589               "@end");
4590
4591  verifyFormat("@implementation Foo : Bar {\n"
4592               "  int _i;\n"
4593               "}\n"
4594               "+ (id)init {\n}\n"
4595               "@end");
4596
4597  verifyFormat("@implementation Foo (HackStuff)\n"
4598               "+ (id)init {\n}\n"
4599               "@end");
4600}
4601
4602TEST_F(FormatTest, FormatObjCProtocol) {
4603  verifyFormat("@protocol Foo\n"
4604               "@property(weak) id delegate;\n"
4605               "- (NSUInteger)numberOfThings;\n"
4606               "@end");
4607
4608  verifyFormat("@protocol MyProtocol <NSObject>\n"
4609               "- (NSUInteger)numberOfThings;\n"
4610               "@end");
4611
4612  verifyGoogleFormat("@protocol MyProtocol<NSObject>\n"
4613                     "- (NSUInteger)numberOfThings;\n"
4614                     "@end");
4615
4616  verifyFormat("@protocol Foo;\n"
4617               "@protocol Bar;\n");
4618
4619  verifyFormat("@protocol Foo\n"
4620               "@end\n"
4621               "@protocol Bar\n"
4622               "@end");
4623
4624  verifyFormat("@protocol myProtocol\n"
4625               "- (void)mandatoryWithInt:(int)i;\n"
4626               "@optional\n"
4627               "- (void)optional;\n"
4628               "@required\n"
4629               "- (void)required;\n"
4630               "@optional\n"
4631               "@property(assign) int madProp;\n"
4632               "@end\n");
4633}
4634
4635TEST_F(FormatTest, FormatObjCMethodDeclarations) {
4636  verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
4637               "                   rect:(NSRect)theRect\n"
4638               "               interval:(float)theInterval {\n"
4639               "}");
4640  verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
4641               "          longKeyword:(NSRect)theRect\n"
4642               "    evenLongerKeyword:(float)theInterval\n"
4643               "                error:(NSError **)theError {\n"
4644               "}");
4645}
4646
4647TEST_F(FormatTest, FormatObjCMethodExpr) {
4648  verifyFormat("[foo bar:baz];");
4649  verifyFormat("return [foo bar:baz];");
4650  verifyFormat("f([foo bar:baz]);");
4651  verifyFormat("f(2, [foo bar:baz]);");
4652  verifyFormat("f(2, a ? b : c);");
4653  verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
4654
4655  // Unary operators.
4656  verifyFormat("int a = +[foo bar:baz];");
4657  verifyFormat("int a = -[foo bar:baz];");
4658  verifyFormat("int a = ![foo bar:baz];");
4659  verifyFormat("int a = ~[foo bar:baz];");
4660  verifyFormat("int a = ++[foo bar:baz];");
4661  verifyFormat("int a = --[foo bar:baz];");
4662  verifyFormat("int a = sizeof [foo bar:baz];");
4663  verifyFormat("int a = alignof [foo bar:baz];", getGoogleStyle());
4664  verifyFormat("int a = &[foo bar:baz];");
4665  verifyFormat("int a = *[foo bar:baz];");
4666  // FIXME: Make casts work, without breaking f()[4].
4667  //verifyFormat("int a = (int)[foo bar:baz];");
4668  //verifyFormat("return (int)[foo bar:baz];");
4669  //verifyFormat("(void)[foo bar:baz];");
4670  verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
4671
4672  // Binary operators.
4673  verifyFormat("[foo bar:baz], [foo bar:baz];");
4674  verifyFormat("[foo bar:baz] = [foo bar:baz];");
4675  verifyFormat("[foo bar:baz] *= [foo bar:baz];");
4676  verifyFormat("[foo bar:baz] /= [foo bar:baz];");
4677  verifyFormat("[foo bar:baz] %= [foo bar:baz];");
4678  verifyFormat("[foo bar:baz] += [foo bar:baz];");
4679  verifyFormat("[foo bar:baz] -= [foo bar:baz];");
4680  verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
4681  verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
4682  verifyFormat("[foo bar:baz] &= [foo bar:baz];");
4683  verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
4684  verifyFormat("[foo bar:baz] |= [foo bar:baz];");
4685  verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
4686  verifyFormat("[foo bar:baz] || [foo bar:baz];");
4687  verifyFormat("[foo bar:baz] && [foo bar:baz];");
4688  verifyFormat("[foo bar:baz] | [foo bar:baz];");
4689  verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
4690  verifyFormat("[foo bar:baz] & [foo bar:baz];");
4691  verifyFormat("[foo bar:baz] == [foo bar:baz];");
4692  verifyFormat("[foo bar:baz] != [foo bar:baz];");
4693  verifyFormat("[foo bar:baz] >= [foo bar:baz];");
4694  verifyFormat("[foo bar:baz] <= [foo bar:baz];");
4695  verifyFormat("[foo bar:baz] > [foo bar:baz];");
4696  verifyFormat("[foo bar:baz] < [foo bar:baz];");
4697  verifyFormat("[foo bar:baz] >> [foo bar:baz];");
4698  verifyFormat("[foo bar:baz] << [foo bar:baz];");
4699  verifyFormat("[foo bar:baz] - [foo bar:baz];");
4700  verifyFormat("[foo bar:baz] + [foo bar:baz];");
4701  verifyFormat("[foo bar:baz] * [foo bar:baz];");
4702  verifyFormat("[foo bar:baz] / [foo bar:baz];");
4703  verifyFormat("[foo bar:baz] % [foo bar:baz];");
4704  // Whew!
4705
4706  verifyFormat("return in[42];");
4707  verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
4708               "}");
4709
4710  verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
4711  verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
4712  verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
4713  verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
4714  verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
4715  verifyFormat("[button setAction:@selector(zoomOut:)];");
4716  verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
4717
4718  verifyFormat("arr[[self indexForFoo:a]];");
4719  verifyFormat("throw [self errorFor:a];");
4720  verifyFormat("@throw [self errorFor:a];");
4721
4722  verifyFormat("[(id)foo bar:(id)baz quux:(id)snorf];");
4723  verifyFormat("[(id)foo bar:(id) ? baz : quux];");
4724  verifyFormat("4 > 4 ? (id)a : (id)baz;");
4725
4726  // This tests that the formatter doesn't break after "backing" but before ":",
4727  // which would be at 80 columns.
4728  verifyFormat(
4729      "void f() {\n"
4730      "  if ((self = [super initWithContentRect:contentRect\n"
4731      "                               styleMask:styleMask\n"
4732      "                                 backing:NSBackingStoreBuffered\n"
4733      "                                   defer:YES]))");
4734
4735  verifyFormat(
4736      "[foo checkThatBreakingAfterColonWorksOk:\n"
4737      "        [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
4738
4739  verifyFormat("[myObj short:arg1 // Force line break\n"
4740               "          longKeyword:arg2\n"
4741               "    evenLongerKeyword:arg3\n"
4742               "                error:arg4];");
4743  verifyFormat(
4744      "void f() {\n"
4745      "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
4746      "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
4747      "                                     pos.width(), pos.height())\n"
4748      "                styleMask:NSBorderlessWindowMask\n"
4749      "                  backing:NSBackingStoreBuffered\n"
4750      "                    defer:NO]);\n"
4751      "}");
4752  verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
4753               "                             with:contentsNativeView];");
4754
4755  verifyFormat(
4756      "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
4757      "           owner:nillllll];");
4758
4759  verifyFormat(
4760      "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
4761      "        forType:kBookmarkButtonDragType];");
4762
4763  verifyFormat("[defaultCenter addObserver:self\n"
4764               "                  selector:@selector(willEnterFullscreen)\n"
4765               "                      name:kWillEnterFullscreenNotification\n"
4766               "                    object:nil];");
4767  verifyFormat("[image_rep drawInRect:drawRect\n"
4768               "             fromRect:NSZeroRect\n"
4769               "            operation:NSCompositeCopy\n"
4770               "             fraction:1.0\n"
4771               "       respectFlipped:NO\n"
4772               "                hints:nil];");
4773
4774  verifyFormat(
4775      "scoped_nsobject<NSTextField> message(\n"
4776      "    // The frame will be fixed up when |-setMessageText:| is called.\n"
4777      "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
4778}
4779
4780TEST_F(FormatTest, ObjCAt) {
4781  verifyFormat("@autoreleasepool");
4782  verifyFormat("@catch");
4783  verifyFormat("@class");
4784  verifyFormat("@compatibility_alias");
4785  verifyFormat("@defs");
4786  verifyFormat("@dynamic");
4787  verifyFormat("@encode");
4788  verifyFormat("@end");
4789  verifyFormat("@finally");
4790  verifyFormat("@implementation");
4791  verifyFormat("@import");
4792  verifyFormat("@interface");
4793  verifyFormat("@optional");
4794  verifyFormat("@package");
4795  verifyFormat("@private");
4796  verifyFormat("@property");
4797  verifyFormat("@protected");
4798  verifyFormat("@protocol");
4799  verifyFormat("@public");
4800  verifyFormat("@required");
4801  verifyFormat("@selector");
4802  verifyFormat("@synchronized");
4803  verifyFormat("@synthesize");
4804  verifyFormat("@throw");
4805  verifyFormat("@try");
4806
4807  EXPECT_EQ("@interface", format("@ interface"));
4808
4809  // The precise formatting of this doesn't matter, nobody writes code like
4810  // this.
4811  verifyFormat("@ /*foo*/ interface");
4812}
4813
4814TEST_F(FormatTest, ObjCSnippets) {
4815  verifyFormat("@autoreleasepool {\n"
4816               "  foo();\n"
4817               "}");
4818  verifyFormat("@class Foo, Bar;");
4819  verifyFormat("@compatibility_alias AliasName ExistingClass;");
4820  verifyFormat("@dynamic textColor;");
4821  verifyFormat("char *buf1 = @encode(int *);");
4822  verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
4823  verifyFormat("char *buf1 = @encode(int **);");
4824  verifyFormat("Protocol *proto = @protocol(p1);");
4825  verifyFormat("SEL s = @selector(foo:);");
4826  verifyFormat("@synchronized(self) {\n"
4827               "  f();\n"
4828               "}");
4829
4830  verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
4831  verifyGoogleFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
4832
4833  verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
4834  verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
4835  verifyGoogleFormat("@property(assign, getter=isEditable) BOOL editable;");
4836
4837  verifyFormat("@import foo.bar;\n"
4838               "@import baz;");
4839}
4840
4841TEST_F(FormatTest, ObjCLiterals) {
4842  verifyFormat("@\"String\"");
4843  verifyFormat("@1");
4844  verifyFormat("@+4.8");
4845  verifyFormat("@-4");
4846  verifyFormat("@1LL");
4847  verifyFormat("@.5");
4848  verifyFormat("@'c'");
4849  verifyFormat("@true");
4850
4851  verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
4852  verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
4853  verifyFormat("NSNumber *favoriteColor = @(Green);");
4854  verifyFormat("NSString *path = @(getenv(\"PATH\"));");
4855
4856  verifyFormat("@[");
4857  verifyFormat("@[]");
4858  verifyFormat(
4859      "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
4860  verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
4861
4862  verifyFormat("@{");
4863  verifyFormat("@{}");
4864  verifyFormat("@{ @\"one\" : @1 }");
4865  verifyFormat("return @{ @\"one\" : @1 };");
4866  verifyFormat("@{ @\"one\" : @1, }");
4867
4868  verifyFormat("@{ @\"one\" : @{ @2 : @1 } }");
4869  verifyFormat("@{ @\"one\" : @{ @2 : @1 }, }");
4870
4871  verifyFormat("@{ 1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2 }");
4872  verifyFormat("[self setDict:@{}");
4873  verifyFormat("[self setDict:@{ @1 : @2 }");
4874  verifyFormat("NSLog(@\"%@\", @{ @1 : @2, @2 : @3 }[@1]);");
4875  verifyFormat(
4876      "NSDictionary *masses = @{ @\"H\" : @1.0078, @\"He\" : @4.0026 };");
4877  verifyFormat(
4878      "NSDictionary *settings = @{ AVEncoderKey : @(AVAudioQualityMax) };");
4879
4880  // FIXME: Nested and multi-line array and dictionary literals need more work.
4881  verifyFormat(
4882      "NSDictionary *d = @{ @\"nam\" : NSUserNam(), @\"dte\" : [NSDate date],\n"
4883      "                     @\"processInfo\" : [NSProcessInfo processInfo] };");
4884  verifyFormat(
4885      "@{ NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :\n"
4886      "   regularFont, };");
4887
4888}
4889
4890TEST_F(FormatTest, ReformatRegionAdjustsIndent) {
4891  EXPECT_EQ("{\n"
4892            "{\n"
4893            "a;\n"
4894            "b;\n"
4895            "}\n"
4896            "}",
4897            format("{\n"
4898                   "{\n"
4899                   "a;\n"
4900                   "     b;\n"
4901                   "}\n"
4902                   "}",
4903                   13, 2, getLLVMStyle()));
4904  EXPECT_EQ("{\n"
4905            "{\n"
4906            "  a;\n"
4907            "b;\n"
4908            "}\n"
4909            "}",
4910            format("{\n"
4911                   "{\n"
4912                   "     a;\n"
4913                   "b;\n"
4914                   "}\n"
4915                   "}",
4916                   9, 2, getLLVMStyle()));
4917  EXPECT_EQ("{\n"
4918            "{\n"
4919            "public:\n"
4920            "  b;\n"
4921            "}\n"
4922            "}",
4923            format("{\n"
4924                   "{\n"
4925                   "public:\n"
4926                   "     b;\n"
4927                   "}\n"
4928                   "}",
4929                   17, 2, getLLVMStyle()));
4930  EXPECT_EQ("{\n"
4931            "{\n"
4932            "a;\n"
4933            "}\n"
4934            "{\n"
4935            "  b; //\n"
4936            "}\n"
4937            "}",
4938            format("{\n"
4939                   "{\n"
4940                   "a;\n"
4941                   "}\n"
4942                   "{\n"
4943                   "           b; //\n"
4944                   "}\n"
4945                   "}",
4946                   22, 2, getLLVMStyle()));
4947  EXPECT_EQ("  {\n"
4948            "    a; //\n"
4949            "  }",
4950            format("  {\n"
4951                   "a; //\n"
4952                   "  }",
4953                   4, 2, getLLVMStyle()));
4954  EXPECT_EQ("void f() {}\n"
4955            "void g() {}",
4956            format("void f() {}\n"
4957                   "void g() {}",
4958                   13, 0, getLLVMStyle()));
4959  EXPECT_EQ("int a; // comment\n"
4960            "       // line 2\n"
4961            "int b;",
4962            format("int a; // comment\n"
4963                   "       // line 2\n"
4964                   "  int b;",
4965                   35, 0, getLLVMStyle()));
4966  EXPECT_EQ("  int a;\n"
4967            "  void\n"
4968            "  ffffff() {\n"
4969            "  }",
4970            format("  int a;\n"
4971                   "void ffffff() {}",
4972                   11, 0, getLLVMStyleWithColumns(11)));
4973}
4974
4975TEST_F(FormatTest, BreakStringLiterals) {
4976  EXPECT_EQ("\"some text \"\n"
4977            "\"other\";",
4978            format("\"some text other\";", getLLVMStyleWithColumns(12)));
4979  EXPECT_EQ("\"some text \"\n"
4980            "\"other\";",
4981            format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
4982  EXPECT_EQ(
4983      "#define A  \\\n"
4984      "  \"some \"  \\\n"
4985      "  \"text \"  \\\n"
4986      "  \"other\";",
4987      format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
4988  EXPECT_EQ(
4989      "#define A  \\\n"
4990      "  \"so \"    \\\n"
4991      "  \"text \"  \\\n"
4992      "  \"other\";",
4993      format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
4994
4995  EXPECT_EQ("\"some text\"",
4996            format("\"some text\"", getLLVMStyleWithColumns(1)));
4997  EXPECT_EQ("\"some text\"",
4998            format("\"some text\"", getLLVMStyleWithColumns(11)));
4999  EXPECT_EQ("\"some \"\n"
5000            "\"text\"",
5001            format("\"some text\"", getLLVMStyleWithColumns(10)));
5002  EXPECT_EQ("\"some \"\n"
5003            "\"text\"",
5004            format("\"some text\"", getLLVMStyleWithColumns(7)));
5005  EXPECT_EQ("\"some\"\n"
5006            "\" tex\"\n"
5007            "\"t\"",
5008            format("\"some text\"", getLLVMStyleWithColumns(6)));
5009  EXPECT_EQ("\"some\"\n"
5010            "\" tex\"\n"
5011            "\" and\"",
5012            format("\"some tex and\"", getLLVMStyleWithColumns(6)));
5013  EXPECT_EQ("\"some\"\n"
5014            "\"/tex\"\n"
5015            "\"/and\"",
5016            format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
5017
5018  EXPECT_EQ("variable =\n"
5019            "    \"long string \"\n"
5020            "    \"literal\";",
5021            format("variable = \"long string literal\";",
5022                   getLLVMStyleWithColumns(20)));
5023
5024  EXPECT_EQ("variable = f(\n"
5025            "    \"long string \"\n"
5026            "    \"literal\",\n"
5027            "    short,\n"
5028            "    loooooooooooooooooooong);",
5029            format("variable = f(\"long string literal\", short, "
5030                   "loooooooooooooooooooong);",
5031                   getLLVMStyleWithColumns(20)));
5032
5033  EXPECT_EQ("f(g(\"long string \"\n"
5034            "    \"literal\"),\n"
5035            "  b);",
5036            format("f(g(\"long string literal\"), b);",
5037                   getLLVMStyleWithColumns(20)));
5038  EXPECT_EQ("f(g(\"long string \"\n"
5039            "    \"literal\",\n"
5040            "    a),\n"
5041            "  b);",
5042            format("f(g(\"long string literal\", a), b);",
5043                   getLLVMStyleWithColumns(20)));
5044  EXPECT_EQ(
5045      "f(\"one two\".split(\n"
5046      "    variable));",
5047      format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
5048  EXPECT_EQ("f(\"one two three four five six \"\n"
5049            "  \"seven\".split(\n"
5050            "      really_looooong_variable));",
5051            format("f(\"one two three four five six seven\"."
5052                   "split(really_looooong_variable));",
5053                   getLLVMStyleWithColumns(33)));
5054
5055  EXPECT_EQ("f(\"some \"\n"
5056            "  \"text\",\n"
5057            "  other);",
5058            format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
5059
5060  // Only break as a last resort.
5061  verifyFormat(
5062      "aaaaaaaaaaaaaaaaaaaa(\n"
5063      "    aaaaaaaaaaaaaaaaaaaa,\n"
5064      "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
5065
5066  EXPECT_EQ(
5067      "\"splitmea\"\n"
5068      "\"trandomp\"\n"
5069      "\"oint\"",
5070      format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
5071
5072  EXPECT_EQ(
5073      "\"split/\"\n"
5074      "\"pathat/\"\n"
5075      "\"slashes\"",
5076      format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
5077
5078  EXPECT_EQ(
5079      "\"split/\"\n"
5080      "\"pathat/\"\n"
5081      "\"slashes\"",
5082      format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
5083  EXPECT_EQ("\"split at \"\n"
5084            "\"spaces/at/\"\n"
5085            "\"slashes.at.any$\"\n"
5086            "\"non-alphanumeric%\"\n"
5087            "\"1111111111characte\"\n"
5088            "\"rs\"",
5089            format("\"split at "
5090                   "spaces/at/"
5091                   "slashes.at."
5092                   "any$non-"
5093                   "alphanumeric%"
5094                   "1111111111characte"
5095                   "rs\"",
5096                   getLLVMStyleWithColumns(20)));
5097
5098  // Verify that splitting the strings understands
5099  // Style::AlwaysBreakBeforeMultilineStrings.
5100  EXPECT_EQ("aaaaaaaaaaaa(aaaaaaaaaaaaa,\n"
5101            "             \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
5102            "             \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
5103            format("aaaaaaaaaaaa(aaaaaaaaaaaaa, \"aaaaaaaaaaaaaaaaaaaaaa "
5104                   "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa "
5105                   "aaaaaaaaaaaaaaaaaaaaaa\");",
5106                   getGoogleStyle()));
5107
5108  FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
5109  AlignLeft.AlignEscapedNewlinesLeft = true;
5110  EXPECT_EQ(
5111      "#define A \\\n"
5112      "  \"some \" \\\n"
5113      "  \"text \" \\\n"
5114      "  \"other\";",
5115      format("#define A \"some text other\";", AlignLeft));
5116}
5117
5118TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
5119  EXPECT_EQ("aaaaaaaaaaa =\n"
5120            "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
5121            "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
5122            "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
5123            format("aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
5124                   "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
5125                   "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
5126}
5127
5128TEST_F(FormatTest, SkipsUnknownStringLiterals) {
5129  EXPECT_EQ(
5130      "u8\"unsupported literal\";",
5131      format("u8\"unsupported literal\";", getGoogleStyleWithColumns(15)));
5132  EXPECT_EQ("u\"unsupported literal\";",
5133            format("u\"unsupported literal\";", getGoogleStyleWithColumns(15)));
5134  EXPECT_EQ("U\"unsupported literal\";",
5135            format("U\"unsupported literal\";", getGoogleStyleWithColumns(15)));
5136  EXPECT_EQ("L\"unsupported literal\";",
5137            format("L\"unsupported literal\";", getGoogleStyleWithColumns(15)));
5138  EXPECT_EQ("R\"x(raw literal)x\";",
5139            format("R\"x(raw literal)x\";", getGoogleStyleWithColumns(15)));
5140  verifyFormat("string a = \"unterminated;");
5141  EXPECT_EQ("function(\"unterminated,\n"
5142            "         OtherParameter);",
5143            format("function(  \"unterminated,\n"
5144                   "    OtherParameter);"));
5145}
5146
5147TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
5148  EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
5149            format("#define x(_a) printf(\"foo\"_a);", getLLVMStyle()));
5150}
5151
5152TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
5153  EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
5154            "             \"ddeeefff\");",
5155            format("someFunction(\"aaabbbcccdddeeefff\");",
5156                   getLLVMStyleWithColumns(25)));
5157  EXPECT_EQ("someFunction1234567890(\n"
5158            "    \"aaabbbcccdddeeefff\");",
5159            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
5160                   getLLVMStyleWithColumns(26)));
5161  EXPECT_EQ("someFunction1234567890(\n"
5162            "    \"aaabbbcccdddeeeff\"\n"
5163            "    \"f\");",
5164            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
5165                   getLLVMStyleWithColumns(25)));
5166  EXPECT_EQ("someFunction1234567890(\n"
5167            "    \"aaabbbcccdddeeeff\"\n"
5168            "    \"f\");",
5169            format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
5170                   getLLVMStyleWithColumns(24)));
5171  EXPECT_EQ("someFunction(\n"
5172            "    \"aaabbbcc \"\n"
5173            "    \"dddeeefff\");",
5174            format("someFunction(\"aaabbbcc dddeeefff\");",
5175                   getLLVMStyleWithColumns(25)));
5176  EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
5177            "             \"ddeeefff\");",
5178            format("someFunction(\"aaabbbccc ddeeefff\");",
5179                   getLLVMStyleWithColumns(25)));
5180  EXPECT_EQ("someFunction1234567890(\n"
5181            "    \"aaabb \"\n"
5182            "    \"cccdddeeefff\");",
5183            format("someFunction1234567890(\"aaabb cccdddeeefff\");",
5184                   getLLVMStyleWithColumns(25)));
5185  EXPECT_EQ("#define A          \\\n"
5186            "  string s =       \\\n"
5187            "      \"123456789\"  \\\n"
5188            "      \"0\";         \\\n"
5189            "  int i;",
5190            format("#define A string s = \"1234567890\"; int i;",
5191                   getLLVMStyleWithColumns(20)));
5192}
5193
5194TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
5195  EXPECT_EQ("\"\\a\"",
5196            format("\"\\a\"", getLLVMStyleWithColumns(3)));
5197  EXPECT_EQ("\"\\\"",
5198            format("\"\\\"", getLLVMStyleWithColumns(2)));
5199  EXPECT_EQ("\"test\"\n"
5200            "\"\\n\"",
5201            format("\"test\\n\"", getLLVMStyleWithColumns(7)));
5202  EXPECT_EQ("\"tes\\\\\"\n"
5203            "\"n\"",
5204            format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
5205  EXPECT_EQ("\"\\\\\\\\\"\n"
5206            "\"\\n\"",
5207            format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
5208  EXPECT_EQ("\"\\uff01\"",
5209            format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
5210  EXPECT_EQ("\"\\uff01\"\n"
5211            "\"test\"",
5212            format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
5213  EXPECT_EQ("\"\\Uff01ff02\"",
5214            format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
5215  EXPECT_EQ("\"\\x000000000001\"\n"
5216            "\"next\"",
5217            format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
5218  EXPECT_EQ("\"\\x000000000001next\"",
5219            format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
5220  EXPECT_EQ("\"\\x000000000001\"",
5221            format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
5222  EXPECT_EQ("\"test\"\n"
5223            "\"\\000000\"\n"
5224            "\"000001\"",
5225            format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
5226  EXPECT_EQ("\"test\\000\"\n"
5227            "\"00000000\"\n"
5228            "\"1\"",
5229            format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
5230  EXPECT_EQ("R\"(\\x\\x00)\"\n",
5231            format("R\"(\\x\\x00)\"\n", getGoogleStyleWithColumns(7)));
5232}
5233
5234TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
5235  verifyFormat("void f() {\n"
5236               "  return g() {}\n"
5237               "  void h() {}");
5238  verifyFormat("if (foo)\n"
5239               "  return { forgot_closing_brace();\n"
5240               "test();");
5241  verifyFormat("int a[] = { void forgot_closing_brace() { f();\n"
5242               "g();\n"
5243               "}");
5244}
5245
5246TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
5247  verifyFormat("class X {\n"
5248               "  void f() {\n"
5249               "  }\n"
5250               "};",
5251               getLLVMStyleWithColumns(12));
5252}
5253
5254TEST_F(FormatTest, ConfigurableIndentWidth) {
5255  FormatStyle EightIndent = getLLVMStyleWithColumns(18);
5256  EightIndent.IndentWidth = 8;
5257  verifyFormat("void f() {\n"
5258               "        someFunction();\n"
5259               "        if (true) {\n"
5260               "                f();\n"
5261               "        }\n"
5262               "}",
5263               EightIndent);
5264  verifyFormat("class X {\n"
5265               "        void f() {\n"
5266               "        }\n"
5267               "};",
5268               EightIndent);
5269  verifyFormat("int x[] = {\n"
5270               "        call(),\n"
5271               "        call(),\n"
5272               "};",
5273               EightIndent);
5274}
5275
5276TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
5277  verifyFormat("void\n"
5278               "f();",
5279               getLLVMStyleWithColumns(8));
5280}
5281
5282TEST_F(FormatTest, ConfigurableUseOfTab) {
5283  FormatStyle Tab = getLLVMStyleWithColumns(42);
5284  Tab.IndentWidth = 8;
5285  Tab.UseTab = true;
5286  Tab.AlignEscapedNewlinesLeft = true;
5287  verifyFormat("class X {\n"
5288               "\tvoid f() {\n"
5289               "\t\tsomeFunction(parameter1,\n"
5290               "\t\t\t     parameter2);\n"
5291               "\t}\n"
5292               "};",
5293               Tab);
5294  verifyFormat("#define A                        \\\n"
5295               "\tvoid f() {               \\\n"
5296               "\t\tsomeFunction(    \\\n"
5297               "\t\t    parameter1,  \\\n"
5298               "\t\t    parameter2); \\\n"
5299               "\t}",
5300               Tab);
5301
5302
5303  // FIXME: To correctly count mixed whitespace we need to
5304  // also correctly count mixed whitespace in front of the comment.
5305  //
5306  // EXPECT_EQ("/*\n"
5307  //           "\t      a\t\tcomment\n"
5308  //           "\t      in multiple lines\n"
5309  //           "       */",
5310  //           format("   /*\t \t \n"
5311  //                  " \t \t a\t\tcomment\t \t\n"
5312  //                  " \t \t in multiple lines\t\n"
5313  //                  " \t  */",
5314  //                  Tab));
5315  // Tab.UseTab = false;
5316  // EXPECT_EQ("/*\n"
5317  //           "              a\t\tcomment\n"
5318  //           "              in multiple lines\n"
5319  //           "       */",
5320  //           format("   /*\t \t \n"
5321  //                  " \t \t a\t\tcomment\t \t\n"
5322  //                  " \t \t in multiple lines\t\n"
5323  //                  " \t  */",
5324  //                  Tab));
5325  // EXPECT_EQ("/* some\n"
5326  //           "   comment */",
5327  //          format(" \t \t /* some\n"
5328  //                 " \t \t    comment */",
5329  //                 Tab));
5330
5331  EXPECT_EQ("{\n"
5332            "  /*\n"
5333            "   * Comment\n"
5334            "   */\n"
5335            "  int i;\n"
5336            "}",
5337            format("{\n"
5338                   "\t/*\n"
5339                   "\t * Comment\n"
5340                   "\t */\n"
5341                   "\t int i;\n"
5342                   "}"));
5343}
5344
5345TEST_F(FormatTest, LinuxBraceBreaking) {
5346  FormatStyle BreakBeforeBrace = getLLVMStyle();
5347  BreakBeforeBrace.BreakBeforeBraces = FormatStyle::BS_Linux;
5348  verifyFormat("namespace a\n"
5349               "{\n"
5350               "class A\n"
5351               "{\n"
5352               "  void f()\n"
5353               "  {\n"
5354               "    if (true) {\n"
5355               "      a();\n"
5356               "      b();\n"
5357               "    }\n"
5358               "  }\n"
5359               "  void g()\n"
5360               "  {\n"
5361               "    return;\n"
5362               "  }\n"
5363               "}\n"
5364               "}",
5365               BreakBeforeBrace);
5366}
5367
5368TEST_F(FormatTest, StroustrupBraceBreaking) {
5369  FormatStyle BreakBeforeBrace = getLLVMStyle();
5370  BreakBeforeBrace.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
5371  verifyFormat("namespace a {\n"
5372               "class A {\n"
5373               "  void f()\n"
5374               "  {\n"
5375               "    if (true) {\n"
5376               "      a();\n"
5377               "      b();\n"
5378               "    }\n"
5379               "  }\n"
5380               "  void g()\n"
5381               "  {\n"
5382               "    return;\n"
5383               "  }\n"
5384               "}\n"
5385               "}",
5386               BreakBeforeBrace);
5387}
5388
5389bool allStylesEqual(ArrayRef<FormatStyle> Styles) {
5390  for (size_t i = 1; i < Styles.size(); ++i)
5391    if (!(Styles[0] == Styles[i]))
5392      return false;
5393  return true;
5394}
5395
5396TEST_F(FormatTest, GetsPredefinedStyleByName) {
5397  FormatStyle Styles[3];
5398
5399  Styles[0] = getLLVMStyle();
5400  EXPECT_TRUE(getPredefinedStyle("LLVM", &Styles[1]));
5401  EXPECT_TRUE(getPredefinedStyle("lLvM", &Styles[2]));
5402  EXPECT_TRUE(allStylesEqual(Styles));
5403
5404  Styles[0] = getGoogleStyle();
5405  EXPECT_TRUE(getPredefinedStyle("Google", &Styles[1]));
5406  EXPECT_TRUE(getPredefinedStyle("gOOgle", &Styles[2]));
5407  EXPECT_TRUE(allStylesEqual(Styles));
5408
5409  Styles[0] = getChromiumStyle();
5410  EXPECT_TRUE(getPredefinedStyle("Chromium", &Styles[1]));
5411  EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", &Styles[2]));
5412  EXPECT_TRUE(allStylesEqual(Styles));
5413
5414  Styles[0] = getMozillaStyle();
5415  EXPECT_TRUE(getPredefinedStyle("Mozilla", &Styles[1]));
5416  EXPECT_TRUE(getPredefinedStyle("moZILla", &Styles[2]));
5417  EXPECT_TRUE(allStylesEqual(Styles));
5418
5419  Styles[0] = getWebKitStyle();
5420  EXPECT_TRUE(getPredefinedStyle("WebKit", &Styles[1]));
5421  EXPECT_TRUE(getPredefinedStyle("wEbKit", &Styles[2]));
5422  EXPECT_TRUE(allStylesEqual(Styles));
5423
5424  EXPECT_FALSE(getPredefinedStyle("qwerty", &Styles[0]));
5425}
5426
5427TEST_F(FormatTest, ParsesConfiguration) {
5428  FormatStyle Style = {};
5429#define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
5430  EXPECT_NE(VALUE, Style.FIELD);                                               \
5431  EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
5432  EXPECT_EQ(VALUE, Style.FIELD)
5433
5434#define CHECK_PARSE_BOOL(FIELD)                                                \
5435  Style.FIELD = false;                                                         \
5436  EXPECT_EQ(0, parseConfiguration(#FIELD ": true", &Style).value());           \
5437  EXPECT_TRUE(Style.FIELD);                                                    \
5438  EXPECT_EQ(0, parseConfiguration(#FIELD ": false", &Style).value());          \
5439  EXPECT_FALSE(Style.FIELD);
5440
5441  CHECK_PARSE_BOOL(AlignEscapedNewlinesLeft);
5442  CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
5443  CHECK_PARSE_BOOL(AllowShortIfStatementsOnASingleLine);
5444  CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
5445  CHECK_PARSE_BOOL(AlwaysBreakTemplateDeclarations);
5446  CHECK_PARSE_BOOL(BinPackParameters);
5447  CHECK_PARSE_BOOL(BreakBeforeBinaryOperators);
5448  CHECK_PARSE_BOOL(BreakConstructorInitializersBeforeComma);
5449  CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
5450  CHECK_PARSE_BOOL(DerivePointerBinding);
5451  CHECK_PARSE_BOOL(IndentCaseLabels);
5452  CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
5453  CHECK_PARSE_BOOL(PointerBindsToType);
5454  CHECK_PARSE_BOOL(Cpp11BracedListStyle);
5455  CHECK_PARSE_BOOL(UseTab);
5456  CHECK_PARSE_BOOL(IndentFunctionDeclarationAfterType);
5457
5458  CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
5459  CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
5460  CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
5461  CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
5462  CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
5463              PenaltyReturnTypeOnItsOwnLine, 1234u);
5464  CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
5465              SpacesBeforeTrailingComments, 1234u);
5466  CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
5467
5468  Style.Standard = FormatStyle::LS_Auto;
5469  CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
5470  CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
5471  CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
5472
5473  Style.ColumnLimit = 123;
5474  FormatStyle BaseStyle = getLLVMStyle();
5475  CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
5476  CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
5477
5478  Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
5479  CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
5480              FormatStyle::BS_Attach);
5481  CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
5482              FormatStyle::BS_Linux);
5483  CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
5484              FormatStyle::BS_Stroustrup);
5485
5486#undef CHECK_PARSE
5487#undef CHECK_PARSE_BOOL
5488}
5489
5490TEST_F(FormatTest, ConfigurationRoundTripTest) {
5491  FormatStyle Style = getLLVMStyle();
5492  std::string YAML = configurationAsText(Style);
5493  FormatStyle ParsedStyle = {};
5494  EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
5495  EXPECT_EQ(Style, ParsedStyle);
5496}
5497
5498TEST_F(FormatTest, WorksFor8bitEncodings) {
5499  EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
5500            "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
5501            "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
5502            "\"\xef\xee\xf0\xf3...\"",
5503            format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
5504                   "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
5505                   "\xef\xee\xf0\xf3...\"",
5506                   getLLVMStyleWithColumns(12)));
5507}
5508
5509// FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
5510#if !defined(_MSC_VER)
5511
5512TEST_F(FormatTest, CountsUTF8CharactersProperly) {
5513  verifyFormat("\"Однажды в студёную зимнюю пору...\"",
5514               getLLVMStyleWithColumns(35));
5515  verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
5516               getLLVMStyleWithColumns(21));
5517  verifyFormat("// Однажды в студёную зимнюю пору...",
5518               getLLVMStyleWithColumns(36));
5519  verifyFormat("// 一 二 三 四 五 六 七 八 九 十",
5520               getLLVMStyleWithColumns(22));
5521  verifyFormat("/* Однажды в студёную зимнюю пору... */",
5522               getLLVMStyleWithColumns(39));
5523  verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
5524               getLLVMStyleWithColumns(25));
5525}
5526
5527TEST_F(FormatTest, SplitsUTF8Strings) {
5528  EXPECT_EQ(
5529      "\"Однажды, в \"\n"
5530      "\"студёную \"\n"
5531      "\"зимнюю \"\n"
5532      "\"пору,\"",
5533      format("\"Однажды, в студёную зимнюю пору,\"",
5534             getLLVMStyleWithColumns(13)));
5535  EXPECT_EQ("\"一 二 三 四 \"\n"
5536            "\"五 六 七 八 \"\n"
5537            "\"九 十\"",
5538            format("\"一 二 三 四 五 六 七 八 九 十\"",
5539                   getLLVMStyleWithColumns(10)));
5540}
5541
5542TEST_F(FormatTest, SplitsUTF8LineComments) {
5543  EXPECT_EQ("// Я из лесу\n"
5544            "// вышел; был\n"
5545            "// сильный\n"
5546            "// мороз.",
5547            format("// Я из лесу вышел; был сильный мороз.",
5548                   getLLVMStyleWithColumns(13)));
5549  EXPECT_EQ("// 一二三\n"
5550            "// 四五六七\n"
5551            "// 八\n"
5552            "// 九 十",
5553            format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(6)));
5554}
5555
5556TEST_F(FormatTest, SplitsUTF8BlockComments) {
5557  EXPECT_EQ("/* Гляжу,\n"
5558            " * поднимается\n"
5559            " * медленно в\n"
5560            " * гору\n"
5561            " * Лошадка,\n"
5562            " * везущая\n"
5563            " * хворосту\n"
5564            " * воз. */",
5565            format("/* Гляжу, поднимается медленно в гору\n"
5566                   " * Лошадка, везущая хворосту воз. */",
5567                   getLLVMStyleWithColumns(13)));
5568  EXPECT_EQ("/* 一二三\n"
5569            " * 四五六七\n"
5570            " * 八\n"
5571            " * 九 十\n"
5572            " */",
5573            format("/* 一二三 四五六七 八  九 十 */", getLLVMStyleWithColumns(6)));
5574  EXPECT_EQ("/* �������� ��������\n"
5575            " * ��������\n"
5576            " * ������-�� */",
5577            format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
5578}
5579
5580TEST_F(FormatTest, FormatsWithWebKitStyle) {
5581  FormatStyle Style = getWebKitStyle();
5582
5583  // Don't indent in outer namespaces.
5584  verifyFormat("namespace outer {\n"
5585               "int i;\n"
5586               "namespace inner {\n"
5587               "int i;\n" // FIXME: This should be indented.
5588               "} // namespace inner\n"
5589               "} // namespace outer\n"
5590               "namespace other_outer {\n"
5591               "int i;\n"
5592               "}",
5593               Style);
5594
5595  // Don't indent case labels.
5596  verifyFormat("switch (variable) {\n"
5597               "case 1:\n"
5598               "case 2:\n"
5599               "    doSomething();\n"
5600               "    break;\n"
5601               "default:\n"
5602               "    ++variable;\n"
5603               "}",
5604               Style);
5605
5606  // Wrap before binary operators.
5607  EXPECT_EQ(
5608      "void f()\n"
5609      "{\n"
5610      "    if (aaaaaaaaaaaaaaaa\n"
5611      "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
5612      "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
5613      "        return;\n"
5614      "}",
5615      format(
5616          "void f() {\n"
5617          "if (aaaaaaaaaaaaaaaa\n"
5618          "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
5619          "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
5620          "return;\n"
5621          "}",
5622          Style));
5623
5624  // Constructor initializers are formatted one per line with the "," on the
5625  // new line.
5626  verifyFormat("Constructor()\n"
5627               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5628               "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
5629               "                               aaaaaaaaaaaaaa)\n"
5630               "    , aaaaaaaaaaaaaaaaaaaaaaa()\n{\n}",
5631               Style);
5632
5633  // Do not align comments.
5634  // FIXME: Implement option to suppress comment alignment.
5635  // verifyFormat("int a; // Do not\n"
5636  //              "double b; // align comments.");
5637
5638  // Accept input's line breaks.
5639  EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
5640            "    || bbbbbbbbbbbbbbb) {\n"
5641            "    i++;\n"
5642            "}",
5643            format("if (aaaaaaaaaaaaaaa\n"
5644                   "|| bbbbbbbbbbbbbbb) { i++; }",
5645                   Style));
5646  EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
5647            "    i++;\n"
5648            "}",
5649            format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
5650}
5651
5652#endif
5653
5654} // end namespace tooling
5655} // end namespace clang
5656