1 //===- unittest/Format/FormatTestObjC.cpp - Formatting unit tests----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Format/Format.h"
11 
12 #include "../Tooling/ReplacementTest.h"
13 #include "FormatTestUtils.h"
14 
15 #include "clang/Frontend/TextDiagnosticPrinter.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/MemoryBuffer.h"
18 #include "gtest/gtest.h"
19 
20 #define DEBUG_TYPE "format-test"
21 
22 using clang::tooling::ReplacementTest;
23 
24 namespace clang {
25 namespace format {
26 namespace {
27 
28 class FormatTestObjC : public ::testing::Test {
29 protected:
30   FormatTestObjC() {
31     Style = getLLVMStyle();
32     Style.Language = FormatStyle::LK_ObjC;
33   }
34 
35   enum StatusCheck {
36     SC_ExpectComplete,
37     SC_ExpectIncomplete,
38     SC_DoNotCheck
39   };
40 
41   std::string format(llvm::StringRef Code,
42                      StatusCheck CheckComplete = SC_ExpectComplete) {
43     DEBUG(llvm::errs() << "---\n");
44     DEBUG(llvm::errs() << Code << "\n\n");
45     std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
46     FormattingAttemptStatus Status;
47     tooling::Replacements Replaces =
48         reformat(Style, Code, Ranges, "<stdin>", &Status);
49     if (CheckComplete != SC_DoNotCheck) {
50       bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete;
51       EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete)
52           << Code << "\n\n";
53     }
54     auto Result = applyAllReplacements(Code, Replaces);
55     EXPECT_TRUE(static_cast<bool>(Result));
56     DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
57     return *Result;
58   }
59 
60   void verifyFormat(StringRef Code) {
61     EXPECT_EQ(Code.str(), format(test::messUp(Code)));
62   }
63 
64   void verifyIncompleteFormat(StringRef Code) {
65     EXPECT_EQ(Code.str(), format(test::messUp(Code), SC_ExpectIncomplete));
66   }
67 
68   FormatStyle Style;
69 };
70 
71 TEST(FormatTestObjCStyle, DetectsObjCInHeaders) {
72   auto Style = getStyle("LLVM", "a.h", "none", "@interface\n"
73                                                "- (id)init;");
74   ASSERT_TRUE((bool)Style);
75   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
76 
77   Style = getStyle("LLVM", "a.h", "none", "@interface\n"
78                                           "+ (id)init;");
79   ASSERT_TRUE((bool)Style);
80   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
81 
82   Style = getStyle("LLVM", "a.h", "none", "@interface\n"
83                                           "@end\n"
84                                           "//comment");
85   ASSERT_TRUE((bool)Style);
86   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
87 
88   Style = getStyle("LLVM", "a.h", "none", "@interface\n"
89                                           "@end //comment");
90   ASSERT_TRUE((bool)Style);
91   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
92 
93   // No recognizable ObjC.
94   Style = getStyle("LLVM", "a.h", "none", "void f() {}");
95   ASSERT_TRUE((bool)Style);
96   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
97 
98   Style = getStyle("{}", "a.h", "none", "@interface Foo\n@end\n");
99   ASSERT_TRUE((bool)Style);
100   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
101 
102   Style = getStyle("{}", "a.h", "none",
103                    "const int interface = 1;\nconst int end = 2;\n");
104   ASSERT_TRUE((bool)Style);
105   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
106 
107   Style = getStyle("{}", "a.h", "none", "@protocol Foo\n@end\n");
108   ASSERT_TRUE((bool)Style);
109   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
110 
111   Style = getStyle("{}", "a.h", "none",
112                    "const int protocol = 1;\nconst int end = 2;\n");
113   ASSERT_TRUE((bool)Style);
114   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
115 
116   Style = getStyle("{}", "a.h", "none", "extern NSString *kFoo;\n");
117   ASSERT_TRUE((bool)Style);
118   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
119 
120   Style =
121       getStyle("{}", "a.h", "none", "typedef NS_ENUM(NSInteger, Foo) {};\n");
122   ASSERT_TRUE((bool)Style);
123   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
124 
125   Style = getStyle("{}", "a.h", "none", "enum Foo {};");
126   ASSERT_TRUE((bool)Style);
127   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
128 
129   Style = getStyle("{}", "a.h", "none", "extern NSInteger Foo();\n");
130   ASSERT_TRUE((bool)Style);
131   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
132 
133   Style =
134       getStyle("{}", "a.h", "none", "inline void Foo() { Log(@\"Foo\"); }\n");
135   ASSERT_TRUE((bool)Style);
136   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
137 
138   Style =
139       getStyle("{}", "a.h", "none", "inline void Foo() { Log(\"Foo\"); }\n");
140   ASSERT_TRUE((bool)Style);
141   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
142 
143   Style =
144       getStyle("{}", "a.h", "none", "inline void Foo() { id = @[1, 2, 3]; }\n");
145   ASSERT_TRUE((bool)Style);
146   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
147 
148   Style = getStyle("{}", "a.h", "none",
149                    "inline void Foo() { id foo = @{1: 2, 3: 4, 5: 6}; }\n");
150   ASSERT_TRUE((bool)Style);
151   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
152 
153   Style = getStyle("{}", "a.h", "none",
154                    "inline void Foo() { int foo[] = {1, 2, 3}; }\n");
155   ASSERT_TRUE((bool)Style);
156   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
157 }
158 
159 TEST_F(FormatTestObjC, FormatObjCTryCatch) {
160   verifyFormat("@try {\n"
161                "  f();\n"
162                "} @catch (NSException e) {\n"
163                "  @throw;\n"
164                "} @finally {\n"
165                "  exit(42);\n"
166                "}");
167   verifyFormat("DEBUG({\n"
168                "  @try {\n"
169                "  } @finally {\n"
170                "  }\n"
171                "});\n");
172 }
173 
174 TEST_F(FormatTestObjC, FormatObjCAutoreleasepool) {
175   verifyFormat("@autoreleasepool {\n"
176                "  f();\n"
177                "}\n"
178                "@autoreleasepool {\n"
179                "  f();\n"
180                "}\n");
181   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
182   verifyFormat("@autoreleasepool\n"
183                "{\n"
184                "  f();\n"
185                "}\n"
186                "@autoreleasepool\n"
187                "{\n"
188                "  f();\n"
189                "}\n");
190 }
191 
192 TEST_F(FormatTestObjC, FormatObjCGenerics) {
193   Style.ColumnLimit = 40;
194   verifyFormat("int aaaaaaaaaaaaaaaa(\n"
195                "    NSArray<aaaaaaaaaaaaaaaaaa *>\n"
196                "        aaaaaaaaaaaaaaaaa);\n");
197   verifyFormat("int aaaaaaaaaaaaaaaa(\n"
198                "    NSArray<aaaaaaaaaaaaaaaaaaa<\n"
199                "        aaaaaaaaaaaaaaaa *> *>\n"
200                "        aaaaaaaaaaaaaaaaa);\n");
201 }
202 
203 TEST_F(FormatTestObjC, FormatObjCInterface) {
204   verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
205                "@public\n"
206                "  int field1;\n"
207                "@protected\n"
208                "  int field2;\n"
209                "@private\n"
210                "  int field3;\n"
211                "@package\n"
212                "  int field4;\n"
213                "}\n"
214                "+ (id)init;\n"
215                "@end");
216 
217   verifyFormat("@interface /* wait for it */ Foo\n"
218                "+ (id)init;\n"
219                "// Look, a comment!\n"
220                "- (int)answerWith:(int)i;\n"
221                "@end");
222 
223   verifyFormat("@interface Foo\n"
224                "@end\n"
225                "@interface Bar\n"
226                "@end");
227 
228   verifyFormat("@interface Foo : Bar\n"
229                "@property(assign, readwrite) NSInteger bar;\n"
230                "+ (id)init;\n"
231                "@end");
232 
233   verifyFormat("FOUNDATION_EXPORT NS_AVAILABLE_IOS(10.0) @interface Foo : Bar\n"
234                "@property(assign, readwrite) NSInteger bar;\n"
235                "+ (id)init;\n"
236                "@end");
237 
238   verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
239                "+ (id)init;\n"
240                "@end");
241 
242   verifyFormat("@interface Foo (HackStuff)\n"
243                "+ (id)init;\n"
244                "@end");
245 
246   verifyFormat("@interface Foo ()\n"
247                "+ (id)init;\n"
248                "@end");
249 
250   verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
251                "+ (id)init;\n"
252                "@end");
253 
254   verifyFormat("@interface Foo {\n"
255                "  int _i;\n"
256                "}\n"
257                "+ (id)init;\n"
258                "@end");
259 
260   verifyFormat("@interface Foo : Bar {\n"
261                "  int _i;\n"
262                "}\n"
263                "+ (id)init;\n"
264                "@end");
265 
266   verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
267                "  int _i;\n"
268                "}\n"
269                "+ (id)init;\n"
270                "@end");
271 
272   verifyFormat("@interface Foo (HackStuff) {\n"
273                "  int _i;\n"
274                "}\n"
275                "+ (id)init;\n"
276                "@end");
277 
278   verifyFormat("@interface Foo () {\n"
279                "  int _i;\n"
280                "}\n"
281                "+ (id)init;\n"
282                "@end");
283 
284   verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
285                "  int _i;\n"
286                "}\n"
287                "+ (id)init;\n"
288                "@end");
289 
290   Style.ColumnLimit = 40;
291   verifyFormat("@interface ccccccccccccc () <\n"
292                "    ccccccccccccc, ccccccccccccc,\n"
293                "    ccccccccccccc, ccccccccccccc> {\n"
294                "}");
295   Style.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
296   verifyFormat("@interface ddddddddddddd () <\n"
297                "    ddddddddddddd,\n"
298                "    ddddddddddddd,\n"
299                "    ddddddddddddd,\n"
300                "    ddddddddddddd> {\n"
301                "}");
302 
303   Style.BinPackParameters = false;
304   Style.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
305   verifyFormat("@interface eeeeeeeeeeeee () <\n"
306                "    eeeeeeeeeeeee,\n"
307                "    eeeeeeeeeeeee,\n"
308                "    eeeeeeeeeeeee,\n"
309                "    eeeeeeeeeeeee> {\n"
310                "}");
311   Style.ObjCBinPackProtocolList = FormatStyle::BPS_Always;
312   verifyFormat("@interface fffffffffffff () <\n"
313                "    fffffffffffff, fffffffffffff,\n"
314                "    fffffffffffff, fffffffffffff> {\n"
315                "}");
316 
317   Style = getGoogleStyle(FormatStyle::LK_ObjC);
318   verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
319                " @public\n"
320                "  int field1;\n"
321                " @protected\n"
322                "  int field2;\n"
323                " @private\n"
324                "  int field3;\n"
325                " @package\n"
326                "  int field4;\n"
327                "}\n"
328                "+ (id)init;\n"
329                "@end");
330   verifyFormat("@interface Foo : Bar <Baz, Quux>\n"
331                "+ (id)init;\n"
332                "@end");
333   verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
334                "+ (id)init;\n"
335                "@end");
336   Style.ColumnLimit = 40;
337   // BinPackParameters should be true by default.
338   verifyFormat("void eeeeeeee(int eeeee, int eeeee,\n"
339                "              int eeeee, int eeeee);\n");
340   // ObjCBinPackProtocolList should be BPS_Never by default.
341   verifyFormat("@interface fffffffffffff () <\n"
342                "    fffffffffffff,\n"
343                "    fffffffffffff,\n"
344                "    fffffffffffff,\n"
345                "    fffffffffffff> {\n"
346                "}");
347 }
348 
349 TEST_F(FormatTestObjC, FormatObjCImplementation) {
350   verifyFormat("@implementation Foo : NSObject {\n"
351                "@public\n"
352                "  int field1;\n"
353                "@protected\n"
354                "  int field2;\n"
355                "@private\n"
356                "  int field3;\n"
357                "@package\n"
358                "  int field4;\n"
359                "}\n"
360                "+ (id)init {\n}\n"
361                "@end");
362 
363   verifyFormat("@implementation Foo\n"
364                "+ (id)init {\n"
365                "  if (true)\n"
366                "    return nil;\n"
367                "}\n"
368                "// Look, a comment!\n"
369                "- (int)answerWith:(int)i {\n"
370                "  return i;\n"
371                "}\n"
372                "+ (int)answerWith:(int)i {\n"
373                "  return i;\n"
374                "}\n"
375                "@end");
376 
377   verifyFormat("@implementation Foo\n"
378                "@end\n"
379                "@implementation Bar\n"
380                "@end");
381 
382   EXPECT_EQ("@implementation Foo : Bar\n"
383             "+ (id)init {\n}\n"
384             "- (void)foo {\n}\n"
385             "@end",
386             format("@implementation Foo : Bar\n"
387                    "+(id)init{}\n"
388                    "-(void)foo{}\n"
389                    "@end"));
390 
391   verifyFormat("@implementation Foo {\n"
392                "  int _i;\n"
393                "}\n"
394                "+ (id)init {\n}\n"
395                "@end");
396 
397   verifyFormat("@implementation Foo : Bar {\n"
398                "  int _i;\n"
399                "}\n"
400                "+ (id)init {\n}\n"
401                "@end");
402 
403   verifyFormat("@implementation Foo (HackStuff)\n"
404                "+ (id)init {\n}\n"
405                "@end");
406   verifyFormat("@implementation ObjcClass\n"
407                "- (void)method;\n"
408                "{}\n"
409                "@end");
410 
411   Style = getGoogleStyle(FormatStyle::LK_ObjC);
412   verifyFormat("@implementation Foo : NSObject {\n"
413                " @public\n"
414                "  int field1;\n"
415                " @protected\n"
416                "  int field2;\n"
417                " @private\n"
418                "  int field3;\n"
419                " @package\n"
420                "  int field4;\n"
421                "}\n"
422                "+ (id)init {\n}\n"
423                "@end");
424 }
425 
426 TEST_F(FormatTestObjC, FormatObjCProtocol) {
427   verifyFormat("@protocol Foo\n"
428                "@property(weak) id delegate;\n"
429                "- (NSUInteger)numberOfThings;\n"
430                "@end");
431 
432   verifyFormat("@protocol MyProtocol <NSObject>\n"
433                "- (NSUInteger)numberOfThings;\n"
434                "@end");
435 
436   verifyFormat("@protocol Foo;\n"
437                "@protocol Bar;\n");
438 
439   verifyFormat("@protocol Foo\n"
440                "@end\n"
441                "@protocol Bar\n"
442                "@end");
443 
444   verifyFormat("FOUNDATION_EXPORT NS_AVAILABLE_IOS(10.0) @protocol Foo\n"
445                "@property(assign, readwrite) NSInteger bar;\n"
446                "@end");
447 
448   verifyFormat("@protocol myProtocol\n"
449                "- (void)mandatoryWithInt:(int)i;\n"
450                "@optional\n"
451                "- (void)optional;\n"
452                "@required\n"
453                "- (void)required;\n"
454                "@optional\n"
455                "@property(assign) int madProp;\n"
456                "@end\n");
457 
458   verifyFormat("@property(nonatomic, assign, readonly)\n"
459                "    int *looooooooooooooooooooooooooooongNumber;\n"
460                "@property(nonatomic, assign, readonly)\n"
461                "    NSString *looooooooooooooooooooooooooooongName;");
462 
463   verifyFormat("@implementation PR18406\n"
464                "}\n"
465                "@end");
466 
467   Style = getGoogleStyle(FormatStyle::LK_ObjC);
468   verifyFormat("@protocol MyProtocol <NSObject>\n"
469                "- (NSUInteger)numberOfThings;\n"
470                "@end");
471 }
472 
473 TEST_F(FormatTestObjC, FormatObjCMethodDeclarations) {
474   verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
475                "                   rect:(NSRect)theRect\n"
476                "               interval:(float)theInterval {\n"
477                "}");
478   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
479                "      longKeyword:(NSRect)theRect\n"
480                "    longerKeyword:(float)theInterval\n"
481                "            error:(NSError **)theError {\n"
482                "}");
483   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
484                "          longKeyword:(NSRect)theRect\n"
485                "    evenLongerKeyword:(float)theInterval\n"
486                "                error:(NSError **)theError {\n"
487                "}");
488   Style.ColumnLimit = 60;
489   verifyFormat("- (instancetype)initXxxxxx:(id<x>)x\n"
490                "                         y:(id<yyyyyyyyyyyyyyyyyyyy>)y\n"
491                "    NS_DESIGNATED_INITIALIZER;");
492   verifyFormat("- (void)drawRectOn:(id)surface\n"
493                "            ofSize:(size_t)height\n"
494                "                  :(size_t)width;");
495 
496   // Continuation indent width should win over aligning colons if the function
497   // name is long.
498   Style = getGoogleStyle(FormatStyle::LK_ObjC);
499   Style.ColumnLimit = 40;
500   Style.IndentWrappedFunctionNames = true;
501   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
502                "    dontAlignNamef:(NSRect)theRect {\n"
503                "}");
504 
505   // Make sure we don't break aligning for short parameter names.
506   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
507                "       aShortf:(NSRect)theRect {\n"
508                "}");
509 
510   // Format pairs correctly.
511   Style.ColumnLimit = 80;
512   verifyFormat("- (void)drawRectOn:(id)surface\n"
513                "            ofSize:(aaaaaaaa)height\n"
514                "                  :(size_t)width\n"
515                "          atOrigin:(size_t)x\n"
516                "                  :(size_t)y\n"
517                "             aaaaa:(a)yyy\n"
518                "               bbb:(d)cccc;");
519   verifyFormat("- (void)drawRectOn:(id)surface ofSize:(aaa)height:(bbb)width;");
520 }
521 
522 TEST_F(FormatTestObjC, FormatObjCMethodExpr) {
523   verifyFormat("[foo bar:baz];");
524   verifyFormat("return [foo bar:baz];");
525   verifyFormat("return (a)[foo bar:baz];");
526   verifyFormat("f([foo bar:baz]);");
527   verifyFormat("f(2, [foo bar:baz]);");
528   verifyFormat("f(2, a ? b : c);");
529   verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
530 
531   // Unary operators.
532   verifyFormat("int a = +[foo bar:baz];");
533   verifyFormat("int a = -[foo bar:baz];");
534   verifyFormat("int a = ![foo bar:baz];");
535   verifyFormat("int a = ~[foo bar:baz];");
536   verifyFormat("int a = ++[foo bar:baz];");
537   verifyFormat("int a = --[foo bar:baz];");
538   verifyFormat("int a = sizeof [foo bar:baz];");
539   verifyFormat("int a = alignof [foo bar:baz];");
540   verifyFormat("int a = &[foo bar:baz];");
541   verifyFormat("int a = *[foo bar:baz];");
542   // FIXME: Make casts work, without breaking f()[4].
543   // verifyFormat("int a = (int)[foo bar:baz];");
544   // verifyFormat("return (int)[foo bar:baz];");
545   // verifyFormat("(void)[foo bar:baz];");
546   verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
547 
548   // Binary operators.
549   verifyFormat("[foo bar:baz], [foo bar:baz];");
550   verifyFormat("[foo bar:baz] = [foo bar:baz];");
551   verifyFormat("[foo bar:baz] *= [foo bar:baz];");
552   verifyFormat("[foo bar:baz] /= [foo bar:baz];");
553   verifyFormat("[foo bar:baz] %= [foo bar:baz];");
554   verifyFormat("[foo bar:baz] += [foo bar:baz];");
555   verifyFormat("[foo bar:baz] -= [foo bar:baz];");
556   verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
557   verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
558   verifyFormat("[foo bar:baz] &= [foo bar:baz];");
559   verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
560   verifyFormat("[foo bar:baz] |= [foo bar:baz];");
561   verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
562   verifyFormat("[foo bar:baz] || [foo bar:baz];");
563   verifyFormat("[foo bar:baz] && [foo bar:baz];");
564   verifyFormat("[foo bar:baz] | [foo bar:baz];");
565   verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
566   verifyFormat("[foo bar:baz] & [foo bar:baz];");
567   verifyFormat("[foo bar:baz] == [foo bar:baz];");
568   verifyFormat("[foo bar:baz] != [foo bar:baz];");
569   verifyFormat("[foo bar:baz] >= [foo bar:baz];");
570   verifyFormat("[foo bar:baz] <= [foo bar:baz];");
571   verifyFormat("[foo bar:baz] > [foo bar:baz];");
572   verifyFormat("[foo bar:baz] < [foo bar:baz];");
573   verifyFormat("[foo bar:baz] >> [foo bar:baz];");
574   verifyFormat("[foo bar:baz] << [foo bar:baz];");
575   verifyFormat("[foo bar:baz] - [foo bar:baz];");
576   verifyFormat("[foo bar:baz] + [foo bar:baz];");
577   verifyFormat("[foo bar:baz] * [foo bar:baz];");
578   verifyFormat("[foo bar:baz] / [foo bar:baz];");
579   verifyFormat("[foo bar:baz] % [foo bar:baz];");
580   // Whew!
581 
582   verifyFormat("return in[42];");
583   verifyFormat("for (auto v : in[1]) {\n}");
584   verifyFormat("for (int i = 0; i < in[a]; ++i) {\n}");
585   verifyFormat("for (int i = 0; in[a] < i; ++i) {\n}");
586   verifyFormat("for (int i = 0; i < n; ++i, ++in[a]) {\n}");
587   verifyFormat("for (int i = 0; i < n; ++i, in[a]++) {\n}");
588   verifyFormat("for (int i = 0; i < f(in[a]); ++i, in[a]++) {\n}");
589   verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
590                "}");
591   verifyFormat("[self aaaaa:MACRO(a, b:, c:)];");
592   verifyFormat("[self aaaaa:(1 + 2) bbbbb:3];");
593   verifyFormat("[self aaaaa:(Type)a bbbbb:3];");
594 
595   verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
596   verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
597   verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
598   verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
599   verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
600   verifyFormat("[button setAction:@selector(zoomOut:)];");
601   verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
602 
603   verifyFormat("arr[[self indexForFoo:a]];");
604   verifyFormat("throw [self errorFor:a];");
605   verifyFormat("@throw [self errorFor:a];");
606 
607   verifyFormat("[(id)foo bar:(id)baz quux:(id)snorf];");
608   verifyFormat("[(id)foo bar:(id) ? baz : quux];");
609   verifyFormat("4 > 4 ? (id)a : (id)baz;");
610 
611   // This tests that the formatter doesn't break after "backing" but before ":",
612   // which would be at 80 columns.
613   verifyFormat(
614       "void f() {\n"
615       "  if ((self = [super initWithContentRect:contentRect\n"
616       "                               styleMask:styleMask ?: otherMask\n"
617       "                                 backing:NSBackingStoreBuffered\n"
618       "                                   defer:YES]))");
619 
620   verifyFormat(
621       "[foo checkThatBreakingAfterColonWorksOk:\n"
622       "         [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
623 
624   verifyFormat("[myObj short:arg1 // Force line break\n"
625                "          longKeyword:arg2 != nil ? arg2 : @\"longKeyword\"\n"
626                "    evenLongerKeyword:arg3 ?: @\"evenLongerKeyword\"\n"
627                "                error:arg4];");
628   verifyFormat(
629       "void f() {\n"
630       "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
631       "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
632       "                                     pos.width(), pos.height())\n"
633       "                styleMask:NSBorderlessWindowMask\n"
634       "                  backing:NSBackingStoreBuffered\n"
635       "                    defer:NO]);\n"
636       "}");
637   verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
638                "                             with:contentsNativeView];");
639 
640   verifyFormat(
641       "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
642       "           owner:nillllll];");
643 
644   verifyFormat(
645       "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
646       "        forType:kBookmarkButtonDragType];");
647 
648   verifyFormat("[defaultCenter addObserver:self\n"
649                "                  selector:@selector(willEnterFullscreen)\n"
650                "                      name:kWillEnterFullscreenNotification\n"
651                "                    object:nil];");
652   verifyFormat("[image_rep drawInRect:drawRect\n"
653                "             fromRect:NSZeroRect\n"
654                "            operation:NSCompositeCopy\n"
655                "             fraction:1.0\n"
656                "       respectFlipped:NO\n"
657                "                hints:nil];");
658   verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
659                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
660   verifyFormat("[aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
661                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
662   verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaa[aaaaaaaaaaaaaaaaaaaaa]\n"
663                "    aaaaaaaaaaaaaaaaaaaaaa];");
664 
665   verifyFormat(
666       "scoped_nsobject<NSTextField> message(\n"
667       "    // The frame will be fixed up when |-setMessageText:| is called.\n"
668       "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
669   verifyFormat("[self aaaaaa:bbbbbbbbbbbbb\n"
670                "    aaaaaaaaaa:bbbbbbbbbbbbbbbbb\n"
671                "         aaaaa:bbbbbbbbbbb + bbbbbbbbbbbb\n"
672                "          aaaa:bbb];");
673   verifyFormat("[self param:function( //\n"
674                "                parameter)]");
675   verifyFormat(
676       "[self aaaaaaaaaa:aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
677       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
678       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa];");
679 
680   // Variadic parameters.
681   verifyFormat(
682       "NSArray *myStrings = [NSArray stringarray:@\"a\", @\"b\", nil];");
683   verifyFormat(
684       "[self aaaaaaaaaaaaa:aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
685       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
686       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa];");
687   verifyFormat("[self // break\n"
688                "      a:a\n"
689                "    aaa:aaa];");
690   verifyFormat("bool a = ([aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaa ||\n"
691                "          [aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaaaaa);");
692 
693   // Formats pair-parameters.
694   verifyFormat("[I drawRectOn:surface ofSize:aa:bbb atOrigin:cc:dd];");
695   verifyFormat("[I drawRectOn:surface //\n"
696                "       ofSize:aa:bbb\n"
697                "     atOrigin:cc:dd];");
698 
699   // Inline block as a first argument.
700   verifyFormat("[object justBlock:^{\n"
701                "  a = 42;\n"
702                "}];");
703   verifyFormat("[object\n"
704                "    justBlock:^{\n"
705                "      a = 42;\n"
706                "    }\n"
707                "     notBlock:42\n"
708                "            a:42];");
709   verifyFormat("[object\n"
710                "    firstBlock:^{\n"
711                "      a = 42;\n"
712                "    }\n"
713                "    blockWithLongerName:^{\n"
714                "      a = 42;\n"
715                "    }];");
716   verifyFormat("[object\n"
717                "    blockWithLongerName:^{\n"
718                "      a = 42;\n"
719                "    }\n"
720                "    secondBlock:^{\n"
721                "      a = 42;\n"
722                "    }];");
723   verifyFormat("[object\n"
724                "    firstBlock:^{\n"
725                "      a = 42;\n"
726                "    }\n"
727                "    notBlock:42\n"
728                "    secondBlock:^{\n"
729                "      a = 42;\n"
730                "    }];");
731 
732   Style.ColumnLimit = 70;
733   verifyFormat(
734       "void f() {\n"
735       "  popup_wdow_.reset([[RenderWidgetPopupWindow alloc]\n"
736       "      iniithContentRect:NSMakRet(origin_global.x, origin_global.y,\n"
737       "                                 pos.width(), pos.height())\n"
738       "                syeMask:NSBorderlessWindowMask\n"
739       "                  bking:NSBackingStoreBuffered\n"
740       "                    der:NO]);\n"
741       "}");
742 
743   Style.ColumnLimit = 60;
744   verifyFormat("[call aaaaaaaa.aaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa\n"
745                "        .aaaaaaaa];"); // FIXME: Indentation seems off.
746   // FIXME: This violates the column limit.
747   verifyFormat(
748       "[aaaaaaaaaaaaaaaaaaaaaaaaa\n"
749       "    aaaaaaaaaaaaaaaaa:aaaaaaaa\n"
750       "                  aaa:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
751 
752   Style = getChromiumStyle(FormatStyle::LK_ObjC);
753   Style.ColumnLimit = 80;
754   verifyFormat(
755       "void f() {\n"
756       "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
757       "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
758       "                                     pos.width(), pos.height())\n"
759       "                styleMask:NSBorderlessWindowMask\n"
760       "                  backing:NSBackingStoreBuffered\n"
761       "                    defer:NO]);\n"
762       "}");
763 
764   // Respect continuation indent and colon alignment (e.g. when object name is
765   // short, and first selector is the longest one)
766   Style = getLLVMStyle();
767   Style.Language = FormatStyle::LK_ObjC;
768   Style.ContinuationIndentWidth = 8;
769   verifyFormat("[self performSelectorOnMainThread:@selector(loadAccessories)\n"
770                "                       withObject:nil\n"
771                "                    waitUntilDone:false];");
772   verifyFormat("[self performSelector:@selector(loadAccessories)\n"
773                "        withObjectOnMainThread:nil\n"
774                "                 waitUntilDone:false];");
775   verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaaaa\n"
776                "        performSelectorOnMainThread:@selector(loadAccessories)\n"
777                "                         withObject:nil\n"
778                "                      waitUntilDone:false];");
779   verifyFormat("[self // force wrapping\n"
780                "        performSelectorOnMainThread:@selector(loadAccessories)\n"
781                "                         withObject:nil\n"
782                "                      waitUntilDone:false];");
783 }
784 
785 TEST_F(FormatTestObjC, ObjCAt) {
786   verifyFormat("@autoreleasepool");
787   verifyFormat("@catch");
788   verifyFormat("@class");
789   verifyFormat("@compatibility_alias");
790   verifyFormat("@defs");
791   verifyFormat("@dynamic");
792   verifyFormat("@encode");
793   verifyFormat("@end");
794   verifyFormat("@finally");
795   verifyFormat("@implementation");
796   verifyFormat("@import");
797   verifyFormat("@interface");
798   verifyFormat("@optional");
799   verifyFormat("@package");
800   verifyFormat("@private");
801   verifyFormat("@property");
802   verifyFormat("@protected");
803   verifyFormat("@protocol");
804   verifyFormat("@public");
805   verifyFormat("@required");
806   verifyFormat("@selector");
807   verifyFormat("@synchronized");
808   verifyFormat("@synthesize");
809   verifyFormat("@throw");
810   verifyFormat("@try");
811 
812   EXPECT_EQ("@interface", format("@ interface"));
813 
814   // The precise formatting of this doesn't matter, nobody writes code like
815   // this.
816   verifyFormat("@ /*foo*/ interface");
817 }
818 
819 TEST_F(FormatTestObjC, ObjCSnippets) {
820   verifyFormat("@autoreleasepool {\n"
821                "  foo();\n"
822                "}");
823   verifyFormat("@class Foo, Bar;");
824   verifyFormat("@compatibility_alias AliasName ExistingClass;");
825   verifyFormat("@dynamic textColor;");
826   verifyFormat("char *buf1 = @encode(int *);");
827   verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
828   verifyFormat("char *buf1 = @encode(int **);");
829   verifyFormat("Protocol *proto = @protocol(p1);");
830   verifyFormat("SEL s = @selector(foo:);");
831   verifyFormat("@synchronized(self) {\n"
832                "  f();\n"
833                "}");
834 
835   verifyFormat("@import foo.bar;\n"
836                "@import baz;");
837 
838   verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
839 
840   verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
841   verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
842 
843   Style = getMozillaStyle();
844   verifyFormat("@property (assign, getter=isEditable) BOOL editable;");
845   verifyFormat("@property BOOL editable;");
846 
847   Style = getWebKitStyle();
848   verifyFormat("@property (assign, getter=isEditable) BOOL editable;");
849   verifyFormat("@property BOOL editable;");
850 
851   Style = getGoogleStyle(FormatStyle::LK_ObjC);
852   verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
853   verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
854 }
855 
856 TEST_F(FormatTestObjC, ObjCForIn) {
857   verifyFormat("- (void)test {\n"
858                "  for (NSString *n in arrayOfStrings) {\n"
859                "    foo(n);\n"
860                "  }\n"
861                "}");
862   verifyFormat("- (void)test {\n"
863                "  for (NSString *n in (__bridge NSArray *)arrayOfStrings) {\n"
864                "    foo(n);\n"
865                "  }\n"
866                "}");
867 }
868 
869 TEST_F(FormatTestObjC, ObjCLiterals) {
870   verifyFormat("@\"String\"");
871   verifyFormat("@1");
872   verifyFormat("@+4.8");
873   verifyFormat("@-4");
874   verifyFormat("@1LL");
875   verifyFormat("@.5");
876   verifyFormat("@'c'");
877   verifyFormat("@true");
878 
879   verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
880   verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
881   verifyFormat("NSNumber *favoriteColor = @(Green);");
882   verifyFormat("NSString *path = @(getenv(\"PATH\"));");
883 
884   verifyFormat("[dictionary setObject:@(1) forKey:@\"number\"];");
885 }
886 
887 TEST_F(FormatTestObjC, ObjCDictLiterals) {
888   verifyFormat("@{");
889   verifyFormat("@{}");
890   verifyFormat("@{@\"one\" : @1}");
891   verifyFormat("return @{@\"one\" : @1;");
892   verifyFormat("@{@\"one\" : @1}");
893 
894   verifyFormat("@{@\"one\" : @{@2 : @1}}");
895   verifyFormat("@{\n"
896                "  @\"one\" : @{@2 : @1},\n"
897                "}");
898 
899   verifyFormat("@{1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2}");
900   verifyIncompleteFormat("[self setDict:@{}");
901   verifyIncompleteFormat("[self setDict:@{@1 : @2}");
902   verifyFormat("NSLog(@\"%@\", @{@1 : @2, @2 : @3}[@1]);");
903   verifyFormat(
904       "NSDictionary *masses = @{@\"H\" : @1.0078, @\"He\" : @4.0026};");
905   verifyFormat(
906       "NSDictionary *settings = @{AVEncoderKey : @(AVAudioQualityMax)};");
907 
908   verifyFormat("NSDictionary *d = @{\n"
909                "  @\"nam\" : NSUserNam(),\n"
910                "  @\"dte\" : [NSDate date],\n"
911                "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
912                "};");
913   verifyFormat(
914       "@{\n"
915       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
916       "regularFont,\n"
917       "};");
918   verifyFormat(
919       "@{\n"
920       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :\n"
921       "      reeeeeeeeeeeeeeeeeeeeeeeegularFont,\n"
922       "};");
923 
924   // We should try to be robust in case someone forgets the "@".
925   verifyFormat("NSDictionary *d = {\n"
926                "  @\"nam\" : NSUserNam(),\n"
927                "  @\"dte\" : [NSDate date],\n"
928                "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
929                "};");
930   verifyFormat("NSMutableDictionary *dictionary =\n"
931                "    [NSMutableDictionary dictionaryWithDictionary:@{\n"
932                "      aaaaaaaaaaaaaaaaaaaaa : aaaaaaaaaaaaa,\n"
933                "      bbbbbbbbbbbbbbbbbb : bbbbb,\n"
934                "      cccccccccccccccc : ccccccccccccccc\n"
935                "    }];");
936 
937   // Ensure that casts before the key are kept on the same line as the key.
938   verifyFormat(
939       "NSDictionary *d = @{\n"
940       "  (aaaaaaaa id)aaaaaaaaa : (aaaaaaaa id)aaaaaaaaaaaaaaaaaaaaaaaa,\n"
941       "  (aaaaaaaa id)aaaaaaaaaaaaaa : (aaaaaaaa id)aaaaaaaaaaaaaa,\n"
942       "};");
943 
944   Style = getGoogleStyle(FormatStyle::LK_ObjC);
945   verifyFormat(
946       "@{\n"
947       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
948       "regularFont,\n"
949       "};");
950 }
951 
952 TEST_F(FormatTestObjC, ObjCArrayLiterals) {
953   verifyIncompleteFormat("@[");
954   verifyFormat("@[]");
955   verifyFormat(
956       "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
957   verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
958   verifyFormat("NSArray *array = @[ [foo description] ];");
959 
960   verifyFormat(
961       "NSArray *some_variable = @[\n"
962       "  aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
963       "  @\"aaaaaaaaaaaaaaaaa\",\n"
964       "  @\"aaaaaaaaaaaaaaaaa\",\n"
965       "  @\"aaaaaaaaaaaaaaaaa\",\n"
966       "];");
967   verifyFormat(
968       "NSArray *some_variable = @[\n"
969       "  aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
970       "  @\"aaaaaaaaaaaaaaaa\", @\"aaaaaaaaaaaaaaaa\", @\"aaaaaaaaaaaaaaaa\"\n"
971       "];");
972   verifyFormat("NSArray *some_variable = @[\n"
973                "  @\"aaaaaaaaaaaaaaaaa\",\n"
974                "  @\"aaaaaaaaaaaaaaaaa\",\n"
975                "  @\"aaaaaaaaaaaaaaaaa\",\n"
976                "  @\"aaaaaaaaaaaaaaaaa\",\n"
977                "];");
978   verifyFormat("NSArray *array = @[\n"
979                "  @\"a\",\n"
980                "  @\"a\",\n" // Trailing comma -> one per line.
981                "];");
982 
983   // We should try to be robust in case someone forgets the "@".
984   verifyFormat("NSArray *some_variable = [\n"
985                "  @\"aaaaaaaaaaaaaaaaa\",\n"
986                "  @\"aaaaaaaaaaaaaaaaa\",\n"
987                "  @\"aaaaaaaaaaaaaaaaa\",\n"
988                "  @\"aaaaaaaaaaaaaaaaa\",\n"
989                "];");
990   verifyFormat(
991       "- (NSAttributedString *)attributedStringForSegment:(NSUInteger)segment\n"
992       "                                             index:(NSUInteger)index\n"
993       "                                nonDigitAttributes:\n"
994       "                                    (NSDictionary *)noDigitAttributes;");
995   verifyFormat("[someFunction someLooooooooooooongParameter:@[\n"
996                "  NSBundle.mainBundle.infoDictionary[@\"a\"]\n"
997                "]];");
998   Style.ColumnLimit = 20;
999   // We can't break string literals inside NSArray literals
1000   // (that raises -Wobjc-string-concatenation).
1001   verifyFormat("NSArray *foo = @[\n"
1002                "  @\"aaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
1003                "];\n");
1004 }
1005 } // end namespace
1006 } // end namespace format
1007 } // end namespace clang
1008