FormatTest.cpp revision f6fd00b12ae7d89436d32851c9bcc8dd3d046ad3
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    Lexer Lex(ID, Context.Sources.getBuffer(ID), Context.Sources, LangOpts);
33    tooling::Replacements Replace =
34        reformat(Style, Lex, Context.Sources, Ranges);
35    EXPECT_TRUE(applyAllReplacements(Replace, Context.Rewrite));
36    return Context.getRewrittenText(ID);
37  }
38
39  std::string format(llvm::StringRef Code,
40                     const FormatStyle &Style = getLLVMStyle()) {
41    return format(Code, 0, Code.size(), Style);
42  }
43
44  std::string messUp(llvm::StringRef Code) {
45    std::string MessedUp(Code.str());
46    bool InComment = false;
47    bool JustReplacedNewline = false;
48    for (unsigned i = 0, e = MessedUp.size() - 1; i != e; ++i) {
49      if (MessedUp[i] == '/' && MessedUp[i + 1] == '/') {
50        if (JustReplacedNewline)
51          MessedUp[i - 1] = '\n';
52        InComment = true;
53      } else if (MessedUp[i] == '\\' && MessedUp[i + 1] == '\n') {
54        MessedUp[i] = ' ';
55      } else if (MessedUp[i] == '\n') {
56        if (InComment) {
57          InComment = false;
58        } else {
59          JustReplacedNewline = true;
60          MessedUp[i] = ' ';
61        }
62      } else if (MessedUp[i] != ' ') {
63        JustReplacedNewline = false;
64      }
65    }
66    return MessedUp;
67  }
68
69  FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
70    FormatStyle Style = getLLVMStyle();
71    Style.ColumnLimit = ColumnLimit;
72    return Style;
73  }
74
75  void verifyFormat(llvm::StringRef Code,
76                    const FormatStyle &Style = getLLVMStyle()) {
77    EXPECT_EQ(Code.str(), format(messUp(Code), Style));
78  }
79
80  void verifyGoogleFormat(llvm::StringRef Code) {
81    verifyFormat(Code, getGoogleStyle());
82  }
83};
84
85//===----------------------------------------------------------------------===//
86// Basic function tests.
87//===----------------------------------------------------------------------===//
88
89TEST_F(FormatTest, DoesNotChangeCorrectlyFormatedCode) {
90  EXPECT_EQ(";", format(";"));
91}
92
93TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
94  EXPECT_EQ("int i;", format("  int i;"));
95  EXPECT_EQ("\nint i;", format(" \n\t \r  int i;"));
96  EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
97  EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
98}
99
100TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
101  EXPECT_EQ("int i;", format("int\ni;"));
102}
103
104TEST_F(FormatTest, FormatsNestedBlockStatements) {
105  EXPECT_EQ("{\n  {\n    {\n    }\n  }\n}", format("{{{}}}"));
106}
107
108TEST_F(FormatTest, FormatsNestedCall) {
109  verifyFormat("Method(f1, f2(f3));");
110  verifyFormat("Method(f1(f2, f3()));");
111}
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//===----------------------------------------------------------------------===//
269// Tests for comments.
270//===----------------------------------------------------------------------===//
271
272TEST_F(FormatTest, UnderstandsSingleLineComments) {
273  verifyFormat("// line 1\n"
274               "// line 2\n"
275               "void f() {\n}\n");
276
277  verifyFormat("void f() {\n"
278               "  // Doesn't do anything\n"
279               "}");
280
281  verifyFormat("int i  // This is a fancy variable\n"
282               "    = 5;");
283
284  verifyFormat("enum E {\n"
285               "  // comment\n"
286               "  VAL_A,  // comment\n"
287               "  VAL_B\n"
288               "};");
289
290  verifyFormat(
291      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
292      "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;  // Trailing comment");
293}
294
295TEST_F(FormatTest, UnderstandsMultiLineComments) {
296  verifyFormat("f(/*test=*/ true);");
297}
298
299
300//===----------------------------------------------------------------------===//
301// Tests for classes, namespaces, etc.
302//===----------------------------------------------------------------------===//
303
304TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
305  verifyFormat("class A {\n};");
306}
307
308TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
309  verifyFormat("class A {\n"
310               "public:\n"
311               "protected:\n"
312               "private:\n"
313               "  void f() {\n"
314               "  }\n"
315               "};");
316  verifyGoogleFormat("class A {\n"
317                     " public:\n"
318                     " protected:\n"
319                     " private:\n"
320                     "  void f() {\n"
321                     "  }\n"
322                     "};");
323}
324
325TEST_F(FormatTest, FormatsDerivedClass) {
326  verifyFormat("class A : public B {\n"
327               "};");
328  verifyFormat("class A : public ::B {\n"
329               "};");
330}
331
332TEST_F(FormatTest, FormatsEnum) {
333  verifyFormat("enum {\n"
334               "  Zero,\n"
335               "  One = 1,\n"
336               "  Two = One + 1,\n"
337               "  Three = (One + Two),\n"
338               "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
339               "  Five = (One, Two, Three, Four, 5)\n"
340               "};");
341  verifyFormat("enum Enum {\n"
342               "};");
343  verifyFormat("enum {\n"
344               "};");
345}
346
347TEST_F(FormatTest, FormatsNamespaces) {
348  verifyFormat("namespace some_namespace {\n"
349               "class A {\n"
350               "};\n"
351               "void f() {\n"
352               "  f();\n"
353               "}\n"
354               "}");
355  verifyFormat("namespace {\n"
356               "class A {\n"
357               "};\n"
358               "void f() {\n"
359               "  f();\n"
360               "}\n"
361               "}");
362  verifyFormat("inline namespace X {\n"
363               "class A {\n"
364               "};\n"
365               "void f() {\n"
366               "  f();\n"
367               "}\n"
368               "}");
369  verifyFormat("using namespace some_namespace;\n"
370               "class A {\n"
371               "};\n"
372               "void f() {\n"
373               "  f();\n"
374               "}");
375}
376
377TEST_F(FormatTest, StaticInitializers) {
378  verifyFormat("static SomeClass SC = { 1, 'a' };");
379
380  // FIXME: Format like enums if the static initializer does not fit on a line.
381  verifyFormat(
382      "static SomeClass WithALoooooooooooooooooooongName = { 100000000,\n"
383      "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" };");
384}
385
386TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
387  verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
388               "                      \\\n"
389               "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
390}
391
392TEST_F(FormatTest, BreaksOnHashWhenDirectiveIsInvalid) {
393  EXPECT_EQ("#\n;", format("#;"));
394}
395
396TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
397  EXPECT_EQ("#line 42 \"test\"\n",
398            format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
399  EXPECT_EQ("#define A  \\\n  B\n",
400            format("#  \\\n define  \\\n    A  \\\n       B\n",
401                   getLLVMStyleWithColumns(12)));
402}
403
404TEST_F(FormatTest, EndOfFileEndsPPDirective) {
405  EXPECT_EQ("#line 42 \"test\"",
406            format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
407  EXPECT_EQ("#define A  \\\n  B",
408            format("#  \\\n define  \\\n    A  \\\n       B",
409                   getLLVMStyleWithColumns(12)));
410}
411
412TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
413  // If the macro fits in one line, we have the full width.
414  verifyFormat("#define A(B)", getLLVMStyleWithColumns(12));
415
416  verifyFormat("#define A(\\\n    B)", getLLVMStyleWithColumns(11));
417  verifyFormat("#define AA(\\\n    B)", getLLVMStyleWithColumns(11));
418  verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
419}
420
421TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
422  EXPECT_EQ("// some comment\n"
423            "#include \"a.h\"\n"
424            "#define A(A,\\\n"
425            "          B)\n"
426            "#include \"b.h\"\n"
427            "// some comment\n",
428            format("  // some comment\n"
429                   "  #include \"a.h\"\n"
430                   "#define A(A,\\\n"
431                   "    B)\n"
432                   "    #include \"b.h\"\n"
433                   " // some comment\n", getLLVMStyleWithColumns(13)));
434}
435
436TEST_F(FormatTest, LayoutSingleHash) {
437  EXPECT_EQ("#\na;", format("#\na;"));
438}
439
440TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
441  EXPECT_EQ("#define A    \\\n"
442            "  c;         \\\n"
443            "  e;\n"
444            "f;", format("#define A c; e;\n"
445                         "f;", getLLVMStyleWithColumns(14)));
446}
447
448TEST_F(FormatTest, LayoutRemainingTokens) {
449  EXPECT_EQ("{\n}", format("{}"));
450}
451
452TEST_F(FormatTest, LayoutSingleUnwrappedLineInMacro) {
453  EXPECT_EQ("#define A \\\n  b;",
454            format("#define A b;", 10, 2, getLLVMStyleWithColumns(11)));
455}
456
457TEST_F(FormatTest, MacroDefinitionInsideStatement) {
458  EXPECT_EQ("int x,\n#define A\ny;", format("int x,\n#define A\ny;"));
459}
460
461TEST_F(FormatTest, HashInMacroDefinition) {
462  verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
463  verifyFormat("#define A \\\n"
464               "  {       \\\n"
465               "    f(#c);\\\n"
466               "  }", getLLVMStyleWithColumns(11));
467}
468
469TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
470  EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
471}
472
473TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
474  verifyFormat("{\n  {\n    a #c;\n  }\n}");
475}
476
477// FIXME: write test for unbalanced braces in macros...
478// FIXME: test # inside a normal statement (like {#define A b})
479
480TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
481  EXPECT_EQ(
482      "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
483      "                      \\\n"
484      "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
485      "\n"
486      "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
487      "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
488      format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
489             "\\\n"
490             "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
491             "  \n"
492             "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
493             "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
494}
495
496//===----------------------------------------------------------------------===//
497// Line break tests.
498//===----------------------------------------------------------------------===//
499
500TEST_F(FormatTest, FormatsFunctionDefinition) {
501  verifyFormat("void f(int a, int b, int c, int d, int e, int f, int g,"
502               " int h, int j, int f,\n"
503               "       int c, int ddddddddddddd) {\n"
504               "}");
505}
506
507TEST_F(FormatTest, FormatsAwesomeMethodCall) {
508  verifyFormat(
509      "SomeLongMethodName(SomeReallyLongMethod(\n"
510      "    CallOtherReallyLongMethod(parameter, parameter, parameter)),\n"
511      "                   SecondLongCall(parameter));");
512}
513
514TEST_F(FormatTest, ConstructorInitializers) {
515  verifyFormat("Constructor() : Initializer(FitsOnTheLine) {\n}");
516
517  verifyFormat(
518      "SomeClass::Constructor()\n"
519      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {\n"
520      "}");
521
522  verifyFormat(
523      "SomeClass::Constructor()\n"
524      "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
525      "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {\n"
526      "}");
527
528  verifyFormat("Constructor()\n"
529               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
530               "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
531               "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
532               "      aaaaaaaaaaaaaaaaaaaaaaa() {\n"
533               "}");
534
535  // Here a line could be saved by splitting the second initializer onto two
536  // lines, but that is not desireable.
537  verifyFormat("Constructor()\n"
538               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
539               "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
540               "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
541               "}");
542
543  verifyGoogleFormat("MyClass::MyClass(int var)\n"
544                     "    : some_var_(var),  // 4 space indent\n"
545                     "      some_other_var_(var + 1) {  // lined up\n"
546                     "}");
547}
548
549TEST_F(FormatTest, BreaksAsHighAsPossible) {
550  verifyFormat(
551      "if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
552      "    (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
553      "  f();");
554}
555
556TEST_F(FormatTest, BreaksDesireably) {
557  verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
558               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
559               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n};");
560
561  verifyFormat(
562      "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
563      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
564
565  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
566               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
567               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
568
569  verifyFormat(
570      "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
571      "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
572      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
573      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
574
575  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
576               "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
577
578  verifyFormat(
579      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
580      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
581
582  // This test case breaks on an incorrect memoization, i.e. an optimization not
583  // taking into account the StopAt value.
584  verifyFormat(
585      "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
586      "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
587      "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
588      "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
589
590  verifyFormat(
591      "{\n  {\n    {\n"
592      "      Annotation.SpaceRequiredBefore =\n"
593      "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
594      "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
595      "    }\n  }\n}");
596}
597
598TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
599  verifyFormat(
600      "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
601      "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
602  verifyFormat(
603      "if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
604      "    ccccccccccccccccccccccccc) {\n}");
605  verifyFormat(
606      "if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
607      "    ccccccccccccccccccccccccc) {\n}");
608  verifyFormat(
609      "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
610      "    ccccccccccccccccccccccccc) {\n}");
611}
612
613TEST_F(FormatTest, AlignsAfterAssignments) {
614  verifyFormat(
615      "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
616      "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
617  verifyFormat(
618      "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
619      "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
620  verifyFormat(
621      "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
622      "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
623  verifyFormat(
624      "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
625      "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
626  verifyFormat(
627      "double LooooooooooooooooooooooooongResult =\n"
628      "    aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
629      "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
630}
631
632TEST_F(FormatTest, AlignsAfterReturn) {
633  verifyFormat(
634      "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
635      "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
636  verifyFormat(
637      "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
638      "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
639}
640
641TEST_F(FormatTest, AlignsStringLiterals) {
642  verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
643               "                                      \"short literal\");");
644  verifyFormat(
645      "looooooooooooooooooooooooongFunction(\n"
646      "    \"short literal\"\n"
647      "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
648}
649
650TEST_F(FormatTest, AlignsPipes) {
651  verifyFormat(
652      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
653      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
654      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
655  verifyFormat(
656      "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
657      "                     << aaaaaaaaaaaaaaaaaaaa;");
658  verifyFormat(
659      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
660      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
661  verifyFormat(
662      "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
663      "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
664      "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
665  verifyFormat(
666      "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
667      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
668      "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
669}
670
671TEST_F(FormatTest, UnderstandsEquals) {
672  verifyFormat(
673      "aaaaaaaaaaaaaaaaa =\n"
674      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
675  verifyFormat(
676      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
677      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
678      "}");
679  verifyFormat(
680      "if (a) {\n"
681      "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
682      "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
683      "}");
684
685  verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
686               "        100000000 + 100000000) {\n}");
687}
688
689TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
690  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
691               "    .looooooooooooooooooooooooooooooooooooooongFunction();");
692
693  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
694               "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
695
696  verifyFormat(
697      "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
698      "                                                          Parameter2);");
699
700  verifyFormat(
701      "ShortObject->shortFunction(\n"
702      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
703      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
704
705  verifyFormat("loooooooooooooongFunction(\n"
706               "    LoooooooooooooongObject->looooooooooooooooongFunction());");
707
708  verifyFormat(
709      "function(LoooooooooooooooooooooooooooooooooooongObject\n"
710      "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
711
712  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
713               "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
714               "}");
715}
716
717TEST_F(FormatTest, WrapsTemplateDeclarations) {
718  verifyFormat("template <typename T>\n"
719               "virtual void loooooooooooongFunction(int Param1, int Param2);");
720  verifyFormat(
721      "template <typename T> void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
722      "                             int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
723  verifyFormat(
724      "template <typename T>\n"
725      "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
726      "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
727  verifyFormat(
728      "template <typename T>\n"
729      "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
730      "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
731      "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
732
733}
734
735TEST_F(FormatTest, UnderstandsTemplateParameters) {
736  verifyFormat("A<int> a;");
737  verifyFormat("A<A<A<int> > > a;");
738  verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
739  verifyFormat("bool x = a < 1 || 2 > a;");
740  verifyFormat("bool x = 5 < f<int>();");
741  verifyFormat("bool x = f<int>() > 5;");
742  verifyFormat("bool x = 5 < a<int>::x;");
743  verifyFormat("bool x = a < 4 ? a > 2 : false;");
744  verifyFormat("bool x = f() ? a < 2 : a > 2;");
745
746  verifyGoogleFormat("A<A<int>> a;");
747  verifyGoogleFormat("A<A<A<int>>> a;");
748  verifyGoogleFormat("A<A<A<A<int>>>> a;");
749
750  verifyFormat("test >> a >> b;");
751  verifyFormat("test << a >> b;");
752
753  verifyFormat("f<int>();");
754  verifyFormat("template <typename T> void f() {\n}");
755}
756
757TEST_F(FormatTest, UnderstandsUnaryOperators) {
758  verifyFormat("int a = -2;");
759  verifyFormat("f(-1, -2, -3);");
760  verifyFormat("a[-1] = 5;");
761  verifyFormat("int a = 5 + -2;");
762  verifyFormat("if (i == -1) {\n}");
763  verifyFormat("if (i != -1) {\n}");
764  verifyFormat("if (i > -1) {\n}");
765  verifyFormat("if (i < -1) {\n}");
766  verifyFormat("++(a->f());");
767  verifyFormat("--(a->f());");
768  verifyFormat("if (!(a->f())) {\n}");
769
770  verifyFormat("a-- > b;");
771  verifyFormat("b ? -a : c;");
772  verifyFormat("n * sizeof char16;");
773  verifyFormat("n * alignof char16;");
774  verifyFormat("sizeof(char);");
775  verifyFormat("alignof(char);");
776
777  verifyFormat("return -1;");
778  verifyFormat("switch (a) {\n"
779               "case -1:\n"
780               "  break;\n"
781               "}");
782}
783
784TEST_F(FormatTest, UndestandsOverloadedOperators) {
785  verifyFormat("bool operator<();");
786  verifyFormat("bool operator>();");
787  verifyFormat("bool operator=();");
788  verifyFormat("bool operator==();");
789  verifyFormat("bool operator!=();");
790  verifyFormat("int operator+();");
791  verifyFormat("int operator++();");
792  verifyFormat("bool operator();");
793  verifyFormat("bool operator()();");
794  verifyFormat("bool operator[]();");
795  verifyFormat("operator bool();");
796  verifyFormat("operator SomeType<int>();");
797  verifyFormat("void *operator new(std::size_t size);");
798  verifyFormat("void *operator new[](std::size_t size);");
799  verifyFormat("void operator delete(void *ptr);");
800  verifyFormat("void operator delete[](void *ptr);");
801}
802
803TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
804  verifyFormat("int *f(int *a) {\n}");
805  verifyFormat("f(a, *a);");
806  verifyFormat("f(*a);");
807  verifyFormat("int a = b * 10;");
808  verifyFormat("int a = 10 * b;");
809  verifyFormat("int a = b * c;");
810  verifyFormat("int a += b * c;");
811  verifyFormat("int a -= b * c;");
812  verifyFormat("int a *= b * c;");
813  verifyFormat("int a /= b * c;");
814  verifyFormat("int a = *b;");
815  verifyFormat("int a = *b * c;");
816  verifyFormat("int a = b * *c;");
817  verifyFormat("int main(int argc, char **argv) {\n}");
818  verifyFormat("return 10 * b;");
819  verifyFormat("return *b * *c;");
820  verifyFormat("return a & ~b;");
821  verifyFormat("f(b ? *c : *d);");
822  verifyFormat("int a = b ? *c : *d;");
823  verifyFormat("*b = a;");
824  verifyFormat("a * ~b;");
825  verifyFormat("a * !b;");
826  verifyFormat("a * +b;");
827  verifyFormat("a * -b;");
828  verifyFormat("a * ++b;");
829  verifyFormat("a * --b;");
830
831  verifyFormat("InvalidRegions[*R] = 0;");
832
833  // FIXME: Is this desired for LLVM? Fix if not.
834  verifyFormat("A<int *> a;");
835  verifyFormat("A<int **> a;");
836  verifyFormat("A<int *, int *> a;");
837  verifyFormat("A<int **, int **> a;");
838  verifyFormat("Type *A = static_cast<Type *>(P);");
839  verifyFormat("Type *A = (Type *) P;");
840  verifyFormat("Type *A = (vector<Type *, int *>) P;");
841
842  verifyGoogleFormat("int main(int argc, char** argv) {\n}");
843  verifyGoogleFormat("A<int*> a;");
844  verifyGoogleFormat("A<int**> a;");
845  verifyGoogleFormat("A<int*, int*> a;");
846  verifyGoogleFormat("A<int**, int**> a;");
847  verifyGoogleFormat("f(b ? *c : *d);");
848  verifyGoogleFormat("int a = b ? *c : *d;");
849}
850
851TEST_F(FormatTest, DoesNotBreakBeforePointerOrReference) {
852  verifyFormat(
853      "int *someFunction(int LoooooooooooooooongParam1,\n"
854      "                  int LoooooooooooooooongParam2) {\n}");
855  verifyFormat(
856      "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
857      "                                   SourceLocation L, IdentifierIn *II,\n"
858      "                                   Type *T) {\n}");
859}
860
861TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
862  verifyFormat("(a)->b();");
863  verifyFormat("--a;");
864}
865
866TEST_F(FormatTest, HandlesIncludeDirectives) {
867  EXPECT_EQ("#include <string>\n", format("#include <string>\n"));
868  EXPECT_EQ("#include <a/b/c.h>\n", format("#include <a/b/c.h>\n"));
869  EXPECT_EQ("#include \"a/b/string\"\n", format("#include \"a/b/string\"\n"));
870  EXPECT_EQ("#include \"string.h\"\n", format("#include \"string.h\"\n"));
871  EXPECT_EQ("#include \"string.h\"\n", format("#include \"string.h\"\n"));
872
873  EXPECT_EQ("#import <string>\n", format("#import <string>\n"));
874  EXPECT_EQ("#import <a/b/c.h>\n", format("#import <a/b/c.h>\n"));
875  EXPECT_EQ("#import \"a/b/string\"\n", format("#import \"a/b/string\"\n"));
876  EXPECT_EQ("#import \"string.h\"\n", format("#import \"string.h\"\n"));
877  EXPECT_EQ("#import \"string.h\"\n", format("#import \"string.h\"\n"));
878}
879
880
881//===----------------------------------------------------------------------===//
882// Error recovery tests.
883//===----------------------------------------------------------------------===//
884
885TEST_F(FormatTest, IncorrectAccessSpecifier) {
886  verifyFormat("public:");
887  verifyFormat("class A {\n"
888               "public\n"
889               "  void f() {\n"
890               "  }\n"
891               "};");
892  verifyFormat("public\n"
893               "int qwerty;");
894  verifyFormat("public\n"
895               "B {\n"
896               "};");
897  verifyFormat("public\n"
898               "{\n"
899               "};");
900  verifyFormat("public\n"
901               "B {\n"
902               "  int x;\n"
903               "};");
904}
905
906TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
907  verifyFormat("{");
908}
909
910TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
911  verifyFormat("do {\n"
912               "};");
913  verifyFormat("do {\n"
914               "};\n"
915               "f();");
916  verifyFormat("do {\n"
917               "}\n"
918               "wheeee(fun);");
919  verifyFormat("do {\n"
920               "  f();\n"
921               "};");
922}
923
924TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
925  verifyFormat("namespace {\n"
926               "class Foo {  Foo  ( }; }  // comment");
927}
928
929TEST_F(FormatTest, IncorrectCodeErrorDetection) {
930  EXPECT_EQ("{\n{\n}\n", format("{\n{\n}\n"));
931  EXPECT_EQ("{\n  {\n}\n", format("{\n  {\n}\n"));
932  EXPECT_EQ("{\n  {\n  }\n", format("{\n  {\n  }\n"));
933  EXPECT_EQ("{\n  {\n    }\n  }\n}\n", format("{\n  {\n    }\n  }\n}\n"));
934
935  FormatStyle Style = getLLVMStyle();
936  Style.ColumnLimit = 10;
937  EXPECT_EQ("{\n"
938            "    {\n"
939            " breakme(\n"
940            "     qwe);\n"
941            "}\n", format("{\n"
942                          "    {\n"
943                          " breakme(qwe);\n"
944                          "}\n", Style));
945
946}
947
948TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
949  verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
950  EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
951            format("-(NSUInteger)indexOfObject:(id)anObject;"));
952  EXPECT_EQ("- (NSInteger)Mthod1;",
953            format("-(NSInteger)Mthod1;"));
954  EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
955  EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
956            format("-(NSInteger)Method3:(id)anObject;"));
957  EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
958            format("-(NSInteger)Method4:(id)anObject;"));
959  EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
960            format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
961  EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
962            format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
963  EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;",
964            format("- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;"));
965
966  // Very long objectiveC method declaration.
967  EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range\n    "
968            "outRange:(NSRange)out_range outRange1:(NSRange)out_range1\n    "
969            "outRange2:(NSRange)out_range2 outRange3:(NSRange)out_range3\n    "
970            "outRange4:(NSRange)out_range4 outRange5:(NSRange)out_range5\n    "
971            "outRange6:(NSRange)out_range6 outRange7:(NSRange)out_range7\n    "
972            "outRange8:(NSRange)out_range8 outRange9:(NSRange)out_range9;",
973
974            format("- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range "
975                   "outRange:(NSRange) out_range outRange1:(NSRange) out_range1 "
976                   "outRange2:(NSRange) out_range2  outRange3:(NSRange) out_range3  "
977                   "outRange4:(NSRange) out_range4  outRange5:(NSRange) out_range5 "
978                   "outRange6:(NSRange) out_range6  outRange7:(NSRange) out_range7  "
979                   "outRange8:(NSRange) out_range8  outRange9:(NSRange) out_range9;"));
980}
981
982}  // end namespace tooling
983}  // end namespace clang
984