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, FormatObjCInterface) {
193   verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
194                "@public\n"
195                "  int field1;\n"
196                "@protected\n"
197                "  int field2;\n"
198                "@private\n"
199                "  int field3;\n"
200                "@package\n"
201                "  int field4;\n"
202                "}\n"
203                "+ (id)init;\n"
204                "@end");
205 
206   verifyFormat("@interface /* wait for it */ Foo\n"
207                "+ (id)init;\n"
208                "// Look, a comment!\n"
209                "- (int)answerWith:(int)i;\n"
210                "@end");
211 
212   verifyFormat("@interface Foo\n"
213                "@end\n"
214                "@interface Bar\n"
215                "@end");
216 
217   verifyFormat("@interface Foo : Bar\n"
218                "+ (id)init;\n"
219                "@end");
220 
221   verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
222                "+ (id)init;\n"
223                "@end");
224 
225   verifyFormat("@interface Foo (HackStuff)\n"
226                "+ (id)init;\n"
227                "@end");
228 
229   verifyFormat("@interface Foo ()\n"
230                "+ (id)init;\n"
231                "@end");
232 
233   verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
234                "+ (id)init;\n"
235                "@end");
236 
237   verifyFormat("@interface Foo {\n"
238                "  int _i;\n"
239                "}\n"
240                "+ (id)init;\n"
241                "@end");
242 
243   verifyFormat("@interface Foo : Bar {\n"
244                "  int _i;\n"
245                "}\n"
246                "+ (id)init;\n"
247                "@end");
248 
249   verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
250                "  int _i;\n"
251                "}\n"
252                "+ (id)init;\n"
253                "@end");
254 
255   verifyFormat("@interface Foo (HackStuff) {\n"
256                "  int _i;\n"
257                "}\n"
258                "+ (id)init;\n"
259                "@end");
260 
261   verifyFormat("@interface Foo () {\n"
262                "  int _i;\n"
263                "}\n"
264                "+ (id)init;\n"
265                "@end");
266 
267   verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
268                "  int _i;\n"
269                "}\n"
270                "+ (id)init;\n"
271                "@end");
272 
273   Style = getGoogleStyle(FormatStyle::LK_ObjC);
274   verifyFormat("@interface Foo : NSObject<NSSomeDelegate> {\n"
275                " @public\n"
276                "  int field1;\n"
277                " @protected\n"
278                "  int field2;\n"
279                " @private\n"
280                "  int field3;\n"
281                " @package\n"
282                "  int field4;\n"
283                "}\n"
284                "+ (id)init;\n"
285                "@end");
286   verifyFormat("@interface Foo : Bar<Baz, Quux>\n"
287                "+ (id)init;\n"
288                "@end");
289   verifyFormat("@interface Foo (HackStuff)<MyProtocol>\n"
290                "+ (id)init;\n"
291                "@end");
292   Style.BinPackParameters = false;
293   Style.ColumnLimit = 80;
294   verifyFormat("@interface aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ()<\n"
295                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
296                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
297                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
298                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
299                "}");
300 }
301 
302 TEST_F(FormatTestObjC, FormatObjCImplementation) {
303   verifyFormat("@implementation Foo : NSObject {\n"
304                "@public\n"
305                "  int field1;\n"
306                "@protected\n"
307                "  int field2;\n"
308                "@private\n"
309                "  int field3;\n"
310                "@package\n"
311                "  int field4;\n"
312                "}\n"
313                "+ (id)init {\n}\n"
314                "@end");
315 
316   verifyFormat("@implementation Foo\n"
317                "+ (id)init {\n"
318                "  if (true)\n"
319                "    return nil;\n"
320                "}\n"
321                "// Look, a comment!\n"
322                "- (int)answerWith:(int)i {\n"
323                "  return i;\n"
324                "}\n"
325                "+ (int)answerWith:(int)i {\n"
326                "  return i;\n"
327                "}\n"
328                "@end");
329 
330   verifyFormat("@implementation Foo\n"
331                "@end\n"
332                "@implementation Bar\n"
333                "@end");
334 
335   EXPECT_EQ("@implementation Foo : Bar\n"
336             "+ (id)init {\n}\n"
337             "- (void)foo {\n}\n"
338             "@end",
339             format("@implementation Foo : Bar\n"
340                    "+(id)init{}\n"
341                    "-(void)foo{}\n"
342                    "@end"));
343 
344   verifyFormat("@implementation Foo {\n"
345                "  int _i;\n"
346                "}\n"
347                "+ (id)init {\n}\n"
348                "@end");
349 
350   verifyFormat("@implementation Foo : Bar {\n"
351                "  int _i;\n"
352                "}\n"
353                "+ (id)init {\n}\n"
354                "@end");
355 
356   verifyFormat("@implementation Foo (HackStuff)\n"
357                "+ (id)init {\n}\n"
358                "@end");
359   verifyFormat("@implementation ObjcClass\n"
360                "- (void)method;\n"
361                "{}\n"
362                "@end");
363 
364   Style = getGoogleStyle(FormatStyle::LK_ObjC);
365   verifyFormat("@implementation Foo : NSObject {\n"
366                " @public\n"
367                "  int field1;\n"
368                " @protected\n"
369                "  int field2;\n"
370                " @private\n"
371                "  int field3;\n"
372                " @package\n"
373                "  int field4;\n"
374                "}\n"
375                "+ (id)init {\n}\n"
376                "@end");
377 }
378 
379 TEST_F(FormatTestObjC, FormatObjCProtocol) {
380   verifyFormat("@protocol Foo\n"
381                "@property(weak) id delegate;\n"
382                "- (NSUInteger)numberOfThings;\n"
383                "@end");
384 
385   verifyFormat("@protocol MyProtocol <NSObject>\n"
386                "- (NSUInteger)numberOfThings;\n"
387                "@end");
388 
389   verifyFormat("@protocol Foo;\n"
390                "@protocol Bar;\n");
391 
392   verifyFormat("@protocol Foo\n"
393                "@end\n"
394                "@protocol Bar\n"
395                "@end");
396 
397   verifyFormat("@protocol myProtocol\n"
398                "- (void)mandatoryWithInt:(int)i;\n"
399                "@optional\n"
400                "- (void)optional;\n"
401                "@required\n"
402                "- (void)required;\n"
403                "@optional\n"
404                "@property(assign) int madProp;\n"
405                "@end\n");
406 
407   verifyFormat("@property(nonatomic, assign, readonly)\n"
408                "    int *looooooooooooooooooooooooooooongNumber;\n"
409                "@property(nonatomic, assign, readonly)\n"
410                "    NSString *looooooooooooooooooooooooooooongName;");
411 
412   verifyFormat("@implementation PR18406\n"
413                "}\n"
414                "@end");
415 
416   Style = getGoogleStyle(FormatStyle::LK_ObjC);
417   verifyFormat("@protocol MyProtocol<NSObject>\n"
418                "- (NSUInteger)numberOfThings;\n"
419                "@end");
420 }
421 
422 TEST_F(FormatTestObjC, FormatObjCMethodDeclarations) {
423   verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
424                "                   rect:(NSRect)theRect\n"
425                "               interval:(float)theInterval {\n"
426                "}");
427   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
428                "      longKeyword:(NSRect)theRect\n"
429                "    longerKeyword:(float)theInterval\n"
430                "            error:(NSError **)theError {\n"
431                "}");
432   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
433                "          longKeyword:(NSRect)theRect\n"
434                "    evenLongerKeyword:(float)theInterval\n"
435                "                error:(NSError **)theError {\n"
436                "}");
437   Style.ColumnLimit = 60;
438   verifyFormat("- (instancetype)initXxxxxx:(id<x>)x\n"
439                "                         y:(id<yyyyyyyyyyyyyyyyyyyy>)y\n"
440                "    NS_DESIGNATED_INITIALIZER;");
441   verifyFormat("- (void)drawRectOn:(id)surface\n"
442                "            ofSize:(size_t)height\n"
443                "                  :(size_t)width;");
444 
445   // Continuation indent width should win over aligning colons if the function
446   // name is long.
447   Style = getGoogleStyle(FormatStyle::LK_ObjC);
448   Style.ColumnLimit = 40;
449   Style.IndentWrappedFunctionNames = true;
450   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
451                "    dontAlignNamef:(NSRect)theRect {\n"
452                "}");
453 
454   // Make sure we don't break aligning for short parameter names.
455   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
456                "       aShortf:(NSRect)theRect {\n"
457                "}");
458 
459   // Format pairs correctly.
460   Style.ColumnLimit = 80;
461   verifyFormat("- (void)drawRectOn:(id)surface\n"
462                "            ofSize:(aaaaaaaa)height\n"
463                "                  :(size_t)width\n"
464                "          atOrigin:(size_t)x\n"
465                "                  :(size_t)y\n"
466                "             aaaaa:(a)yyy\n"
467                "               bbb:(d)cccc;");
468   verifyFormat("- (void)drawRectOn:(id)surface ofSize:(aaa)height:(bbb)width;");
469 }
470 
471 TEST_F(FormatTestObjC, FormatObjCMethodExpr) {
472   verifyFormat("[foo bar:baz];");
473   verifyFormat("return [foo bar:baz];");
474   verifyFormat("return (a)[foo bar:baz];");
475   verifyFormat("f([foo bar:baz]);");
476   verifyFormat("f(2, [foo bar:baz]);");
477   verifyFormat("f(2, a ? b : c);");
478   verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
479 
480   // Unary operators.
481   verifyFormat("int a = +[foo bar:baz];");
482   verifyFormat("int a = -[foo bar:baz];");
483   verifyFormat("int a = ![foo bar:baz];");
484   verifyFormat("int a = ~[foo bar:baz];");
485   verifyFormat("int a = ++[foo bar:baz];");
486   verifyFormat("int a = --[foo bar:baz];");
487   verifyFormat("int a = sizeof [foo bar:baz];");
488   verifyFormat("int a = alignof [foo bar:baz];");
489   verifyFormat("int a = &[foo bar:baz];");
490   verifyFormat("int a = *[foo bar:baz];");
491   // FIXME: Make casts work, without breaking f()[4].
492   // verifyFormat("int a = (int)[foo bar:baz];");
493   // verifyFormat("return (int)[foo bar:baz];");
494   // verifyFormat("(void)[foo bar:baz];");
495   verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
496 
497   // Binary operators.
498   verifyFormat("[foo bar:baz], [foo bar:baz];");
499   verifyFormat("[foo bar:baz] = [foo bar:baz];");
500   verifyFormat("[foo bar:baz] *= [foo bar:baz];");
501   verifyFormat("[foo bar:baz] /= [foo bar:baz];");
502   verifyFormat("[foo bar:baz] %= [foo bar:baz];");
503   verifyFormat("[foo bar:baz] += [foo bar:baz];");
504   verifyFormat("[foo bar:baz] -= [foo bar:baz];");
505   verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
506   verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
507   verifyFormat("[foo bar:baz] &= [foo bar:baz];");
508   verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
509   verifyFormat("[foo bar:baz] |= [foo bar:baz];");
510   verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
511   verifyFormat("[foo bar:baz] || [foo bar:baz];");
512   verifyFormat("[foo bar:baz] && [foo bar:baz];");
513   verifyFormat("[foo bar:baz] | [foo bar:baz];");
514   verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
515   verifyFormat("[foo bar:baz] & [foo bar:baz];");
516   verifyFormat("[foo bar:baz] == [foo bar:baz];");
517   verifyFormat("[foo bar:baz] != [foo bar:baz];");
518   verifyFormat("[foo bar:baz] >= [foo bar:baz];");
519   verifyFormat("[foo bar:baz] <= [foo bar:baz];");
520   verifyFormat("[foo bar:baz] > [foo bar:baz];");
521   verifyFormat("[foo bar:baz] < [foo bar:baz];");
522   verifyFormat("[foo bar:baz] >> [foo bar:baz];");
523   verifyFormat("[foo bar:baz] << [foo bar:baz];");
524   verifyFormat("[foo bar:baz] - [foo bar:baz];");
525   verifyFormat("[foo bar:baz] + [foo bar:baz];");
526   verifyFormat("[foo bar:baz] * [foo bar:baz];");
527   verifyFormat("[foo bar:baz] / [foo bar:baz];");
528   verifyFormat("[foo bar:baz] % [foo bar:baz];");
529   // Whew!
530 
531   verifyFormat("return in[42];");
532   verifyFormat("for (auto v : in[1]) {\n}");
533   verifyFormat("for (int i = 0; i < in[a]; ++i) {\n}");
534   verifyFormat("for (int i = 0; in[a] < i; ++i) {\n}");
535   verifyFormat("for (int i = 0; i < n; ++i, ++in[a]) {\n}");
536   verifyFormat("for (int i = 0; i < n; ++i, in[a]++) {\n}");
537   verifyFormat("for (int i = 0; i < f(in[a]); ++i, in[a]++) {\n}");
538   verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
539                "}");
540   verifyFormat("[self aaaaa:MACRO(a, b:, c:)];");
541   verifyFormat("[self aaaaa:(1 + 2) bbbbb:3];");
542   verifyFormat("[self aaaaa:(Type)a bbbbb:3];");
543 
544   verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
545   verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
546   verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
547   verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
548   verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
549   verifyFormat("[button setAction:@selector(zoomOut:)];");
550   verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
551 
552   verifyFormat("arr[[self indexForFoo:a]];");
553   verifyFormat("throw [self errorFor:a];");
554   verifyFormat("@throw [self errorFor:a];");
555 
556   verifyFormat("[(id)foo bar:(id)baz quux:(id)snorf];");
557   verifyFormat("[(id)foo bar:(id) ? baz : quux];");
558   verifyFormat("4 > 4 ? (id)a : (id)baz;");
559 
560   // This tests that the formatter doesn't break after "backing" but before ":",
561   // which would be at 80 columns.
562   verifyFormat(
563       "void f() {\n"
564       "  if ((self = [super initWithContentRect:contentRect\n"
565       "                               styleMask:styleMask ?: otherMask\n"
566       "                                 backing:NSBackingStoreBuffered\n"
567       "                                   defer:YES]))");
568 
569   verifyFormat(
570       "[foo checkThatBreakingAfterColonWorksOk:\n"
571       "         [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
572 
573   verifyFormat("[myObj short:arg1 // Force line break\n"
574                "          longKeyword:arg2 != nil ? arg2 : @\"longKeyword\"\n"
575                "    evenLongerKeyword:arg3 ?: @\"evenLongerKeyword\"\n"
576                "                error:arg4];");
577   verifyFormat(
578       "void f() {\n"
579       "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
580       "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
581       "                                     pos.width(), pos.height())\n"
582       "                styleMask:NSBorderlessWindowMask\n"
583       "                  backing:NSBackingStoreBuffered\n"
584       "                    defer:NO]);\n"
585       "}");
586   verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
587                "                             with:contentsNativeView];");
588 
589   verifyFormat(
590       "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
591       "           owner:nillllll];");
592 
593   verifyFormat(
594       "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
595       "        forType:kBookmarkButtonDragType];");
596 
597   verifyFormat("[defaultCenter addObserver:self\n"
598                "                  selector:@selector(willEnterFullscreen)\n"
599                "                      name:kWillEnterFullscreenNotification\n"
600                "                    object:nil];");
601   verifyFormat("[image_rep drawInRect:drawRect\n"
602                "             fromRect:NSZeroRect\n"
603                "            operation:NSCompositeCopy\n"
604                "             fraction:1.0\n"
605                "       respectFlipped:NO\n"
606                "                hints:nil];");
607   verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
608                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
609   verifyFormat("[aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
610                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
611   verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaa[aaaaaaaaaaaaaaaaaaaaa]\n"
612                "    aaaaaaaaaaaaaaaaaaaaaa];");
613 
614   verifyFormat(
615       "scoped_nsobject<NSTextField> message(\n"
616       "    // The frame will be fixed up when |-setMessageText:| is called.\n"
617       "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
618   verifyFormat("[self aaaaaa:bbbbbbbbbbbbb\n"
619                "    aaaaaaaaaa:bbbbbbbbbbbbbbbbb\n"
620                "         aaaaa:bbbbbbbbbbb + bbbbbbbbbbbb\n"
621                "          aaaa:bbb];");
622   verifyFormat("[self param:function( //\n"
623                "                parameter)]");
624   verifyFormat(
625       "[self aaaaaaaaaa:aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
626       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
627       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa];");
628 
629   // Variadic parameters.
630   verifyFormat(
631       "NSArray *myStrings = [NSArray stringarray:@\"a\", @\"b\", nil];");
632   verifyFormat(
633       "[self aaaaaaaaaaaaa:aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
634       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
635       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa];");
636   verifyFormat("[self // break\n"
637                "      a:a\n"
638                "    aaa:aaa];");
639   verifyFormat("bool a = ([aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaa ||\n"
640                "          [aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaaaaa);");
641 
642   // Formats pair-parameters.
643   verifyFormat("[I drawRectOn:surface ofSize:aa:bbb atOrigin:cc:dd];");
644   verifyFormat("[I drawRectOn:surface //\n"
645                "        ofSize:aa:bbb\n"
646                "      atOrigin:cc:dd];");
647 
648   Style.ColumnLimit = 70;
649   verifyFormat(
650       "void f() {\n"
651       "  popup_wdow_.reset([[RenderWidgetPopupWindow alloc]\n"
652       "      iniithContentRect:NSMakRet(origin_global.x, origin_global.y,\n"
653       "                                 pos.width(), pos.height())\n"
654       "                syeMask:NSBorderlessWindowMask\n"
655       "                  bking:NSBackingStoreBuffered\n"
656       "                    der:NO]);\n"
657       "}");
658 
659   Style.ColumnLimit = 60;
660   verifyFormat("[call aaaaaaaa.aaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa\n"
661                "        .aaaaaaaa];"); // FIXME: Indentation seems off.
662   // FIXME: This violates the column limit.
663   verifyFormat(
664       "[aaaaaaaaaaaaaaaaaaaaaaaaa\n"
665       "    aaaaaaaaaaaaaaaaa:aaaaaaaa\n"
666       "                  aaa:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
667 
668   Style = getChromiumStyle(FormatStyle::LK_ObjC);
669   Style.ColumnLimit = 80;
670   verifyFormat(
671       "void f() {\n"
672       "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
673       "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
674       "                                     pos.width(), pos.height())\n"
675       "                styleMask:NSBorderlessWindowMask\n"
676       "                  backing:NSBackingStoreBuffered\n"
677       "                    defer:NO]);\n"
678       "}");
679 }
680 
681 TEST_F(FormatTestObjC, ObjCAt) {
682   verifyFormat("@autoreleasepool");
683   verifyFormat("@catch");
684   verifyFormat("@class");
685   verifyFormat("@compatibility_alias");
686   verifyFormat("@defs");
687   verifyFormat("@dynamic");
688   verifyFormat("@encode");
689   verifyFormat("@end");
690   verifyFormat("@finally");
691   verifyFormat("@implementation");
692   verifyFormat("@import");
693   verifyFormat("@interface");
694   verifyFormat("@optional");
695   verifyFormat("@package");
696   verifyFormat("@private");
697   verifyFormat("@property");
698   verifyFormat("@protected");
699   verifyFormat("@protocol");
700   verifyFormat("@public");
701   verifyFormat("@required");
702   verifyFormat("@selector");
703   verifyFormat("@synchronized");
704   verifyFormat("@synthesize");
705   verifyFormat("@throw");
706   verifyFormat("@try");
707 
708   EXPECT_EQ("@interface", format("@ interface"));
709 
710   // The precise formatting of this doesn't matter, nobody writes code like
711   // this.
712   verifyFormat("@ /*foo*/ interface");
713 }
714 
715 TEST_F(FormatTestObjC, ObjCSnippets) {
716   verifyFormat("@autoreleasepool {\n"
717                "  foo();\n"
718                "}");
719   verifyFormat("@class Foo, Bar;");
720   verifyFormat("@compatibility_alias AliasName ExistingClass;");
721   verifyFormat("@dynamic textColor;");
722   verifyFormat("char *buf1 = @encode(int *);");
723   verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
724   verifyFormat("char *buf1 = @encode(int **);");
725   verifyFormat("Protocol *proto = @protocol(p1);");
726   verifyFormat("SEL s = @selector(foo:);");
727   verifyFormat("@synchronized(self) {\n"
728                "  f();\n"
729                "}");
730 
731   verifyFormat("@import foo.bar;\n"
732                "@import baz;");
733 
734   verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
735 
736   verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
737   verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
738 
739   Style = getMozillaStyle();
740   verifyFormat("@property (assign, getter=isEditable) BOOL editable;");
741   verifyFormat("@property BOOL editable;");
742 
743   Style = getWebKitStyle();
744   verifyFormat("@property (assign, getter=isEditable) BOOL editable;");
745   verifyFormat("@property BOOL editable;");
746 
747   Style = getGoogleStyle(FormatStyle::LK_ObjC);
748   verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
749   verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
750 }
751 
752 TEST_F(FormatTestObjC, ObjCForIn) {
753   verifyFormat("- (void)test {\n"
754                "  for (NSString *n in arrayOfStrings) {\n"
755                "    foo(n);\n"
756                "  }\n"
757                "}");
758   verifyFormat("- (void)test {\n"
759                "  for (NSString *n in (__bridge NSArray *)arrayOfStrings) {\n"
760                "    foo(n);\n"
761                "  }\n"
762                "}");
763 }
764 
765 TEST_F(FormatTestObjC, ObjCLiterals) {
766   verifyFormat("@\"String\"");
767   verifyFormat("@1");
768   verifyFormat("@+4.8");
769   verifyFormat("@-4");
770   verifyFormat("@1LL");
771   verifyFormat("@.5");
772   verifyFormat("@'c'");
773   verifyFormat("@true");
774 
775   verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
776   verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
777   verifyFormat("NSNumber *favoriteColor = @(Green);");
778   verifyFormat("NSString *path = @(getenv(\"PATH\"));");
779 
780   verifyFormat("[dictionary setObject:@(1) forKey:@\"number\"];");
781 }
782 
783 TEST_F(FormatTestObjC, ObjCDictLiterals) {
784   verifyFormat("@{");
785   verifyFormat("@{}");
786   verifyFormat("@{@\"one\" : @1}");
787   verifyFormat("return @{@\"one\" : @1;");
788   verifyFormat("@{@\"one\" : @1}");
789 
790   verifyFormat("@{@\"one\" : @{@2 : @1}}");
791   verifyFormat("@{\n"
792                "  @\"one\" : @{@2 : @1},\n"
793                "}");
794 
795   verifyFormat("@{1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2}");
796   verifyIncompleteFormat("[self setDict:@{}");
797   verifyIncompleteFormat("[self setDict:@{@1 : @2}");
798   verifyFormat("NSLog(@\"%@\", @{@1 : @2, @2 : @3}[@1]);");
799   verifyFormat(
800       "NSDictionary *masses = @{@\"H\" : @1.0078, @\"He\" : @4.0026};");
801   verifyFormat(
802       "NSDictionary *settings = @{AVEncoderKey : @(AVAudioQualityMax)};");
803 
804   verifyFormat("NSDictionary *d = @{\n"
805                "  @\"nam\" : NSUserNam(),\n"
806                "  @\"dte\" : [NSDate date],\n"
807                "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
808                "};");
809   verifyFormat(
810       "@{\n"
811       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
812       "regularFont,\n"
813       "};");
814   verifyFormat(
815       "@{\n"
816       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :\n"
817       "      reeeeeeeeeeeeeeeeeeeeeeeegularFont,\n"
818       "};");
819 
820   // We should try to be robust in case someone forgets the "@".
821   verifyFormat("NSDictionary *d = {\n"
822                "  @\"nam\" : NSUserNam(),\n"
823                "  @\"dte\" : [NSDate date],\n"
824                "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
825                "};");
826   verifyFormat("NSMutableDictionary *dictionary =\n"
827                "    [NSMutableDictionary dictionaryWithDictionary:@{\n"
828                "      aaaaaaaaaaaaaaaaaaaaa : aaaaaaaaaaaaa,\n"
829                "      bbbbbbbbbbbbbbbbbb : bbbbb,\n"
830                "      cccccccccccccccc : ccccccccccccccc\n"
831                "    }];");
832 
833   // Ensure that casts before the key are kept on the same line as the key.
834   verifyFormat(
835       "NSDictionary *d = @{\n"
836       "  (aaaaaaaa id)aaaaaaaaa : (aaaaaaaa id)aaaaaaaaaaaaaaaaaaaaaaaa,\n"
837       "  (aaaaaaaa id)aaaaaaaaaaaaaa : (aaaaaaaa id)aaaaaaaaaaaaaa,\n"
838       "};");
839 
840   Style = getGoogleStyle(FormatStyle::LK_ObjC);
841   verifyFormat(
842       "@{\n"
843       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
844       "regularFont,\n"
845       "};");
846 }
847 
848 TEST_F(FormatTestObjC, ObjCArrayLiterals) {
849   verifyIncompleteFormat("@[");
850   verifyFormat("@[]");
851   verifyFormat(
852       "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
853   verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
854   verifyFormat("NSArray *array = @[ [foo description] ];");
855 
856   verifyFormat(
857       "NSArray *some_variable = @[\n"
858       "  aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
859       "  @\"aaaaaaaaaaaaaaaaa\",\n"
860       "  @\"aaaaaaaaaaaaaaaaa\",\n"
861       "  @\"aaaaaaaaaaaaaaaaa\",\n"
862       "];");
863   verifyFormat(
864       "NSArray *some_variable = @[\n"
865       "  aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
866       "  @\"aaaaaaaaaaaaaaaa\", @\"aaaaaaaaaaaaaaaa\", @\"aaaaaaaaaaaaaaaa\"\n"
867       "];");
868   verifyFormat("NSArray *some_variable = @[\n"
869                "  @\"aaaaaaaaaaaaaaaaa\",\n"
870                "  @\"aaaaaaaaaaaaaaaaa\",\n"
871                "  @\"aaaaaaaaaaaaaaaaa\",\n"
872                "  @\"aaaaaaaaaaaaaaaaa\",\n"
873                "];");
874   verifyFormat("NSArray *array = @[\n"
875                "  @\"a\",\n"
876                "  @\"a\",\n" // Trailing comma -> one per line.
877                "];");
878 
879   // We should try to be robust in case someone forgets the "@".
880   verifyFormat("NSArray *some_variable = [\n"
881                "  @\"aaaaaaaaaaaaaaaaa\",\n"
882                "  @\"aaaaaaaaaaaaaaaaa\",\n"
883                "  @\"aaaaaaaaaaaaaaaaa\",\n"
884                "  @\"aaaaaaaaaaaaaaaaa\",\n"
885                "];");
886   verifyFormat(
887       "- (NSAttributedString *)attributedStringForSegment:(NSUInteger)segment\n"
888       "                                             index:(NSUInteger)index\n"
889       "                                nonDigitAttributes:\n"
890       "                                    (NSDictionary *)noDigitAttributes;");
891   verifyFormat("[someFunction someLooooooooooooongParameter:@[\n"
892                "  NSBundle.mainBundle.infoDictionary[@\"a\"]\n"
893                "]];");
894 }
895 } // end namespace
896 } // end namespace format
897 } // end namespace clang
898