FormatTest.cpp revision c44ee89cb448e34aada006b707eb45a1280f31e3
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
18// Uncomment to get debug output from tests:
19// #define DEBUG_WITH_TYPE(T, X) do { X; } while(0)
20
21namespace clang {
22namespace format {
23
24class FormatTest : public ::testing::Test {
25protected:
26  std::string format(llvm::StringRef Code, unsigned Offset, unsigned Length,
27                     const FormatStyle &Style) {
28    DEBUG(llvm::errs() << "---\n");
29    RewriterTestContext Context;
30    FileID ID = Context.createInMemoryFile("input.cc", Code);
31    SourceLocation Start =
32        Context.Sources.getLocForStartOfFile(ID).getLocWithOffset(Offset);
33    std::vector<CharSourceRange> Ranges(
34        1,
35        CharSourceRange::getCharRange(Start, Start.getLocWithOffset(Length)));
36    Lexer Lex(ID, Context.Sources.getBuffer(ID), Context.Sources,
37              getFormattingLangOpts());
38    tooling::Replacements Replace = reformat(Style, Lex, Context.Sources,
39                                             Ranges,
40                                             new IgnoringDiagConsumer());
41    EXPECT_TRUE(applyAllReplacements(Replace, Context.Rewrite));
42    DEBUG(llvm::errs() << "\n" << Context.getRewrittenText(ID) << "\n\n");
43    return Context.getRewrittenText(ID);
44  }
45
46  std::string format(llvm::StringRef Code,
47                     const FormatStyle &Style = getLLVMStyle()) {
48    return format(Code, 0, Code.size(), Style);
49  }
50
51  std::string messUp(llvm::StringRef Code) {
52    std::string MessedUp(Code.str());
53    bool InComment = false;
54    bool InPreprocessorDirective = false;
55    bool JustReplacedNewline = false;
56    for (unsigned i = 0, e = MessedUp.size() - 1; i != e; ++i) {
57      if (MessedUp[i] == '/' && MessedUp[i + 1] == '/') {
58        if (JustReplacedNewline)
59          MessedUp[i - 1] = '\n';
60        InComment = true;
61      } else if (MessedUp[i] == '#' && (JustReplacedNewline || i == 0)) {
62        if (i != 0) MessedUp[i - 1] = '\n';
63        InPreprocessorDirective = true;
64      } else if (MessedUp[i] == '\\' && MessedUp[i + 1] == '\n') {
65        MessedUp[i] = ' ';
66        MessedUp[i + 1] = ' ';
67      } else if (MessedUp[i] == '\n') {
68        if (InComment) {
69          InComment = false;
70        } else if (InPreprocessorDirective) {
71          InPreprocessorDirective = false;
72        } else {
73          JustReplacedNewline = true;
74          MessedUp[i] = ' ';
75        }
76      } else if (MessedUp[i] != ' ') {
77        JustReplacedNewline = false;
78      }
79    }
80    return MessedUp;
81  }
82
83  FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
84    FormatStyle Style = getLLVMStyle();
85    Style.ColumnLimit = ColumnLimit;
86    return Style;
87  }
88
89  FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
90    FormatStyle Style = getGoogleStyle();
91    Style.ColumnLimit = ColumnLimit;
92    return Style;
93  }
94
95  void verifyFormat(llvm::StringRef Code,
96                    const FormatStyle &Style = getLLVMStyle()) {
97    EXPECT_EQ(Code.str(), format(messUp(Code), Style));
98  }
99
100  void verifyGoogleFormat(llvm::StringRef Code) {
101    verifyFormat(Code, getGoogleStyle());
102  }
103};
104
105TEST_F(FormatTest, MessUp) {
106  EXPECT_EQ("1 2 3", messUp("1 2 3"));
107  EXPECT_EQ("1 2 3\n", messUp("1\n2\n3\n"));
108  EXPECT_EQ("a\n//b\nc", messUp("a\n//b\nc"));
109  EXPECT_EQ("a\n#b\nc", messUp("a\n#b\nc"));
110  EXPECT_EQ("a\n#b  c  d\ne", messUp("a\n#b\\\nc\\\nd\ne"));
111}
112
113//===----------------------------------------------------------------------===//
114// Basic function tests.
115//===----------------------------------------------------------------------===//
116
117TEST_F(FormatTest, DoesNotChangeCorrectlyFormatedCode) {
118  EXPECT_EQ(";", format(";"));
119}
120
121TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
122  EXPECT_EQ("int i;", format("  int i;"));
123  EXPECT_EQ("\nint i;", format(" \n\t \r  int i;"));
124  EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
125  EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
126}
127
128TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
129  EXPECT_EQ("int i;", format("int\ni;"));
130}
131
132TEST_F(FormatTest, FormatsNestedBlockStatements) {
133  EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
134}
135
136TEST_F(FormatTest, FormatsNestedCall) {
137  verifyFormat("Method(f1, f2(f3));");
138  verifyFormat("Method(f1(f2, f3()));");
139  verifyFormat("Method(f1(f2, (f3())));");
140}
141
142TEST_F(FormatTest, ImportantSpaces) {
143  verifyFormat("vector< ::Type> v;");
144}
145
146//===----------------------------------------------------------------------===//
147// Tests for control statements.
148//===----------------------------------------------------------------------===//
149
150TEST_F(FormatTest, FormatIfWithoutCompountStatement) {
151  verifyFormat("if (true)\n  f();\ng();");
152  verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
153  verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
154
155  FormatStyle AllowsMergedIf = getGoogleStyle();
156  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
157  verifyFormat("if (a)\n"
158               "  // comment\n"
159               "  f();", AllowsMergedIf);
160
161  verifyFormat("if (a)  // Can't merge this\n"
162               "  f();\n", AllowsMergedIf);
163  verifyFormat("if (a) /* still don't merge */\n"
164               "  f();", AllowsMergedIf);
165  verifyFormat("if (a) {  // Never merge this\n"
166               "  f();\n"
167               "}", AllowsMergedIf);
168  verifyFormat("if (a) { /* Never merge this */\n"
169               "  f();\n"
170               "}", AllowsMergedIf);
171
172  AllowsMergedIf.ColumnLimit = 14;
173  verifyFormat("if (a) return;", AllowsMergedIf);
174  verifyFormat("if (aaaaaaaaa)\n"
175               "  return;", AllowsMergedIf);
176
177  AllowsMergedIf.ColumnLimit = 13;
178  verifyFormat("if (a)\n  return;", AllowsMergedIf);
179}
180
181TEST_F(FormatTest, ParseIfElse) {
182  verifyFormat("if (true)\n"
183               "  if (true)\n"
184               "    if (true)\n"
185               "      f();\n"
186               "    else\n"
187               "      g();\n"
188               "  else\n"
189               "    h();\n"
190               "else\n"
191               "  i();");
192  verifyFormat("if (true)\n"
193               "  if (true)\n"
194               "    if (true) {\n"
195               "      if (true)\n"
196               "        f();\n"
197               "    } else {\n"
198               "      g();\n"
199               "    }\n"
200               "  else\n"
201               "    h();\n"
202               "else {\n"
203               "  i();\n"
204               "}");
205}
206
207TEST_F(FormatTest, ElseIf) {
208  verifyFormat("if (a) {} else if (b) {}");
209  verifyFormat("if (a)\n"
210               "  f();\n"
211               "else if (b)\n"
212               "  g();\n"
213               "else\n"
214               "  h();");
215}
216
217TEST_F(FormatTest, FormatsForLoop) {
218  verifyFormat(
219      "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
220      "     ++VeryVeryLongLoopVariable)\n"
221      "  ;");
222  verifyFormat("for (;;)\n"
223               "  f();");
224  verifyFormat("for (;;) {}");
225  verifyFormat("for (;;) {\n"
226               "  f();\n"
227               "}");
228
229  verifyFormat(
230      "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
231      "                                          E = UnwrappedLines.end();\n"
232      "     I != E; ++I) {}");
233
234  verifyFormat(
235      "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
236      "     ++IIIII) {}");
237}
238
239TEST_F(FormatTest, FormatsWhileLoop) {
240  verifyFormat("while (true) {}");
241  verifyFormat("while (true)\n"
242               "  f();");
243  verifyFormat("while () {}");
244  verifyFormat("while () {\n"
245               "  f();\n"
246               "}");
247}
248
249TEST_F(FormatTest, FormatsDoWhile) {
250  verifyFormat("do {\n"
251               "  do_something();\n"
252               "} while (something());");
253  verifyFormat("do\n"
254               "  do_something();\n"
255               "while (something());");
256}
257
258TEST_F(FormatTest, FormatsSwitchStatement) {
259  verifyFormat("switch (x) {\n"
260               "case 1:\n"
261               "  f();\n"
262               "  break;\n"
263               "case kFoo:\n"
264               "case ns::kBar:\n"
265               "case kBaz:\n"
266               "  break;\n"
267               "default:\n"
268               "  g();\n"
269               "  break;\n"
270               "}");
271  verifyFormat("switch (x) {\n"
272               "case 1: {\n"
273               "  f();\n"
274               "  break;\n"
275               "}\n"
276               "}");
277  verifyFormat("switch (x) {\n"
278               "case 1: {\n"
279               "  f();\n"
280               "  {\n"
281               "    g();\n"
282               "    h();\n"
283               "  }\n"
284               "  break;\n"
285               "}\n"
286               "}");
287  verifyFormat("switch (x) {\n"
288               "case 1: {\n"
289               "  f();\n"
290               "  if (foo) {\n"
291               "    g();\n"
292               "    h();\n"
293               "  }\n"
294               "  break;\n"
295               "}\n"
296               "}");
297  verifyFormat("switch (x) {\n"
298               "case 1: {\n"
299               "  f();\n"
300               "  g();\n"
301               "} break;\n"
302               "}");
303  verifyFormat("switch (test)\n"
304               "  ;");
305  verifyGoogleFormat("switch (x) {\n"
306                     "  case 1:\n"
307                     "    f();\n"
308                     "    break;\n"
309                     "  case kFoo:\n"
310                     "  case ns::kBar:\n"
311                     "  case kBaz:\n"
312                     "    break;\n"
313                     "  default:\n"
314                     "    g();\n"
315                     "    break;\n"
316                     "}");
317  verifyGoogleFormat("switch (x) {\n"
318                     "  case 1: {\n"
319                     "    f();\n"
320                     "    break;\n"
321                     "  }\n"
322                     "}");
323  verifyGoogleFormat("switch (test)\n"
324                     "    ;");
325}
326
327TEST_F(FormatTest, FormatsLabels) {
328  verifyFormat("void f() {\n"
329               "  some_code();\n"
330               "test_label:\n"
331               "  some_other_code();\n"
332               "  {\n"
333               "    some_more_code();\n"
334               "  another_label:\n"
335               "    some_more_code();\n"
336               "  }\n"
337               "}");
338  verifyFormat("some_code();\n"
339               "test_label:\n"
340               "some_other_code();");
341}
342
343//===----------------------------------------------------------------------===//
344// Tests for comments.
345//===----------------------------------------------------------------------===//
346
347TEST_F(FormatTest, UnderstandsSingleLineComments) {
348  verifyFormat("// line 1\n"
349               "// line 2\n"
350               "void f() {}\n");
351
352  verifyFormat("void f() {\n"
353               "  // Doesn't do anything\n"
354               "}");
355  verifyFormat("void f(int i,  // some comment (probably for i)\n"
356               "       int j,  // some comment (probably for j)\n"
357               "       int k); // some comment (probably for k)");
358  verifyFormat("void f(int i,\n"
359               "       // some comment (probably for j)\n"
360               "       int j,\n"
361               "       // some comment (probably for k)\n"
362               "       int k);");
363
364  verifyFormat("int i    // This is a fancy variable\n"
365               "    = 5; // with nicely aligned comment.");
366
367  verifyFormat("// Leading comment.\n"
368               "int a; // Trailing comment.");
369  verifyFormat("int a; // Trailing comment\n"
370               "       // on 2\n"
371               "       // or 3 lines.\n"
372               "int b;");
373  verifyFormat("int a; // Trailing comment\n"
374               "\n"
375               "// Leading comment.\n"
376               "int b;");
377  verifyFormat("int a;    // Comment.\n"
378               "          // More details.\n"
379               "int bbbb; // Another comment.");
380  verifyFormat(
381      "int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
382      "int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;   // comment\n"
383      "int cccccccccccccccccccccccccccccc;       // comment\n"
384      "int ddd;                     // looooooooooooooooooooooooong comment\n"
385      "int aaaaaaaaaaaaaaaaaaaaaaa; // comment\n"
386      "int bbbbbbbbbbbbbbbbbbbbb;   // comment\n"
387      "int ccccccccccccccccccc;     // comment");
388
389  verifyFormat("#include \"a\"     // comment\n"
390               "#include \"a/b/c\" // comment");
391  verifyFormat("#include <a>     // comment\n"
392               "#include <a/b/c> // comment");
393
394  verifyFormat("enum E {\n"
395               "  // comment\n"
396               "  VAL_A, // comment\n"
397               "  VAL_B\n"
398               "};");
399
400  verifyFormat(
401      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
402      "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; // Trailing comment");
403  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
404               "    // Comment inside a statement.\n"
405               "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
406
407  EXPECT_EQ("int i; // single line trailing comment",
408            format("int i;\\\n// single line trailing comment"));
409
410  verifyGoogleFormat("int a;  // Trailing comment.");
411}
412
413TEST_F(FormatTest, UnderstandsMultiLineComments) {
414  verifyFormat("f(/*test=*/ true);");
415  EXPECT_EQ(
416      "f(aaaaaaaaaaaaaaaaaaaaaaaaa, /* Trailing comment for aa... */\n"
417      "  bbbbbbbbbbbbbbbbbbbbbbbbb);",
418      format("f(aaaaaaaaaaaaaaaaaaaaaaaaa ,  /* Trailing comment for aa... */\n"
419             "  bbbbbbbbbbbbbbbbbbbbbbbbb);"));
420  EXPECT_EQ(
421      "f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
422      "  /* Leading comment for bb... */ bbbbbbbbbbbbbbbbbbbbbbbbb);",
423      format("f(aaaaaaaaaaaaaaaaaaaaaaaaa    ,   \n"
424             "/* Leading comment for bb... */   bbbbbbbbbbbbbbbbbbbbbbbbb);"));
425}
426
427TEST_F(FormatTest, CommentsInStaticInitializers) {
428  EXPECT_EQ(
429      "static SomeType type = { aaaaaaaaaaaaaaaaaaaa, /* comment */\n"
430      "                         aaaaaaaaaaaaaaaaaaaa /* comment */,\n"
431      "                         /* comment */ aaaaaaaaaaaaaaaaaaaa,\n"
432      "                         aaaaaaaaaaaaaaaaaaaa, // comment\n"
433      "                         aaaaaaaaaaaaaaaaaaaa };",
434      format("static SomeType type = { aaaaaaaaaaaaaaaaaaaa  ,  /* comment */\n"
435             "                   aaaaaaaaaaaaaaaaaaaa   /* comment */ ,\n"
436             "                     /* comment */   aaaaaaaaaaaaaaaaaaaa ,\n"
437             "              aaaaaaaaaaaaaaaaaaaa ,   // comment\n"
438             "                  aaaaaaaaaaaaaaaaaaaa };"));
439  verifyFormat("static SomeType type = { aaaaaaaaaaa, // comment for aa...\n"
440               "                         bbbbbbbbbbb, ccccccccccc };");
441  verifyFormat("static SomeType type = { aaaaaaaaaaa,\n"
442               "                         // comment for bb....\n"
443               "                         bbbbbbbbbbb, ccccccccccc };");
444  verifyGoogleFormat(
445      "static SomeType type = { aaaaaaaaaaa,  // comment for aa...\n"
446      "                         bbbbbbbbbbb,\n"
447      "                         ccccccccccc };");
448  verifyGoogleFormat("static SomeType type = { aaaaaaaaaaa,\n"
449                     "                         // comment for bb....\n"
450                     "                         bbbbbbbbbbb,\n"
451                     "                         ccccccccccc };");
452
453}
454
455//===----------------------------------------------------------------------===//
456// Tests for classes, namespaces, etc.
457//===----------------------------------------------------------------------===//
458
459TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
460  verifyFormat("class A {};");
461}
462
463TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
464  verifyFormat("class A {\n"
465               "public:\n"
466               "protected:\n"
467               "private:\n"
468               "  void f() {}\n"
469               "};");
470  verifyGoogleFormat("class A {\n"
471                     " public:\n"
472                     " protected:\n"
473                     " private:\n"
474                     "  void f() {}\n"
475                     "};");
476}
477
478TEST_F(FormatTest, FormatsDerivedClass) {
479  verifyFormat("class A : public B {};");
480  verifyFormat("class A : public ::B {};");
481}
482
483TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
484  verifyFormat("class A {} a, b;");
485  verifyFormat("struct A {} a, b;");
486  verifyFormat("union A {} a;");
487}
488
489TEST_F(FormatTest, FormatsEnum) {
490  verifyFormat("enum {\n"
491               "  Zero,\n"
492               "  One = 1,\n"
493               "  Two = One + 1,\n"
494               "  Three = (One + Two),\n"
495               "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
496               "  Five = (One, Two, Three, Four, 5)\n"
497               "};");
498  verifyFormat("enum Enum {\n"
499               "};");
500  verifyFormat("enum {\n"
501               "};");
502}
503
504TEST_F(FormatTest, FormatsBitfields) {
505  verifyFormat("struct Bitfields {\n"
506               "  unsigned sClass : 8;\n"
507               "  unsigned ValueKind : 2;\n"
508               "};");
509}
510
511TEST_F(FormatTest, FormatsNamespaces) {
512  verifyFormat("namespace some_namespace {\n"
513               "class A {};\n"
514               "void f() { f(); }\n"
515               "}");
516  verifyFormat("namespace {\n"
517               "class A {};\n"
518               "void f() { f(); }\n"
519               "}");
520  verifyFormat("inline namespace X {\n"
521               "class A {};\n"
522               "void f() { f(); }\n"
523               "}");
524  verifyFormat("using namespace some_namespace;\n"
525               "class A {};\n"
526               "void f() { f(); }");
527}
528
529TEST_F(FormatTest, FormatTryCatch) {
530  // FIXME: Handle try-catch explicitly in the UnwrappedLineParser, then we'll
531  // also not create single-line-blocks.
532  verifyFormat("try {\n"
533               "  throw a * b;\n"
534               "}\n"
535               "catch (int a) {\n"
536               "  // Do nothing.\n"
537               "}\n"
538               "catch (...) {\n"
539               "  exit(42);\n"
540               "}");
541
542  // Function-level try statements.
543  verifyFormat("int f() try { return 4; }\n"
544               "catch (...) {\n"
545               "  return 5;\n"
546               "}");
547  verifyFormat("class A {\n"
548               "  int a;\n"
549               "  A() try : a(0) {}\n"
550               "  catch (...) {\n"
551               "    throw;\n"
552               "  }\n"
553               "};\n");
554}
555
556TEST_F(FormatTest, FormatObjCTryCatch) {
557  verifyFormat("@try {\n"
558               "  f();\n"
559               "}\n"
560               "@catch (NSException e) {\n"
561               "  @throw;\n"
562               "}\n"
563               "@finally {\n"
564               "  exit(42);\n"
565               "}");
566}
567
568TEST_F(FormatTest, StaticInitializers) {
569  verifyFormat("static SomeClass SC = { 1, 'a' };");
570
571  // FIXME: Format like enums if the static initializer does not fit on a line.
572  verifyFormat(
573      "static SomeClass WithALoooooooooooooooooooongName = {\n"
574      "  100000000, \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
575      "};");
576
577  verifyFormat(
578      "static SomeClass = { a, b, c, d, e, f, g, h, i, j,\n"
579      "                     looooooooooooooooooooooooooooooooooongname,\n"
580      "                     looooooooooooooooooooooooooooooong };");
581}
582
583TEST_F(FormatTest, NestedStaticInitializers) {
584  verifyFormat("static A x = { { {} } };\n");
585  verifyFormat(
586      "static A x = { { { init1, init2, init3, init4 },\n"
587      "                 { init1, init2, init3, init4 } } };");
588
589  // FIXME: Fix this in general and verify that it works in LLVM style again.
590  verifyGoogleFormat(
591      "somes Status::global_reps[3] = {\n"
592      "  { kGlobalRef, OK_CODE, NULL, NULL, NULL },\n"
593      "  { kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL },\n"
594      "  { kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL }\n"
595      "};");
596  verifyFormat(
597      "CGRect cg_rect = { { rect.fLeft, rect.fTop },\n"
598      "                   { rect.fRight - rect.fLeft, rect.fBottom - rect.fTop"
599      " } };");
600
601  // FIXME: We might at some point want to handle this similar to parameter
602  // lists, where we have an option to put each on a single line.
603  verifyFormat("struct {\n"
604               "  unsigned bit;\n"
605               "  const char *const name;\n"
606               "} kBitsToOs[] = { { kOsMac, \"Mac\" }, { kOsWin, \"Windows\" },\n"
607               "                  { kOsLinux, \"Linux\" }, { kOsCrOS, \"Chrome OS\" } };");
608}
609
610TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
611  verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
612               "                      \\\n"
613               "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
614}
615
616TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
617  verifyFormat("virtual void write(ELFWriter *writerrr,\n"
618               "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
619}
620
621TEST_F(FormatTest, BreaksOnHashWhenDirectiveIsInvalid) {
622  EXPECT_EQ("#\n;", format("#;"));
623  verifyFormat("#\n;\n;\n;");
624}
625
626TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
627  EXPECT_EQ("#line 42 \"test\"\n",
628            format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
629  EXPECT_EQ("#define A B\n",
630            format("#  \\\n define  \\\n    A  \\\n       B\n",
631                   getLLVMStyleWithColumns(12)));
632}
633
634TEST_F(FormatTest, EndOfFileEndsPPDirective) {
635  EXPECT_EQ("#line 42 \"test\"",
636            format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
637  EXPECT_EQ("#define A B",
638            format("#  \\\n define  \\\n    A  \\\n       B"));
639}
640
641TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
642  // If the macro fits in one line, we still do not get the full
643  // line, as only the next line decides whether we need an escaped newline and
644  // thus use the last column.
645  verifyFormat("#define A(B)", getLLVMStyleWithColumns(13));
646
647  verifyFormat("#define A( \\\n    B)", getLLVMStyleWithColumns(12));
648  verifyFormat("#define AA(\\\n    B)", getLLVMStyleWithColumns(12));
649  verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
650
651  verifyFormat("#define A A\n#define A A");
652  verifyFormat("#define A(X) A\n#define A A");
653
654  verifyFormat("#define Something Other", getLLVMStyleWithColumns(24));
655  verifyFormat("#define Something     \\\n"
656               "  Other", getLLVMStyleWithColumns(23));
657}
658
659TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
660  EXPECT_EQ("// some comment\n"
661            "#include \"a.h\"\n"
662            "#define A(A,\\\n"
663            "          B)\n"
664            "#include \"b.h\"\n"
665            "// some comment\n",
666            format("  // some comment\n"
667                   "  #include \"a.h\"\n"
668                   "#define A(A,\\\n"
669                   "    B)\n"
670                   "    #include \"b.h\"\n"
671                   " // some comment\n", getLLVMStyleWithColumns(13)));
672}
673
674TEST_F(FormatTest, LayoutSingleHash) {
675  EXPECT_EQ("#\na;", format("#\na;"));
676}
677
678TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
679  EXPECT_EQ("#define A    \\\n"
680            "  c;         \\\n"
681            "  e;\n"
682            "f;", format("#define A c; e;\n"
683                         "f;", getLLVMStyleWithColumns(14)));
684}
685
686TEST_F(FormatTest, LayoutRemainingTokens) {
687  EXPECT_EQ("{}", format("{}"));
688}
689
690TEST_F(FormatTest, LayoutSingleUnwrappedLineInMacro) {
691  EXPECT_EQ("# define A\\\n  b;",
692            format("# define A b;", 11, 2, getLLVMStyleWithColumns(11)));
693}
694
695TEST_F(FormatTest, MacroDefinitionInsideStatement) {
696  EXPECT_EQ("int x,\n"
697            "#define A\n"
698            "    y;", format("int x,\n#define A\ny;"));
699}
700
701TEST_F(FormatTest, HashInMacroDefinition) {
702  verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
703  verifyFormat("#define A \\\n"
704               "  {       \\\n"
705               "    f(#c);\\\n"
706               "  }", getLLVMStyleWithColumns(11));
707
708  verifyFormat("#define A(X)         \\\n"
709               "  void function##X()", getLLVMStyleWithColumns(22));
710
711  verifyFormat("#define A(a, b, c)   \\\n"
712               "  void a##b##c()", getLLVMStyleWithColumns(22));
713
714  verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
715}
716
717TEST_F(FormatTest, IndentPreprocessorDirectivesAtZero) {
718  EXPECT_EQ("{\n  {\n#define A\n  }\n}", format("{{\n#define A\n}}"));
719}
720
721TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
722  verifyFormat("{\n  { a #c; }\n}");
723}
724
725TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
726  EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
727            format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
728  EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
729            format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
730}
731
732TEST_F(FormatTest, EscapedNewlineAtStartOfTokenInMacroDefinition) {
733  EXPECT_EQ(
734      "#define A \\\n  int i;  \\\n  int j;",
735      format("#define A \\\nint i;\\\n  int j;", getLLVMStyleWithColumns(11)));
736}
737
738TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
739  verifyFormat("#define A \\\n"
740               "  int v(  \\\n"
741               "      a); \\\n"
742               "  int i;", getLLVMStyleWithColumns(11));
743}
744
745TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
746  EXPECT_EQ(
747      "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
748      "                      \\\n"
749      "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
750      "\n"
751      "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
752      "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
753      format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
754             "\\\n"
755             "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
756             "  \n"
757             "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
758             "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
759}
760
761TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
762  EXPECT_EQ("int\n"
763            "#define A\n"
764            "    a;",
765            format("int\n#define A\na;"));
766  verifyFormat(
767      "functionCallTo(someOtherFunction(\n"
768      "    withSomeParameters, whichInSequence,\n"
769      "    areLongerThanALine(andAnotherCall,\n"
770      "#define A B\n"
771      "                       withMoreParamters,\n"
772      "                       whichStronglyInfluenceTheLayout),\n"
773      "    andMoreParameters), trailing);", getLLVMStyleWithColumns(69));
774}
775
776TEST_F(FormatTest, LayoutBlockInsideParens) {
777  EXPECT_EQ("functionCall({\n"
778            "  int i;\n"
779            "});", format(" functionCall ( {int i;} );"));
780}
781
782TEST_F(FormatTest, LayoutBlockInsideStatement) {
783  EXPECT_EQ("SOME_MACRO { int i; }\n"
784            "int i;", format("  SOME_MACRO  {int i;}  int i;"));
785}
786
787TEST_F(FormatTest, LayoutNestedBlocks) {
788  verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
789               "  struct s {\n"
790               "    int i;\n"
791               "  };\n"
792               "  s kBitsToOs[] = { { 10 } };\n"
793               "  for (int i = 0; i < 10; ++i)\n"
794               "    return;\n"
795               "}");
796}
797
798TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
799  EXPECT_EQ("{}", format("{}"));
800}
801
802//===----------------------------------------------------------------------===//
803// Line break tests.
804//===----------------------------------------------------------------------===//
805
806TEST_F(FormatTest, FormatsFunctionDefinition) {
807  verifyFormat("void f(int a, int b, int c, int d, int e, int f, int g,"
808               " int h, int j, int f,\n"
809               "       int c, int ddddddddddddd) {}");
810}
811
812TEST_F(FormatTest, FormatsAwesomeMethodCall) {
813  verifyFormat(
814      "SomeLongMethodName(SomeReallyLongMethod(\n"
815      "    CallOtherReallyLongMethod(parameter, parameter, parameter)),\n"
816      "                   SecondLongCall(parameter));");
817}
818
819TEST_F(FormatTest, ConstructorInitializers) {
820  verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
821  verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
822               getLLVMStyleWithColumns(45));
823  verifyFormat("Constructor()\n"
824               "    : Inttializer(FitsOnTheLine) {}",
825               getLLVMStyleWithColumns(44));
826
827  verifyFormat(
828      "SomeClass::Constructor()\n"
829      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
830
831  verifyFormat(
832      "SomeClass::Constructor()\n"
833      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
834      "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
835  verifyGoogleFormat(
836      "SomeClass::Constructor()\n"
837      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
838      "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
839      "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
840  verifyGoogleFormat(
841      "SomeClass::Constructor()\n"
842      "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),  // Some comment\n"
843      "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
844      "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
845
846  verifyFormat(
847      "SomeClass::Constructor()\n"
848      "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
849      "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
850
851  verifyFormat("Constructor()\n"
852               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
853               "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
854               "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
855               "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
856
857  // Here a line could be saved by splitting the second initializer onto two
858  // lines, but that is not desireable.
859  verifyFormat("Constructor()\n"
860               "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
861               "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
862               "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
863
864  verifyGoogleFormat("MyClass::MyClass(int var)\n"
865                     "    : some_var_(var),             // 4 space indent\n"
866                     "      some_other_var_(var + 1) {  // lined up\n"
867                     "}");
868
869  // This test takes VERY long when memoization is broken.
870  std::string input = "Constructor()\n"
871                 "    : aaaa(a,\n";
872  for (unsigned i = 0, e = 80; i != e; ++i) {
873    input += "           a,\n";
874  }
875  input += "           a) {}";
876  verifyGoogleFormat(input);
877}
878
879TEST_F(FormatTest, BreaksAsHighAsPossible) {
880  verifyFormat(
881      "if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
882      "    (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
883      "  f();");
884}
885
886TEST_F(FormatTest, BreaksDesireably) {
887  verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
888               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
889               "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {}");
890
891  verifyFormat(
892      "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
893      "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
894
895  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
896               "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
897               "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
898
899  verifyFormat(
900      "aaaaaaaa(aaaaaaaaaaaaa, aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
901      "                            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
902      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
903      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
904
905  verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
906               "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
907
908  verifyFormat(
909      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
910      "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
911
912  // This test case breaks on an incorrect memoization, i.e. an optimization not
913  // taking into account the StopAt value.
914  verifyFormat(
915      "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
916      "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
917      "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
918      "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
919
920  verifyFormat("{\n  {\n    {\n"
921               "      Annotation.SpaceRequiredBefore =\n"
922               "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
923               "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
924               "    }\n  }\n}");
925}
926
927TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
928  verifyGoogleFormat(
929      "aaaaaaaa(aaaaaaaaaaaaa,\n"
930      "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
931      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
932      "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
933      "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
934  verifyGoogleFormat(
935      "aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa)\n"
936      "    .aaaaaaaaaaaaaaaaaa();");
937  verifyGoogleFormat(
938      "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
939      "                               ddddddddddddddddddddddddddddd),\n"
940      "             test);");
941
942  verifyGoogleFormat(
943      "std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
944      "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
945      "            aaaaaaaaaaaaaaaaaaaaaaa> aaaaaaaaaaaaaaaaaa;");
946  verifyGoogleFormat("a(\"a\"\n"
947                     "  \"a\",\n"
948                     "  a);");
949}
950
951TEST_F(FormatTest, FormatsBuilderPattern) {
952  verifyFormat(
953      "return llvm::StringSwitch<Reference::Kind>(name)\n"
954      "       .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
955      "       .StartsWith(\".eh_frame\", ORDER_EH_FRAME).StartsWith(\".init\", ORDER_INIT)\n"
956      "       .StartsWith(\".fini\", ORDER_FINI).StartsWith(\".hash\", ORDER_HASH)\n"
957      "       .Default(ORDER_TEXT);\n");
958}
959
960TEST_F(FormatTest, DoesNotBreakTrailingAnnotation) {
961  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
962               "    GUARDED_BY(aaaaaaaaaaaaa);");
963  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
964               "    GUARDED_BY(aaaaaaaaaaaaa);");
965  verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
966               "    GUARDED_BY(aaaaaaaaaaaaa) {}");
967}
968
969TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
970  verifyFormat(
971      "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
972      "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {}");
973  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
974               "    ccccccccccccccccccccccccc) {}");
975  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
976               "    ccccccccccccccccccccccccc) {}");
977  verifyFormat(
978      "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
979      "    ccccccccccccccccccccccccc) {}");
980}
981
982TEST_F(FormatTest, PrefersNotToBreakAfterAssignments) {
983  verifyFormat(
984      "unsigned Cost = TTI.getMemoryOpCost(I->getOpcode(), VectorTy,\n"
985      "                                    SI->getAlignment(),\n"
986      "                                    SI->getPointerAddressSpaceee());\n");
987  verifyFormat(
988      "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
989      "                                Line.Tokens.front().Tok.getLocation(),\n"
990      "                                Line.Tokens.back().Tok.getLocation());");
991}
992
993TEST_F(FormatTest, AlignsAfterAssignments) {
994  verifyFormat(
995      "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
996      "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
997  verifyFormat(
998      "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
999      "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
1000  verifyFormat(
1001      "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
1002      "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
1003  verifyFormat(
1004      "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
1005      "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
1006  verifyFormat(
1007      "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
1008      "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
1009      "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
1010}
1011
1012TEST_F(FormatTest, AlignsAfterReturn) {
1013  verifyFormat(
1014      "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
1015      "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
1016  verifyFormat(
1017      "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
1018      "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
1019}
1020
1021TEST_F(FormatTest, BreaksConditionalExpressions) {
1022  verifyFormat(
1023      "aaaa(aaaaaaaaaaaaaaaaaaaa,\n"
1024      "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
1025      "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1026  verifyFormat("aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
1027               "         aaaaaaaaaaaaaaaaaaaaaaa : aaaaaaaaaaaaaaaaaaaaa);");
1028  verifyFormat(
1029      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
1030      "                                   aaaaaaaaaaaaa);");
1031}
1032
1033TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
1034  verifyFormat("arr[foo ? bar : baz];");
1035  verifyFormat("f()[foo ? bar : baz];");
1036  verifyFormat("(a + b)[foo ? bar : baz];");
1037  verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
1038}
1039
1040TEST_F(FormatTest, AlignsStringLiterals) {
1041  verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
1042               "                                      \"short literal\");");
1043  verifyFormat(
1044      "looooooooooooooooooooooooongFunction(\n"
1045      "    \"short literal\"\n"
1046      "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
1047}
1048
1049TEST_F(FormatTest, AlignsPipes) {
1050  verifyFormat(
1051      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1052      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1053      "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
1054  verifyFormat(
1055      "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
1056      "                     << aaaaaaaaaaaaaaaaaaaa;");
1057  verifyFormat(
1058      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1059      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
1060  verifyFormat(
1061      "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
1062      "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
1063      "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
1064  verifyFormat(
1065      "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
1066      "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
1067      "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
1068}
1069
1070TEST_F(FormatTest, UnderstandsEquals) {
1071  verifyFormat(
1072      "aaaaaaaaaaaaaaaaa =\n"
1073      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
1074  verifyFormat(
1075      "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
1076      "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
1077  verifyFormat(
1078      "if (a) {\n"
1079      "  f();\n"
1080      "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
1081      "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
1082
1083  verifyFormat(
1084      // FIXME: Does an expression like this ever make sense? If yes, fix.
1085      "if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 100000000 +\n"
1086      "    10000000) {}");
1087}
1088
1089TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
1090  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
1091               "    .looooooooooooooooooooooooooooooooooooooongFunction();");
1092
1093  verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
1094               "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
1095
1096  verifyFormat(
1097      "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
1098      "                                                          Parameter2);");
1099
1100  verifyFormat(
1101      "ShortObject->shortFunction(\n"
1102      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
1103      "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
1104
1105  verifyFormat("loooooooooooooongFunction(\n"
1106               "    LoooooooooooooongObject->looooooooooooooooongFunction());");
1107
1108  verifyFormat(
1109      "function(LoooooooooooooooooooooooooooooooooooongObject\n"
1110      "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
1111
1112  // Here, it is not necessary to wrap at "." or "->".
1113  verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
1114               "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
1115  verifyFormat(
1116      "aaaaaaaaaaa->aaaaaaaaa(\n"
1117      "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
1118      "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
1119}
1120
1121TEST_F(FormatTest, WrapsTemplateDeclarations) {
1122  verifyFormat("template <typename T>\n"
1123               "virtual void loooooooooooongFunction(int Param1, int Param2);");
1124  verifyFormat(
1125      "template <typename T>\n"
1126      "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
1127      "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
1128  verifyFormat(
1129      "template <typename T>\n"
1130      "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
1131      "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
1132  verifyFormat(
1133      "template <typename T>\n"
1134      "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
1135      "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
1136      "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1137  verifyFormat("template <typename T>\n"
1138               "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1139               "    int aaaaaaaaaaaaaaaaa);");
1140  verifyFormat(
1141      "template <typename T1, typename T2 = char, typename T3 = char,\n"
1142      "          typename T4 = char>\n"
1143      "void f();");
1144}
1145
1146TEST_F(FormatTest, UnderstandsTemplateParameters) {
1147  verifyFormat("A<int> a;");
1148  verifyFormat("A<A<A<int> > > a;");
1149  verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
1150  verifyFormat("bool x = a < 1 || 2 > a;");
1151  verifyFormat("bool x = 5 < f<int>();");
1152  verifyFormat("bool x = f<int>() > 5;");
1153  verifyFormat("bool x = 5 < a<int>::x;");
1154  verifyFormat("bool x = a < 4 ? a > 2 : false;");
1155  verifyFormat("bool x = f() ? a < 2 : a > 2;");
1156
1157  verifyGoogleFormat("A<A<int>> a;");
1158  verifyGoogleFormat("A<A<A<int>>> a;");
1159  verifyGoogleFormat("A<A<A<A<int>>>> a;");
1160
1161  verifyFormat("test >> a >> b;");
1162  verifyFormat("test << a >> b;");
1163
1164  verifyFormat("f<int>();");
1165  verifyFormat("template <typename T> void f() {}");
1166}
1167
1168TEST_F(FormatTest, UnderstandsUnaryOperators) {
1169  verifyFormat("int a = -2;");
1170  verifyFormat("f(-1, -2, -3);");
1171  verifyFormat("a[-1] = 5;");
1172  verifyFormat("int a = 5 + -2;");
1173  verifyFormat("if (i == -1) {}");
1174  verifyFormat("if (i != -1) {}");
1175  verifyFormat("if (i > -1) {}");
1176  verifyFormat("if (i < -1) {}");
1177  verifyFormat("++(a->f());");
1178  verifyFormat("--(a->f());");
1179  verifyFormat("(a->f())++;");
1180  verifyFormat("a[42]++;");
1181  verifyFormat("if (!(a->f())) {}");
1182
1183  verifyFormat("a-- > b;");
1184  verifyFormat("b ? -a : c;");
1185  verifyFormat("n * sizeof char16;");
1186  verifyFormat("n * alignof char16;");
1187  verifyFormat("sizeof(char);");
1188  verifyFormat("alignof(char);");
1189
1190  verifyFormat("return -1;");
1191  verifyFormat("switch (a) {\n"
1192               "case -1:\n"
1193               "  break;\n"
1194               "}");
1195
1196  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { -5, +3 };");
1197  verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = { +5, -3 };");
1198
1199  verifyFormat("int a = /* confusing comment */ -1;");
1200  // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
1201  verifyFormat("int a = i /* confusing comment */++;");
1202}
1203
1204TEST_F(FormatTest, UndestandsOverloadedOperators) {
1205  verifyFormat("bool operator<();");
1206  verifyFormat("bool operator>();");
1207  verifyFormat("bool operator=();");
1208  verifyFormat("bool operator==();");
1209  verifyFormat("bool operator!=();");
1210  verifyFormat("int operator+();");
1211  verifyFormat("int operator++();");
1212  verifyFormat("bool operator();");
1213  verifyFormat("bool operator()();");
1214  verifyFormat("bool operator[]();");
1215  verifyFormat("operator bool();");
1216  verifyFormat("operator SomeType<int>();");
1217  verifyFormat("void *operator new(std::size_t size);");
1218  verifyFormat("void *operator new[](std::size_t size);");
1219  verifyFormat("void operator delete(void *ptr);");
1220  verifyFormat("void operator delete[](void *ptr);");
1221}
1222
1223TEST_F(FormatTest, UnderstandsNewAndDelete) {
1224  verifyFormat("A *a = new A;");
1225  verifyFormat("A *a = new (placement) A;");
1226  verifyFormat("delete a;");
1227  verifyFormat("delete (A *)a;");
1228}
1229
1230TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
1231  verifyFormat("int *f(int *a) {}");
1232  verifyFormat("f(a, *a);");
1233  verifyFormat("f(*a);");
1234  verifyFormat("int a = b * 10;");
1235  verifyFormat("int a = 10 * b;");
1236  verifyFormat("int a = b * c;");
1237  verifyFormat("int a += b * c;");
1238  verifyFormat("int a -= b * c;");
1239  verifyFormat("int a *= b * c;");
1240  verifyFormat("int a /= b * c;");
1241  verifyFormat("int a = *b;");
1242  verifyFormat("int a = *b * c;");
1243  verifyFormat("int a = b * *c;");
1244  verifyFormat("int main(int argc, char **argv) {}");
1245  verifyFormat("return 10 * b;");
1246  verifyFormat("return *b * *c;");
1247  verifyFormat("return a & ~b;");
1248  verifyFormat("f(b ? *c : *d);");
1249  verifyFormat("int a = b ? *c : *d;");
1250  verifyFormat("*b = a;");
1251  verifyFormat("a * ~b;");
1252  verifyFormat("a * !b;");
1253  verifyFormat("a * +b;");
1254  verifyFormat("a * -b;");
1255  verifyFormat("a * ++b;");
1256  verifyFormat("a * --b;");
1257  verifyFormat("a[4] * b;");
1258  verifyFormat("f() * b;");
1259  verifyFormat("a * [self dostuff];");
1260  verifyFormat("a * (a + b);");
1261  verifyFormat("(a *)(a + b);");
1262  verifyFormat("int *pa = (int *)&a;");
1263
1264  verifyFormat("InvalidRegions[*R] = 0;");
1265
1266  verifyFormat("A<int *> a;");
1267  verifyFormat("A<int **> a;");
1268  verifyFormat("A<int *, int *> a;");
1269  verifyFormat("A<int **, int **> a;");
1270
1271  verifyFormat(
1272      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1273      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
1274
1275  verifyGoogleFormat("int main(int argc, char** argv) {}");
1276  verifyGoogleFormat("A<int*> a;");
1277  verifyGoogleFormat("A<int**> a;");
1278  verifyGoogleFormat("A<int*, int*> a;");
1279  verifyGoogleFormat("A<int**, int**> a;");
1280  verifyGoogleFormat("f(b ? *c : *d);");
1281  verifyGoogleFormat("int a = b ? *c : *d;");
1282  verifyGoogleFormat("Type* t = **x;");
1283  verifyGoogleFormat("Type* t = *++*x;");
1284  verifyGoogleFormat("*++*x;");
1285  verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
1286  verifyGoogleFormat("Type* t = x++ * y;");
1287
1288  verifyFormat("a = *(x + y);");
1289  verifyFormat("a = &(x + y);");
1290  verifyFormat("*(x + y).call();");
1291  verifyFormat("&(x + y)->call();");
1292  verifyFormat("&(*I).first");
1293
1294  verifyFormat("f(b * /* confusing comment */ ++c);");
1295  verifyFormat(
1296      "int *MyValues = {\n"
1297      "  *A, // Operator detection might be confused by the '{'\n"
1298      "  *BB // Operator detection might be confused by previous comment\n"
1299      "};");
1300
1301  verifyFormat("if (int *a = &b)");
1302  verifyFormat("if (int &a = *b)");
1303  verifyFormat("if (a & b[i])");
1304  verifyFormat("if (a::b::c::d & b[i])");
1305  verifyFormat("if (*b[i])");
1306  verifyFormat("if (int *a = (&b))");
1307  verifyFormat("while (int *a = &b)");
1308}
1309
1310TEST_F(FormatTest, FormatsCasts) {
1311  verifyFormat("Type *A = static_cast<Type *>(P);");
1312  verifyFormat("Type *A = (Type *)P;");
1313  verifyFormat("Type *A = (vector<Type *, int *>)P;");
1314  verifyFormat("int a = (int)(2.0f);");
1315
1316  // FIXME: These also need to be identified.
1317  verifyFormat("int a = (int) 2.0f;");
1318  verifyFormat("int a = (int) * b;");
1319
1320  // These are not casts.
1321  verifyFormat("void f(int *) {}");
1322  verifyFormat("void f(int *);");
1323  verifyFormat("void f(int *) = 0;");
1324  verifyFormat("void f(SmallVector<int>) {}");
1325  verifyFormat("void f(SmallVector<int>);");
1326  verifyFormat("void f(SmallVector<int>) = 0;");
1327}
1328
1329TEST_F(FormatTest, FormatsFunctionTypes) {
1330  // FIXME: Determine the cases that need a space after the return type and fix.
1331  verifyFormat("A<bool()> a;");
1332  verifyFormat("A<SomeType()> a;");
1333  verifyFormat("A<void(*)(int, std::string)> a;");
1334
1335  verifyFormat("int(*func)(void *);");
1336}
1337
1338TEST_F(FormatTest, DoesNotBreakBeforePointerOrReference) {
1339  verifyFormat("int *someFunction(int LoooooooooooooooongParam1,\n"
1340               "                  int LoooooooooooooooongParam2) {}");
1341  verifyFormat(
1342      "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
1343      "                                   SourceLocation L, IdentifierIn *II,\n"
1344      "                                   Type *T) {}");
1345}
1346
1347TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
1348  verifyFormat("(a)->b();");
1349  verifyFormat("--a;");
1350}
1351
1352TEST_F(FormatTest, HandlesIncludeDirectives) {
1353  verifyFormat("#include <string>\n"
1354               "#include <a/b/c.h>\n"
1355               "#include \"a/b/string\"\n"
1356               "#include \"string.h\"\n"
1357               "#include \"string.h\"\n"
1358               "#include <a-a>\n"
1359               "#include < path with space >\n");
1360
1361  verifyFormat("#import <string>");
1362  verifyFormat("#import <a/b/c.h>");
1363  verifyFormat("#import \"a/b/string\"");
1364  verifyFormat("#import \"string.h\"");
1365  verifyFormat("#import \"string.h\"");
1366}
1367
1368//===----------------------------------------------------------------------===//
1369// Error recovery tests.
1370//===----------------------------------------------------------------------===//
1371
1372TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
1373  verifyFormat("void f() { return; }\n42");
1374  verifyFormat("void f() {\n"
1375               "  if (0)\n"
1376               "    return;\n"
1377               "}\n"
1378               "42");
1379  verifyFormat("void f() { return }\n42");
1380  verifyFormat("void f() {\n"
1381               "  if (0)\n"
1382               "    return\n"
1383               "}\n"
1384               "42");
1385}
1386
1387TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
1388  EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
1389  EXPECT_EQ("void f() {\n"
1390            "  if (a)\n"
1391            "    return\n"
1392            "}", format("void  f  (  )  {  if  ( a )  return  }"));
1393  EXPECT_EQ("namespace N { void f() }", format("namespace  N  {  void f()  }"));
1394  EXPECT_EQ("namespace N {\n"
1395            "void f() {}\n"
1396            "void g()\n"
1397            "}", format("namespace N  { void f( ) { } void g( ) }"));
1398}
1399
1400TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
1401  verifyFormat("int aaaaaaaa =\n"
1402               "    // Overly long comment\n"
1403               "    b;", getLLVMStyleWithColumns(20));
1404  verifyFormat("function(\n"
1405               "    ShortArgument,\n"
1406               "    LoooooooooooongArgument);\n", getLLVMStyleWithColumns(20));
1407}
1408
1409TEST_F(FormatTest, IncorrectAccessSpecifier) {
1410  verifyFormat("public:");
1411  verifyFormat("class A {\n"
1412               "public\n"
1413               "  void f() {}\n"
1414               "};");
1415  verifyFormat("public\n"
1416               "int qwerty;");
1417  verifyFormat("public\n"
1418               "B {}");
1419  verifyFormat("public\n"
1420               "{}");
1421  verifyFormat("public\n"
1422               "B { int x; }");
1423}
1424
1425TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
1426  verifyFormat("{");
1427}
1428
1429TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
1430  verifyFormat("do {}");
1431  verifyFormat("do {}\n"
1432               "f();");
1433  verifyFormat("do {}\n"
1434               "wheeee(fun);");
1435  verifyFormat("do {\n"
1436               "  f();\n"
1437               "}");
1438}
1439
1440TEST_F(FormatTest, IncorrectCodeMissingParens) {
1441  verifyFormat("if {\n  foo;\n  foo();\n}");
1442  verifyFormat("switch {\n  foo;\n  foo();\n}");
1443  verifyFormat("for {\n  foo;\n  foo();\n}");
1444  verifyFormat("while {\n  foo;\n  foo();\n}");
1445  verifyFormat("do {\n  foo;\n  foo();\n} while;");
1446}
1447
1448TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
1449  verifyFormat("namespace {\n"
1450               "class Foo {  Foo  ( }; }  // comment");
1451}
1452
1453TEST_F(FormatTest, IncorrectCodeErrorDetection) {
1454  EXPECT_EQ("{\n{}\n", format("{\n{\n}\n"));
1455  EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
1456  EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
1457  EXPECT_EQ("{\n  {}\n  }\n}\n", format("{\n  {\n    }\n  }\n}\n"));
1458
1459  EXPECT_EQ("{\n"
1460            "    {\n"
1461            " breakme(\n"
1462            "     qwe);\n"
1463            "}\n", format("{\n"
1464                          "    {\n"
1465                          " breakme(qwe);\n"
1466                          "}\n", getLLVMStyleWithColumns(10)));
1467}
1468
1469TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
1470  verifyFormat(
1471      "int x = {\n"
1472      "  avariable,\n"
1473      "  b(alongervariable)\n"
1474      "};", getLLVMStyleWithColumns(25));
1475}
1476
1477TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
1478  verifyFormat("return (a)(b) { 1, 2, 3 };");
1479}
1480
1481TEST_F(FormatTest, LayoutTokensFollowingBlockInParentheses) {
1482  verifyFormat(
1483      "Aaa({\n"
1484      "  int i;\n"
1485      "}, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
1486      "                                    ccccccccccccccccc));");
1487}
1488
1489TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
1490  verifyFormat("void f() { return 42; }");
1491  verifyFormat("void f() {\n"
1492               "  // Comment\n"
1493               "}");
1494  verifyFormat("{\n"
1495               "#error {\n"
1496               "  int a;\n"
1497               "}");
1498  verifyFormat("{\n"
1499               "  int a;\n"
1500               "#error {\n"
1501               "}");
1502}
1503
1504TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
1505  // Elaborate type variable declarations.
1506  verifyFormat("struct foo a = { bar };\nint n;");
1507  verifyFormat("class foo a = { bar };\nint n;");
1508  verifyFormat("union foo a = { bar };\nint n;");
1509
1510  // Elaborate types inside function definitions.
1511  verifyFormat("struct foo f() {}\nint n;");
1512  verifyFormat("class foo f() {}\nint n;");
1513  verifyFormat("union foo f() {}\nint n;");
1514
1515  // Templates.
1516  verifyFormat("template <class X> void f() {}\nint n;");
1517  verifyFormat("template <struct X> void f() {}\nint n;");
1518  verifyFormat("template <union X> void f() {}\nint n;");
1519
1520  // Actual definitions...
1521  verifyFormat("struct {} n;");
1522  verifyFormat("template <template <class T, class Y>, class Z > class X {} n;");
1523  verifyFormat("union Z {\n  int n;\n} x;");
1524  verifyFormat("class MACRO Z {} n;");
1525  verifyFormat("class MACRO(X) Z {} n;");
1526  verifyFormat("class __attribute__(X) Z {} n;");
1527  verifyFormat("class __declspec(X) Z {} n;");
1528
1529  // Elaborate types where incorrectly parsing the structural element would
1530  // break the indent.
1531  verifyFormat("if (true)\n"
1532               "  class X x;\n"
1533               "else\n"
1534               "  f();\n");
1535}
1536
1537TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
1538  verifyFormat("#error Leave     all         white!!!!! space* alone!\n");
1539  verifyFormat("#warning Leave     all         white!!!!! space* alone!\n");
1540  EXPECT_EQ("#error 1", format("  #  error   1"));
1541  EXPECT_EQ("#warning 1", format("  #  warning 1"));
1542}
1543
1544TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
1545  FormatStyle AllowsMergedIf = getGoogleStyle();
1546  AllowsMergedIf.AllowShortIfStatementsOnASingleLine = true;
1547  verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
1548  verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
1549  verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
1550  EXPECT_EQ("if (true) return 42;",
1551            format("if (true)\nreturn 42;", AllowsMergedIf));
1552  FormatStyle ShortMergedIf = AllowsMergedIf;
1553  ShortMergedIf.ColumnLimit = 25;
1554  verifyFormat("#define A               \\\n"
1555               "  if (true) return 42;", ShortMergedIf);
1556  verifyFormat("#define A               \\\n"
1557               "  f();                  \\\n"
1558               "  if (true)\n"
1559               "#define B", ShortMergedIf);
1560  verifyFormat("#define A               \\\n"
1561               "  f();                  \\\n"
1562               "  if (true)\n"
1563               "g();", ShortMergedIf);
1564}
1565
1566//===----------------------------------------------------------------------===//
1567// Objective-C tests.
1568//===----------------------------------------------------------------------===//
1569
1570TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
1571  verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
1572  EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
1573            format("-(NSUInteger)indexOfObject:(id)anObject;"));
1574  EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
1575  EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
1576  EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
1577            format("-(NSInteger)Method3:(id)anObject;"));
1578  EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
1579            format("-(NSInteger)Method4:(id)anObject;"));
1580  EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
1581            format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
1582  EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
1583            format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
1584  EXPECT_EQ(
1585      "- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;",
1586      format("- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;"));
1587
1588  // Very long objectiveC method declaration.
1589  EXPECT_EQ(
1590      "- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range\n    "
1591      "outRange:(NSRange)out_range outRange1:(NSRange)out_range1\n    "
1592      "outRange2:(NSRange)out_range2 outRange3:(NSRange)out_range3\n    "
1593      "outRange4:(NSRange)out_range4 outRange5:(NSRange)out_range5\n    "
1594      "outRange6:(NSRange)out_range6 outRange7:(NSRange)out_range7\n    "
1595      "outRange8:(NSRange)out_range8 outRange9:(NSRange)out_range9;",
1596      format(
1597          "- (NSUInteger)indexOfObject:(id)anObject inRange:(NSRange)range "
1598          "outRange:(NSRange) out_range outRange1:(NSRange) out_range1 "
1599          "outRange2:(NSRange) out_range2  outRange3:(NSRange) out_range3  "
1600          "outRange4:(NSRange) out_range4  outRange5:(NSRange) out_range5 "
1601          "outRange6:(NSRange) out_range6  outRange7:(NSRange) out_range7  "
1602          "outRange8:(NSRange) out_range8  outRange9:(NSRange) out_range9;"));
1603
1604  verifyFormat("- (int)sum:(vector<int>)numbers;");
1605  verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
1606  // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
1607  // protocol lists (but not for template classes):
1608  //verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
1609
1610  verifyFormat("- (int(*)())foo:(int(*)())f;");
1611  verifyGoogleFormat("- (int(*)())foo:(int(*)())foo;");
1612
1613  // If there's no return type (very rare in practice!), LLVM and Google style
1614  // agree.
1615  verifyFormat("- foo:(int)f;");
1616  verifyGoogleFormat("- foo:(int)foo;");
1617}
1618
1619TEST_F(FormatTest, FormatObjCBlocks) {
1620  verifyFormat("int (^Block)(int, int);");
1621  verifyFormat("int (^Block1)(int, int) = ^(int i, int j)");
1622}
1623
1624TEST_F(FormatTest, FormatObjCInterface) {
1625  // FIXME: Handle comments like in "@interface /* wait for it */ Foo", PR14875
1626  verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
1627               "@public\n"
1628               "  int field1;\n"
1629               "@protected\n"
1630               "  int field2;\n"
1631               "@private\n"
1632               "  int field3;\n"
1633               "@package\n"
1634               "  int field4;\n"
1635               "}\n"
1636               "+ (id)init;\n"
1637               "@end");
1638
1639  verifyGoogleFormat("@interface Foo : NSObject<NSSomeDelegate> {\n"
1640                     " @public\n"
1641                     "  int field1;\n"
1642                     " @protected\n"
1643                     "  int field2;\n"
1644                     " @private\n"
1645                     "  int field3;\n"
1646                     " @package\n"
1647                     "  int field4;\n"
1648                     "}\n"
1649                     "+ (id)init;\n"
1650                     "@end");
1651
1652  verifyFormat("@interface Foo\n"
1653               "+ (id)init;\n"
1654               "// Look, a comment!\n"
1655               "- (int)answerWith:(int)i;\n"
1656               "@end");
1657
1658  verifyFormat("@interface Foo\n"
1659               "@end\n"
1660               "@interface Bar\n"
1661               "@end");
1662
1663  verifyFormat("@interface Foo : Bar\n"
1664               "+ (id)init;\n"
1665               "@end");
1666
1667  verifyFormat("@interface Foo : Bar <Baz, Quux>\n"
1668               "+ (id)init;\n"
1669               "@end");
1670
1671  verifyGoogleFormat("@interface Foo : Bar<Baz, Quux>\n"
1672                     "+ (id)init;\n"
1673                     "@end");
1674
1675  verifyFormat("@interface Foo (HackStuff)\n"
1676               "+ (id)init;\n"
1677               "@end");
1678
1679  verifyFormat("@interface Foo ()\n"
1680               "+ (id)init;\n"
1681               "@end");
1682
1683  verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
1684               "+ (id)init;\n"
1685               "@end");
1686
1687  verifyGoogleFormat("@interface Foo (HackStuff)<MyProtocol>\n"
1688                     "+ (id)init;\n"
1689                     "@end");
1690
1691  verifyFormat("@interface Foo {\n"
1692               "  int _i;\n"
1693               "}\n"
1694               "+ (id)init;\n"
1695               "@end");
1696
1697  verifyFormat("@interface Foo : Bar {\n"
1698               "  int _i;\n"
1699               "}\n"
1700               "+ (id)init;\n"
1701               "@end");
1702
1703  verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
1704               "  int _i;\n"
1705               "}\n"
1706               "+ (id)init;\n"
1707               "@end");
1708
1709  verifyFormat("@interface Foo (HackStuff) {\n"
1710               "  int _i;\n"
1711               "}\n"
1712               "+ (id)init;\n"
1713               "@end");
1714
1715  verifyFormat("@interface Foo () {\n"
1716               "  int _i;\n"
1717               "}\n"
1718               "+ (id)init;\n"
1719               "@end");
1720
1721  verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
1722               "  int _i;\n"
1723               "}\n"
1724               "+ (id)init;\n"
1725               "@end");
1726}
1727
1728TEST_F(FormatTest, FormatObjCImplementation) {
1729  verifyFormat("@implementation Foo : NSObject {\n"
1730               "@public\n"
1731               "  int field1;\n"
1732               "@protected\n"
1733               "  int field2;\n"
1734               "@private\n"
1735               "  int field3;\n"
1736               "@package\n"
1737               "  int field4;\n"
1738               "}\n"
1739               "+ (id)init {}\n"
1740               "@end");
1741
1742  verifyGoogleFormat("@implementation Foo : NSObject {\n"
1743                     " @public\n"
1744                     "  int field1;\n"
1745                     " @protected\n"
1746                     "  int field2;\n"
1747                     " @private\n"
1748                     "  int field3;\n"
1749                     " @package\n"
1750                     "  int field4;\n"
1751                     "}\n"
1752                     "+ (id)init {}\n"
1753                     "@end");
1754
1755  verifyFormat("@implementation Foo\n"
1756               "+ (id)init {\n"
1757               "  if (true)\n"
1758               "    return nil;\n"
1759               "}\n"
1760               "// Look, a comment!\n"
1761               "- (int)answerWith:(int)i {\n"
1762               "  return i;\n"
1763               "}\n"
1764               "+ (int)answerWith:(int)i {\n"
1765               "  return i;\n"
1766               "}\n"
1767               "@end");
1768
1769  verifyFormat("@implementation Foo\n"
1770               "@end\n"
1771               "@implementation Bar\n"
1772               "@end");
1773
1774  verifyFormat("@implementation Foo : Bar\n"
1775               "+ (id)init {}\n"
1776               "- (void)foo {}\n"
1777               "@end");
1778
1779  verifyFormat("@implementation Foo {\n"
1780               "  int _i;\n"
1781               "}\n"
1782               "+ (id)init {}\n"
1783               "@end");
1784
1785  verifyFormat("@implementation Foo : Bar {\n"
1786               "  int _i;\n"
1787               "}\n"
1788               "+ (id)init {}\n"
1789               "@end");
1790
1791  verifyFormat("@implementation Foo (HackStuff)\n"
1792               "+ (id)init {}\n"
1793               "@end");
1794}
1795
1796TEST_F(FormatTest, FormatObjCProtocol) {
1797  verifyFormat("@protocol Foo\n"
1798               "@property(weak) id delegate;\n"
1799               "- (NSUInteger)numberOfThings;\n"
1800               "@end");
1801
1802  verifyFormat("@protocol MyProtocol <NSObject>\n"
1803               "- (NSUInteger)numberOfThings;\n"
1804               "@end");
1805
1806  verifyGoogleFormat("@protocol MyProtocol<NSObject>\n"
1807                     "- (NSUInteger)numberOfThings;\n"
1808                     "@end");
1809
1810  verifyFormat("@protocol Foo;\n"
1811               "@protocol Bar;\n");
1812
1813  verifyFormat("@protocol Foo\n"
1814               "@end\n"
1815               "@protocol Bar\n"
1816               "@end");
1817
1818  verifyFormat("@protocol myProtocol\n"
1819               "- (void)mandatoryWithInt:(int)i;\n"
1820               "@optional\n"
1821               "- (void)optional;\n"
1822               "@required\n"
1823               "- (void)required;\n"
1824               "@optional\n"
1825               "@property(assign) int madProp;\n"
1826               "@end\n");
1827}
1828
1829TEST_F(FormatTest, FormatObjCMethodExpr) {
1830  verifyFormat("[foo bar:baz];");
1831  verifyFormat("return [foo bar:baz];");
1832  verifyFormat("f([foo bar:baz]);");
1833  verifyFormat("f(2, [foo bar:baz]);");
1834  verifyFormat("f(2, a ? b : c);");
1835  verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
1836
1837  verifyFormat("[foo bar:baz], [foo bar:baz];");
1838  verifyFormat("[foo bar:baz] = [foo bar:baz];");
1839  verifyFormat("[foo bar:baz] *= [foo bar:baz];");
1840  verifyFormat("[foo bar:baz] /= [foo bar:baz];");
1841  verifyFormat("[foo bar:baz] %= [foo bar:baz];");
1842  verifyFormat("[foo bar:baz] += [foo bar:baz];");
1843  verifyFormat("[foo bar:baz] -= [foo bar:baz];");
1844  verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
1845  verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
1846  verifyFormat("[foo bar:baz] &= [foo bar:baz];");
1847  verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
1848  verifyFormat("[foo bar:baz] |= [foo bar:baz];");
1849  verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
1850  verifyFormat("[foo bar:baz] || [foo bar:baz];");
1851  verifyFormat("[foo bar:baz] && [foo bar:baz];");
1852  verifyFormat("[foo bar:baz] | [foo bar:baz];");
1853  verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
1854  verifyFormat("[foo bar:baz] & [foo bar:baz];");
1855  verifyFormat("[foo bar:baz] == [foo bar:baz];");
1856  verifyFormat("[foo bar:baz] != [foo bar:baz];");
1857  verifyFormat("[foo bar:baz] >= [foo bar:baz];");
1858  verifyFormat("[foo bar:baz] <= [foo bar:baz];");
1859  verifyFormat("[foo bar:baz] > [foo bar:baz];");
1860  verifyFormat("[foo bar:baz] < [foo bar:baz];");
1861  verifyFormat("[foo bar:baz] >> [foo bar:baz];");
1862  verifyFormat("[foo bar:baz] << [foo bar:baz];");
1863  verifyFormat("[foo bar:baz] - [foo bar:baz];");
1864  verifyFormat("[foo bar:baz] + [foo bar:baz];");
1865  verifyFormat("[foo bar:baz] * [foo bar:baz];");
1866  verifyFormat("[foo bar:baz] / [foo bar:baz];");
1867  verifyFormat("[foo bar:baz] % [foo bar:baz];");
1868  // Whew!
1869
1870  verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
1871  verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
1872  verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
1873  verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
1874  verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
1875  verifyFormat("[button setAction:@selector(zoomOut:)];");
1876  verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
1877
1878  verifyFormat("arr[[self indexForFoo:a]];");
1879  verifyFormat("throw [self errorFor:a];");
1880  verifyFormat("@throw [self errorFor:a];");
1881
1882  // This tests that the formatter doesn't break after "backing" but before ":",
1883  // which would be at 80 columns.
1884  verifyFormat(
1885      "void f() {\n"
1886      "  if ((self = [super initWithContentRect:contentRect styleMask:styleMask\n"
1887      "                  backing:NSBackingStoreBuffered defer:YES]))");
1888
1889  verifyFormat("[foo checkThatBreakingAfterColonWorksOk:\n"
1890               "    [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
1891
1892}
1893
1894TEST_F(FormatTest, ObjCAt) {
1895  verifyFormat("@autoreleasepool");
1896  verifyFormat("@catch");
1897  verifyFormat("@class");
1898  verifyFormat("@compatibility_alias");
1899  verifyFormat("@defs");
1900  verifyFormat("@dynamic");
1901  verifyFormat("@encode");
1902  verifyFormat("@end");
1903  verifyFormat("@finally");
1904  verifyFormat("@implementation");
1905  verifyFormat("@import");
1906  verifyFormat("@interface");
1907  verifyFormat("@optional");
1908  verifyFormat("@package");
1909  verifyFormat("@private");
1910  verifyFormat("@property");
1911  verifyFormat("@protected");
1912  verifyFormat("@protocol");
1913  verifyFormat("@public");
1914  verifyFormat("@required");
1915  verifyFormat("@selector");
1916  verifyFormat("@synchronized");
1917  verifyFormat("@synthesize");
1918  verifyFormat("@throw");
1919  verifyFormat("@try");
1920
1921  verifyFormat("@\"String\"");
1922  verifyFormat("@1");
1923  verifyFormat("@+4.8");
1924  verifyFormat("@-4");
1925  verifyFormat("@1LL");
1926  verifyFormat("@.5");
1927  verifyFormat("@'c'");
1928  verifyFormat("@true");
1929  verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
1930  // FIXME: Array and dictionary literals need more work.
1931  verifyFormat("@[");
1932  verifyFormat("@{");
1933
1934  EXPECT_EQ("@interface", format("@ interface"));
1935
1936  // The precise formatting of this doesn't matter, nobody writes code like
1937  // this.
1938  verifyFormat("@ /*foo*/ interface");
1939}
1940
1941TEST_F(FormatTest, ObjCSnippets) {
1942  verifyFormat("@autoreleasepool {\n"
1943               "  foo();\n"
1944               "}");
1945  verifyFormat("@class Foo, Bar;");
1946  verifyFormat("@compatibility_alias AliasName ExistingClass;");
1947  verifyFormat("@dynamic textColor;");
1948  verifyFormat("char *buf1 = @encode(int *);");
1949  verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
1950  // FIXME: Enable once PR14884 is fixed:
1951  //verifyFormat("char *buf1 = @encode(int **);");
1952  verifyFormat("Protocol *proto = @protocol(p1);");
1953  verifyFormat("SEL s = @selector(foo:);");
1954  verifyFormat("@synchronized(self) {\n"
1955               "  f();\n"
1956               "}");
1957
1958  verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
1959  verifyGoogleFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
1960
1961  verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
1962  verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
1963  verifyGoogleFormat("@property(assign, getter=isEditable) BOOL editable;");
1964}
1965
1966} // end namespace tooling
1967} // end namespace clang
1968