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