FormatTest.cpp revision efcfe733970b994b75ba5fc728a97357b3a6a0e1
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#include "clang/Format/Format.h"
11#include "../Tooling/RewriterTestContext.h"
12#include "clang/Lex/Lexer.h"
13#include "gtest/gtest.h"
14
15namespace clang {
16namespace format {
17
18class FormatTest : public ::testing::Test {
19protected:
20  std::string format(llvm::StringRef Code, unsigned Offset, unsigned Length,
21                     const FormatStyle &Style) {
22    RewriterTestContext Context;
23    FileID ID = Context.createInMemoryFile("input.cc", Code);
24    SourceLocation Start =
25        Context.Sources.getLocForStartOfFile(ID).getLocWithOffset(Offset);
26    std::vector<CharSourceRange> Ranges(
27        1,
28        CharSourceRange::getCharRange(Start, Start.getLocWithOffset(Length)));
29    LangOptions LangOpts;
30    LangOpts.CPlusPlus = 1;
31    LangOpts.CPlusPlus11 = 1;
32    LangOpts.ObjC1 = 1;
33    Lexer Lex(ID, Context.Sources.getBuffer(ID), Context.Sources, LangOpts);
34    tooling::Replacements Replace = reformat(Style, Lex, Context.Sources,
35                                             Ranges);
36    EXPECT_TRUE(applyAllReplacements(Replace, Context.Rewrite));
37    return Context.getRewrittenText(ID);
38  }
39
40  std::string format(llvm::StringRef Code,
41                     const FormatStyle &Style = getLLVMStyle()) {
42    return format(Code, 0, Code.size(), Style);
43  }
44
45  std::string messUp(llvm::StringRef Code) {
46    std::string MessedUp(Code.str());
47    bool InComment = false;
48    bool JustReplacedNewline = false;
49    for (unsigned i = 0, e = MessedUp.size() - 1; i != e; ++i) {
50      if (MessedUp[i] == '/' && MessedUp[i + 1] == '/') {
51        if (JustReplacedNewline)
52          MessedUp[i - 1] = '\n';
53        InComment = true;
54      } else if (MessedUp[i] == '\\' && MessedUp[i + 1] == '\n') {
55        MessedUp[i] = ' ';
56      } else if (MessedUp[i] == '\n') {
57        if (InComment) {
58          InComment = false;
59        } else {
60          JustReplacedNewline = true;
61          MessedUp[i] = ' ';
62        }
63      } else if (MessedUp[i] != ' ') {
64        JustReplacedNewline = false;
65      }
66    }
67    return MessedUp;
68  }
69
70  FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
71    FormatStyle Style = getLLVMStyle();
72    Style.ColumnLimit = ColumnLimit;
73    return Style;
74  }
75
76  void verifyFormat(llvm::StringRef Code,
77                    const FormatStyle &Style = getLLVMStyle()) {
78    EXPECT_EQ(Code.str(), format(messUp(Code), Style));
79  }
80
81  void verifyGoogleFormat(llvm::StringRef Code) {
82    verifyFormat(Code, getGoogleStyle());
83  }
84};
85
86//===----------------------------------------------------------------------===//
87// Basic function tests.
88//===----------------------------------------------------------------------===//
89
90TEST_F(FormatTest, DoesNotChangeCorrectlyFormatedCode) {
91  EXPECT_EQ(";", format(";"));
92}
93
94TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
95  EXPECT_EQ("int i;", format("  int i;"));
96  EXPECT_EQ("\nint i;", format(" \n\t \r  int i;"));
97  EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
98  EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
99}
100
101TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
102  EXPECT_EQ("int i;", format("int\ni;"));
103}
104
105TEST_F(FormatTest, FormatsNestedBlockStatements) {
106  EXPECT_EQ("{\n  {\n    {\n    }\n  }\n}", format("{{{}}}"));
107}
108
109TEST_F(FormatTest, FormatsNestedCall) {
110  verifyFormat("Method(f1, f2(f3));");
111  verifyFormat("Method(f1(f2, f3()));");
112}
113
114//===----------------------------------------------------------------------===//
115// Tests for control statements.
116//===----------------------------------------------------------------------===//
117
118TEST_F(FormatTest, FormatIfWithoutCompountStatement) {
119  verifyFormat("if (true)\n  f();\ng();");
120  verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
121  verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
122  verifyFormat("if (a)\n"
123               "  // comment\n"
124               "  f();");
125}
126
127TEST_F(FormatTest, ParseIfElse) {
128  verifyFormat("if (true)\n"
129               "  if (true)\n"
130               "    if (true)\n"
131               "      f();\n"
132               "    else\n"
133               "      g();\n"
134               "  else\n"
135               "    h();\n"
136               "else\n"
137               "  i();");
138  verifyFormat("if (true)\n"
139               "  if (true)\n"
140               "    if (true) {\n"
141               "      if (true)\n"
142               "        f();\n"
143               "    } else {\n"
144               "      g();\n"
145               "    }\n"
146               "  else\n"
147               "    h();\n"
148               "else {\n"
149               "  i();\n"
150               "}");
151}
152
153TEST_F(FormatTest, ElseIf) {
154  verifyFormat("if (a) {\n"
155               "} else if (b) {\n"
156               "}");
157  verifyFormat("if (a)\n"
158               "  f();\n"
159               "else if (b)\n"
160               "  g();\n"
161               "else\n"
162               "  h();");
163}
164
165TEST_F(FormatTest, FormatsForLoop) {
166  verifyFormat(
167      "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
168      "     ++VeryVeryLongLoopVariable)\n"
169      "  ;");
170  verifyFormat("for (;;)\n"
171               "  f();");
172  verifyFormat("for (;;) {\n"
173               "}");
174  verifyFormat("for (;;) {\n"
175               "  f();\n"
176               "}");
177
178  verifyFormat(
179      "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
180      "                                          E = UnwrappedLines.end();\n"
181      "     I != E; ++I) {\n}");
182
183  verifyFormat(
184      "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
185      "     ++IIIII) {\n}");
186}
187
188TEST_F(FormatTest, FormatsWhileLoop) {
189  verifyFormat("while (true) {\n}");
190  verifyFormat("while (true)\n"
191               "  f();");
192  verifyFormat("while () {\n"
193               "}");
194  verifyFormat("while () {\n"
195               "  f();\n"
196               "}");
197}
198
199TEST_F(FormatTest, FormatsDoWhile) {
200  verifyFormat("do {\n"
201               "  do_something();\n"
202               "} while (something());");
203  verifyFormat("do\n"
204               "  do_something();\n"
205               "while (something());");
206}
207
208TEST_F(FormatTest, FormatsSwitchStatement) {
209  verifyFormat("switch (x) {\n"
210               "case 1:\n"
211               "  f();\n"
212               "  break;\n"
213               "case kFoo:\n"
214               "case ns::kBar:\n"
215               "case kBaz:\n"
216               "  break;\n"
217               "default:\n"
218               "  g();\n"
219               "  break;\n"
220               "}");
221  verifyFormat("switch (x) {\n"
222               "case 1: {\n"
223               "  f();\n"
224               "  break;\n"
225               "}\n"
226               "}");
227  verifyFormat("switch (test)\n"
228               "  ;");
229  verifyGoogleFormat("switch (x) {\n"
230                     "  case 1:\n"
231                     "    f();\n"
232                     "    break;\n"
233                     "  case kFoo:\n"
234                     "  case ns::kBar:\n"
235                     "  case kBaz:\n"
236                     "    break;\n"
237                     "  default:\n"
238                     "    g();\n"
239                     "    break;\n"
240                     "}");
241  verifyGoogleFormat("switch (x) {\n"
242                     "  case 1: {\n"
243                     "    f();\n"
244                     "    break;\n"
245                     "  }\n"
246                     "}");
247  verifyGoogleFormat("switch (test)\n"
248                     "    ;");
249}
250
251TEST_F(FormatTest, FormatsLabels) {
252  verifyFormat("void f() {\n"
253               "  some_code();\n"
254               "test_label:\n"
255               "  some_other_code();\n"
256               "  {\n"
257               "    some_more_code();\n"
258               "  another_label:\n"
259               "    some_more_code();\n"
260               "  }\n"
261               "}");
262  verifyFormat("some_code();\n"
263               "test_label:\n"
264               "some_other_code();");
265}
266
267//===----------------------------------------------------------------------===//
268// Tests for comments.
269//===----------------------------------------------------------------------===//
270
271TEST_F(FormatTest, UnderstandsSingleLineComments) {
272  verifyFormat("// line 1\n"
273               "// line 2\n"
274               "void f() {\n}\n");
275
276  verifyFormat("void f() {\n"
277               "  // Doesn't do anything\n"
278               "}");
279
280  verifyFormat("int i // This is a fancy variable\n"
281               "    = 5;");
282
283  verifyFormat("enum E {\n"
284               "  // comment\n"
285               "  VAL_A, // comment\n"
286               "  VAL_B\n"
287               "};");
288
289  verifyFormat(
290      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
291      "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // Trailing comment");
292
293  EXPECT_EQ("int i; // single line trailing comment",
294            format("int i;\\\n// single line trailing comment"));
295
296  verifyGoogleFormat("int a;  // Trailing comment.");
297}
298
299TEST_F(FormatTest, UnderstandsMultiLineComments) {
300  verifyFormat("f(/*test=*/ true);");
301}
302
303//===----------------------------------------------------------------------===//
304// Tests for classes, namespaces, etc.
305//===----------------------------------------------------------------------===//
306
307TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
308  verifyFormat("class A {\n};");
309}
310
311TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
312  verifyFormat("class A {\n"
313               "public:\n"
314               "protected:\n"
315               "private:\n"
316               "  void f() {\n"
317               "  }\n"
318               "};");
319  verifyGoogleFormat("class A {\n"
320                     " public:\n"
321                     " protected:\n"
322                     " private:\n"
323                     "  void f() {\n"
324                     "  }\n"
325                     "};");
326}
327
328TEST_F(FormatTest, FormatsDerivedClass) {
329  verifyFormat("class A : public B {\n"
330               "};");
331  verifyFormat("class A : public ::B {\n"
332               "};");
333}
334
335TEST_F(FormatTest, FormatsEnum) {
336  verifyFormat("enum {\n"
337               "  Zero,\n"
338               "  One = 1,\n"
339               "  Two = One + 1,\n"
340               "  Three = (One + Two),\n"
341               "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
342               "  Five = (One, Two, Three, Four, 5)\n"
343               "};");
344  verifyFormat("enum Enum {\n"
345               "};");
346  verifyFormat("enum {\n"
347               "};");
348}
349
350TEST_F(FormatTest, FormatsNamespaces) {
351  verifyFormat("namespace some_namespace {\n"
352               "class A {\n"
353               "};\n"
354               "void f() {\n"
355               "  f();\n"
356               "}\n"
357               "}");
358  verifyFormat("namespace {\n"
359               "class A {\n"
360               "};\n"
361               "void f() {\n"
362               "  f();\n"
363               "}\n"
364               "}");
365  verifyFormat("inline namespace X {\n"
366               "class A {\n"
367               "};\n"
368               "void f() {\n"
369               "  f();\n"
370               "}\n"
371               "}");
372  verifyFormat("using namespace some_namespace;\n"
373               "class A {\n"
374               "};\n"
375               "void f() {\n"
376               "  f();\n"
377               "}");
378}
379
380TEST_F(FormatTest, StaticInitializers) {
381  verifyFormat("static SomeClass SC = { 1, 'a' };");
382
383  // FIXME: Format like enums if the static initializer does not fit on a line.
384  verifyFormat(
385      "static SomeClass WithALoooooooooooooooooooongName = {\n"
386      "  100000000, \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" };");
387}
388
389TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
390  verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
391               "                      \\\n"
392               "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
393}
394
395TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
396  verifyFormat("virtual void write(ELFWriter *writerrr,\n"
397               "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
398}
399
400TEST_F(FormatTest, BreaksOnHashWhenDirectiveIsInvalid) {
401  EXPECT_EQ("#\n;", format("#;"));
402  verifyFormat("#\n;\n;\n;");
403}
404
405TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
406  EXPECT_EQ("#line 42 \"test\"\n",
407            format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
408  EXPECT_EQ("#define A  \\\n  B\n",
409            format("#  \\\n define  \\\n    A  \\\n       B\n",
410                   getLLVMStyleWithColumns(12)));
411}
412
413TEST_F(FormatTest, EndOfFileEndsPPDirective) {
414  EXPECT_EQ("#line 42 \"test\"",
415            format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
416  EXPECT_EQ("#define A  \\\n  B",
417            format("#  \\\n define  \\\n    A  \\\n       B",
418                   getLLVMStyleWithColumns(12)));
419}
420
421TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
422  // If the macro fits in one line, we still do not get the full
423  // line, as only the next line decides whether we need an escaped newline and
424  // thus use the last column.
425  verifyFormat("#define A(B)", getLLVMStyleWithColumns(13));
426
427  verifyFormat("#define A( \\\n    B)", getLLVMStyleWithColumns(12));
428  verifyFormat("#define AA(\\\n    B)", getLLVMStyleWithColumns(12));
429  verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
430}
431
432TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
433  EXPECT_EQ("// some comment\n"
434            "#include \"a.h\"\n"
435            "#define A(A,\\\n"
436            "          B)\n"
437            "#include \"b.h\"\n"
438            "// some comment\n",
439            format("  // some comment\n"
440                   "  #include \"a.h\"\n"
441                   "#define A(A,\\\n"
442                   "    B)\n"
443                   "    #include \"b.h\"\n"
444                   " // some comment\n", getLLVMStyleWithColumns(13)));
445}
446
447TEST_F(FormatTest, LayoutSingleHash) {
448  EXPECT_EQ("#\na;", format("#\na;"));
449}
450
451TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
452  EXPECT_EQ("#define A    \\\n"
453            "  c;         \\\n"
454            "  e;\n"
455            "f;", format("#define A c; e;\n"
456                         "f;", getLLVMStyleWithColumns(14)));
457}
458
459TEST_F(FormatTest, LayoutRemainingTokens) {
460  EXPECT_EQ("{\n}", format("{}"));
461}
462
463TEST_F(FormatTest, LayoutSingleUnwrappedLineInMacro) {
464  EXPECT_EQ("#define A \\\n  b;",
465            format("#define A b;", 10, 2, getLLVMStyleWithColumns(11)));
466}
467
468TEST_F(FormatTest, MacroDefinitionInsideStatement) {
469  EXPECT_EQ("int x,\n#define A\ny;", format("int x,\n#define A\ny;"));
470}
471
472TEST_F(FormatTest, HashInMacroDefinition) {
473  verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
474  verifyFormat("#define A \\\n"
475               "  {       \\\n"
476               "    f(#c);\\\n"
477               "  }", getLLVMStyleWithColumns(11));
478}
479
480TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
481  EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
482}
483
484TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
485  verifyFormat("{\n  {\n    a #c;\n  }\n}");
486}
487
488TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
489  EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
490            format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
491  EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
492            format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
493}
494
495TEST_F(FormatTest, EscapedNewlineAtStartOfTokenInMacroDefinition) {
496  EXPECT_EQ(
497      "#define A \\\n  int i;  \\\n  int j;",
498      format("#define A \\\nint i;\\\n  int j;", getLLVMStyleWithColumns(11)));
499}
500
501TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
502  verifyFormat("#define A \\\n"
503               "  int v(  \\\n"
504               "      a); \\\n"
505               "  int i;", getLLVMStyleWithColumns(11));
506}
507
508TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
509  EXPECT_EQ(
510      "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
511      "                      \\\n"
512      "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
513      "\n"
514      "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
515      "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
516      format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
517             "\\\n"
518             "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
519             "  \n"
520             "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
521             "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
522}
523
524//===----------------------------------------------------------------------===//
525// Line break tests.
526//===----------------------------------------------------------------------===//
527
528TEST_F(FormatTest, FormatsFunctionDefinition) {
529  verifyFormat("void f(int a, int b, int c, int d, int e, int f, int g,"
530               " int h, int j, int f,\n"
531               "       int c, int ddddddddddddd) {\n"
532               "}");
533}
534
535TEST_F(FormatTest, FormatsAwesomeMethodCall) {
536  verifyFormat(
537      "SomeLongMethodName(SomeReallyLongMethod(\n"
538      "    CallOtherReallyLongMethod(parameter, parameter, parameter)),\n"
539      "                   SecondLongCall(parameter));");
540}
541
542TEST_F(FormatTest, ConstructorInitializers) {
543  verifyFormat("Constructor() : Initializer(FitsOnTheLine) {\n}");
544
545  verifyFormat(
546      "SomeClass::Constructor()\n"
547      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {\n"
548      "}");
549
550  verifyFormat(
551      "SomeClass::Constructor()\n"
552      "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
553      "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {\n"
554      "}");
555
556  verifyFormat("Constructor()\n"
557               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
558               "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
559               "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
560               "      aaaaaaaaaaaaaaaaaaaaaaa() {\n"
561               "}");
562
563  // Here a line could be saved by splitting the second initializer onto two
564  // lines, but that is not desireable.
565  verifyFormat("Constructor()\n"
566               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
567               "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
568               "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
569               "}");
570
571  verifyGoogleFormat("MyClass::MyClass(int var)\n"
572                     "    : some_var_(var),  // 4 space indent\n"
573                     "      some_other_var_(var + 1) {  // lined up\n"
574                     "}");
575}
576
577TEST_F(FormatTest, BreaksAsHighAsPossible) {
578  verifyFormat(
579      "if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
580      "    (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
581      "  f();");
582}
583
584TEST_F(FormatTest, BreaksDesireably) {
585  verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
586               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
587               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n};");
588
589  verifyFormat(
590      "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
591      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
592
593  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
594               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
595               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
596
597  verifyFormat(
598      "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
599      "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
600      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
601      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
602
603  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
604               "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
605
606  verifyFormat(
607      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
608      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
609
610  // This test case breaks on an incorrect memoization, i.e. an optimization not
611  // taking into account the StopAt value.
612  verifyFormat(
613      "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
614      "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
615      "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
616      "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
617
618  verifyFormat("{\n  {\n    {\n"
619               "      Annotation.SpaceRequiredBefore =\n"
620               "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
621               "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
622               "    }\n  }\n}");
623}
624
625TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
626  verifyFormat(
627      "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
628      "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
629  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
630               "    ccccccccccccccccccccccccc) {\n}");
631  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
632               "    ccccccccccccccccccccccccc) {\n}");
633  verifyFormat(
634      "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
635      "    ccccccccccccccccccccccccc) {\n}");
636}
637
638TEST_F(FormatTest, PrefersNotToBreakAfterAssignments) {
639  verifyFormat(
640      "unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,\n"
641      "                                    SI->getAlignment(),\n"
642      "                                    SI->getPointerAddressSpaceee());\n");
643  verifyFormat(
644      "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
645      "                                Line.Tokens.front().Tok.getLocation(),\n"
646      "                                Line.Tokens.back().Tok.getLocation());");
647}
648
649TEST_F(FormatTest, AlignsAfterAssignments) {
650  verifyFormat(
651      "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
652      "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
653  verifyFormat(
654      "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
655      "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
656  verifyFormat(
657      "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
658      "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
659  verifyFormat(
660      "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
661      "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
662  verifyFormat(
663      "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
664      "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
665      "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
666}
667
668TEST_F(FormatTest, AlignsAfterReturn) {
669  verifyFormat(
670      "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
671      "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
672  verifyFormat(
673      "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
674      "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
675}
676
677TEST_F(FormatTest, AlignsStringLiterals) {
678  verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
679               "                                      \"short literal\");");
680  verifyFormat(
681      "looooooooooooooooooooooooongFunction(\n"
682      "    \"short literal\"\n"
683      "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
684}
685
686TEST_F(FormatTest, AlignsPipes) {
687  verifyFormat(
688      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
689      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
690      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
691  verifyFormat(
692      "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
693      "                     << aaaaaaaaaaaaaaaaaaaa;");
694  verifyFormat(
695      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
696      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
697  verifyFormat(
698      "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
699      "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
700      "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
701  verifyFormat(
702      "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
703      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
704      "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
705}
706
707TEST_F(FormatTest, UnderstandsEquals) {
708  verifyFormat(
709      "aaaaaaaaaaaaaaaaa =\n"
710      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
711  verifyFormat(
712      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
713      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
714      "}");
715  verifyFormat(
716      "if (a) {\n"
717      "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
718      "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
719      "}");
720
721  verifyFormat(
722      "if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 100000000 +\n"
723      "                                                           10000000) {\n"
724      "}");
725}
726
727TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
728  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
729               "    .looooooooooooooooooooooooooooooooooooooongFunction();");
730
731  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
732               "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
733
734  verifyFormat(
735      "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
736      "                                                          Parameter2);");
737
738  verifyFormat(
739      "ShortObject->shortFunction(\n"
740      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
741      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
742
743  verifyFormat("loooooooooooooongFunction(\n"
744               "    LoooooooooooooongObject->looooooooooooooooongFunction());");
745
746  verifyFormat(
747      "function(LoooooooooooooooooooooooooooooooooooongObject\n"
748      "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
749
750  // Here, it is not necessary to wrap at "." or "->".
751  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
752               "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
753               "}");
754  verifyFormat(
755      "aaaaaaaaaaa->aaaaaaaaa(\n"
756      "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
757      "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
758}
759
760TEST_F(FormatTest, WrapsTemplateDeclarations) {
761  verifyFormat("template <typename T>\n"
762               "virtual void loooooooooooongFunction(int Param1, int Param2);");
763  verifyFormat(
764      "template <typename T> void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
765      "                             int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
766  verifyFormat(
767      "template <typename T>\n"
768      "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
769      "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
770  verifyFormat(
771      "template <typename T>\n"
772      "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
773      "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
774      "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
775
776}
777
778TEST_F(FormatTest, UnderstandsTemplateParameters) {
779  verifyFormat("A<int> a;");
780  verifyFormat("A<A<A<int> > > a;");
781  verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
782  verifyFormat("bool x = a < 1 || 2 > a;");
783  verifyFormat("bool x = 5 < f<int>();");
784  verifyFormat("bool x = f<int>() > 5;");
785  verifyFormat("bool x = 5 < a<int>::x;");
786  verifyFormat("bool x = a < 4 ? a > 2 : false;");
787  verifyFormat("bool x = f() ? a < 2 : a > 2;");
788
789  verifyGoogleFormat("A<A<int>> a;");
790  verifyGoogleFormat("A<A<A<int>>> a;");
791  verifyGoogleFormat("A<A<A<A<int>>>> a;");
792
793  verifyFormat("test >> a >> b;");
794  verifyFormat("test << a >> b;");
795
796  verifyFormat("f<int>();");
797  verifyFormat("template <typename T> void f() {\n}");
798}
799
800TEST_F(FormatTest, UnderstandsUnaryOperators) {
801  verifyFormat("int a = -2;");
802  verifyFormat("f(-1, -2, -3);");
803  verifyFormat("a[-1] = 5;");
804  verifyFormat("int a = 5 + -2;");
805  verifyFormat("if (i == -1) {\n}");
806  verifyFormat("if (i != -1) {\n}");
807  verifyFormat("if (i > -1) {\n}");
808  verifyFormat("if (i < -1) {\n}");
809  verifyFormat("++(a->f());");
810  verifyFormat("--(a->f());");
811  verifyFormat("if (!(a->f())) {\n}");
812
813  verifyFormat("a-- > b;");
814  verifyFormat("b ? -a : c;");
815  verifyFormat("n * sizeof char16;");
816  verifyFormat("n * alignof char16;");
817  verifyFormat("sizeof(char);");
818  verifyFormat("alignof(char);");
819
820  verifyFormat("return -1;");
821  verifyFormat("switch (a) {\n"
822               "case -1:\n"
823               "  break;\n"
824               "}");
825}
826
827TEST_F(FormatTest, UndestandsOverloadedOperators) {
828  verifyFormat("bool operator<();");
829  verifyFormat("bool operator>();");
830  verifyFormat("bool operator=();");
831  verifyFormat("bool operator==();");
832  verifyFormat("bool operator!=();");
833  verifyFormat("int operator+();");
834  verifyFormat("int operator++();");
835  verifyFormat("bool operator();");
836  verifyFormat("bool operator()();");
837  verifyFormat("bool operator[]();");
838  verifyFormat("operator bool();");
839  verifyFormat("operator SomeType<int>();");
840  verifyFormat("void *operator new(std::size_t size);");
841  verifyFormat("void *operator new[](std::size_t size);");
842  verifyFormat("void operator delete(void *ptr);");
843  verifyFormat("void operator delete[](void *ptr);");
844}
845
846TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
847  verifyFormat("int *f(int *a) {\n}");
848  verifyFormat("f(a, *a);");
849  verifyFormat("f(*a);");
850  verifyFormat("int a = b * 10;");
851  verifyFormat("int a = 10 * b;");
852  verifyFormat("int a = b * c;");
853  verifyFormat("int a += b * c;");
854  verifyFormat("int a -= b * c;");
855  verifyFormat("int a *= b * c;");
856  verifyFormat("int a /= b * c;");
857  verifyFormat("int a = *b;");
858  verifyFormat("int a = *b * c;");
859  verifyFormat("int a = b * *c;");
860  verifyFormat("int main(int argc, char **argv) {\n}");
861  verifyFormat("return 10 * b;");
862  verifyFormat("return *b * *c;");
863  verifyFormat("return a & ~b;");
864  verifyFormat("f(b ? *c : *d);");
865  verifyFormat("int a = b ? *c : *d;");
866  verifyFormat("*b = a;");
867  verifyFormat("a * ~b;");
868  verifyFormat("a * !b;");
869  verifyFormat("a * +b;");
870  verifyFormat("a * -b;");
871  verifyFormat("a * ++b;");
872  verifyFormat("a * --b;");
873
874  verifyFormat("InvalidRegions[*R] = 0;");
875
876  // FIXME: Is this desired for LLVM? Fix if not.
877  verifyFormat("A<int *> a;");
878  verifyFormat("A<int **> a;");
879  verifyFormat("A<int *, int *> a;");
880  verifyFormat("A<int **, int **> a;");
881  verifyFormat("Type *A = static_cast<Type *>(P);");
882  verifyFormat("Type *A = (Type *) P;");
883  verifyFormat("Type *A = (vector<Type *, int *>) P;");
884
885  verifyGoogleFormat("int main(int argc, char** argv) {\n}");
886  verifyGoogleFormat("A<int*> a;");
887  verifyGoogleFormat("A<int**> a;");
888  verifyGoogleFormat("A<int*, int*> a;");
889  verifyGoogleFormat("A<int**, int**> a;");
890  verifyGoogleFormat("f(b ? *c : *d);");
891  verifyGoogleFormat("int a = b ? *c : *d;");
892}
893
894TEST_F(FormatTest, DoesNotBreakBeforePointerOrReference) {
895  verifyFormat("int *someFunction(int LoooooooooooooooongParam1,\n"
896               "                  int LoooooooooooooooongParam2) {\n}");
897  verifyFormat(
898      "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
899      "                                   SourceLocation L, IdentifierIn *II,\n"
900      "                                   Type *T) {\n}");
901}
902
903TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
904  verifyFormat("(a)->b();");
905  verifyFormat("--a;");
906}
907
908TEST_F(FormatTest, HandlesIncludeDirectives) {
909  EXPECT_EQ("#include <string>\n", format("#include <string>\n"));
910  EXPECT_EQ("#include <a/b/c.h>\n", format("#include <a/b/c.h>\n"));
911  EXPECT_EQ("#include \"a/b/string\"\n", format("#include \"a/b/string\"\n"));
912  EXPECT_EQ("#include \"string.h\"\n", format("#include \"string.h\"\n"));
913  EXPECT_EQ("#include \"string.h\"\n", format("#include \"string.h\"\n"));
914
915  EXPECT_EQ("#import <string>\n", format("#import <string>\n"));
916  EXPECT_EQ("#import <a/b/c.h>\n", format("#import <a/b/c.h>\n"));
917  EXPECT_EQ("#import \"a/b/string\"\n", format("#import \"a/b/string\"\n"));
918  EXPECT_EQ("#import \"string.h\"\n", format("#import \"string.h\"\n"));
919  EXPECT_EQ("#import \"string.h\"\n", format("#import \"string.h\"\n"));
920}
921
922//===----------------------------------------------------------------------===//
923// Error recovery tests.
924//===----------------------------------------------------------------------===//
925
926TEST_F(FormatTest, IncorrectAccessSpecifier) {
927  verifyFormat("public:");
928  verifyFormat("class A {\n"
929               "public\n"
930               "  void f() {\n"
931               "  }\n"
932               "};");
933  verifyFormat("public\n"
934               "int qwerty;");
935  verifyFormat("public\n"
936               "B {\n"
937               "};");
938  verifyFormat("public\n"
939               "{\n"
940               "};");
941  verifyFormat("public\n"
942               "B {\n"
943               "  int x;\n"
944               "};");
945}
946
947TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
948  verifyFormat("{");
949}
950
951TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
952  verifyFormat("do {\n"
953               "};");
954  verifyFormat("do {\n"
955               "};\n"
956               "f();");
957  verifyFormat("do {\n"
958               "}\n"
959               "wheeee(fun);");
960  verifyFormat("do {\n"
961               "  f();\n"
962               "};");
963}
964
965TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
966  verifyFormat("namespace {\n"
967               "class Foo {  Foo  ( }; }  // comment");
968}
969
970TEST_F(FormatTest, IncorrectCodeErrorDetection) {
971  EXPECT_EQ("{\n{\n}\n", format("{\n{\n}\n"));
972  EXPECT_EQ("{\n  {\n}\n", format("{\n  {\n}\n"));
973  EXPECT_EQ("{\n  {\n  }\n", format("{\n  {\n  }\n"));
974  EXPECT_EQ("{\n  {\n    }\n  }\n}\n", format("{\n  {\n    }\n  }\n}\n"));
975
976  FormatStyle Style = getLLVMStyle();
977  Style.ColumnLimit = 10;
978  EXPECT_EQ("{\n"
979            "    {\n"
980            " breakme(\n"
981            "     qwe);\n"
982            "}\n", format("{\n"
983                          "    {\n"
984                          " breakme(qwe);\n"
985                          "}\n", Style));
986
987}
988
989TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
990  verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
991  EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
992            format("-(NSUInteger)indexOfObject:(id)anObject;"));
993  EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
994  EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
995  EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
996            format("-(NSInteger)Method3:(id)anObject;"));
997  EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
998            format("-(NSInteger)Method4:(id)anObject;"));
999  EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
1000            format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
1001  EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
1002            format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
1003  EXPECT_EQ(
1004      "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;",
1005      format("- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;"));
1006
1007  // Very long objectiveC method declaration.
1008  EXPECT_EQ(
1009      "- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range\n    "
1010      "outRange:(NSRange)out_range outRange1:(NSRange)out_range1\n    "
1011      "outRange2:(NSRange)out_range2 outRange3:(NSRange)out_range3\n    "
1012      "outRange4:(NSRange)out_range4 outRange5:(NSRange)out_range5\n    "
1013      "outRange6:(NSRange)out_range6 outRange7:(NSRange)out_range7\n    "
1014      "outRange8:(NSRange)out_range8 outRange9:(NSRange)out_range9;",
1015      format(
1016          "- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range "
1017          "outRange:(NSRange) out_range outRange1:(NSRange) out_range1 "
1018          "outRange2:(NSRange) out_range2  outRange3:(NSRange) out_range3  "
1019          "outRange4:(NSRange) out_range4  outRange5:(NSRange) out_range5 "
1020          "outRange6:(NSRange) out_range6  outRange7:(NSRange) out_range7  "
1021          "outRange8:(NSRange) out_range8  outRange9:(NSRange) out_range9;"));
1022}
1023
1024TEST_F(FormatTest, DoNotDropAt) {
1025  verifyFormat("@interface");
1026  verifyFormat("@dynamic");
1027}
1028
1029} // end namespace tooling
1030} // end namespace clang
1031