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