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