xref: /llvm-project/clang/unittests/Format/FormatTestObjC.cpp (revision 24b5266892c30e2c9cb6ea28c2631e988a5754b6)
1 //===- unittest/Format/FormatTestObjC.cpp - Formatting unit tests----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Format/Format.h"
10 
11 #include "../Tooling/ReplacementTest.h"
12 #include "FormatTestUtils.h"
13 
14 #include "clang/Frontend/TextDiagnosticPrinter.h"
15 #include "llvm/Support/Debug.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "gtest/gtest.h"
18 
19 #define DEBUG_TYPE "format-test"
20 
21 using clang::tooling::ReplacementTest;
22 
23 namespace clang {
24 namespace format {
25 namespace {
26 
27 class FormatTestObjC : public ::testing::Test {
28 protected:
29   FormatTestObjC() {
30     Style = getLLVMStyle();
31     Style.Language = FormatStyle::LK_ObjC;
32   }
33 
34   enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck };
35 
36   std::string format(llvm::StringRef Code,
37                      StatusCheck CheckComplete = SC_ExpectComplete) {
38     LLVM_DEBUG(llvm::errs() << "---\n");
39     LLVM_DEBUG(llvm::errs() << Code << "\n\n");
40     std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
41     FormattingAttemptStatus Status;
42     tooling::Replacements Replaces =
43         reformat(Style, Code, Ranges, "<stdin>", &Status);
44     if (CheckComplete != SC_DoNotCheck) {
45       bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete;
46       EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete)
47           << Code << "\n\n";
48     }
49     auto Result = applyAllReplacements(Code, Replaces);
50     EXPECT_TRUE(static_cast<bool>(Result));
51     LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
52     return *Result;
53   }
54 
55   void verifyFormat(StringRef Code) {
56     EXPECT_EQ(Code.str(), format(Code)) << "Expected code is not stable";
57     EXPECT_EQ(Code.str(), format(test::messUp(Code)));
58   }
59 
60   void verifyIncompleteFormat(StringRef Code) {
61     EXPECT_EQ(Code.str(), format(test::messUp(Code), SC_ExpectIncomplete));
62   }
63 
64   FormatStyle Style;
65 };
66 
67 TEST(FormatTestObjCStyle, DetectsObjCInHeaders) {
68   auto Style = getStyle("LLVM", "a.h", "none",
69                         "@interface\n"
70                         "- (id)init;");
71   ASSERT_TRUE((bool)Style);
72   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
73 
74   Style = getStyle("LLVM", "a.h", "none",
75                    "@interface\n"
76                    "+ (id)init;");
77   ASSERT_TRUE((bool)Style);
78   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
79 
80   Style = getStyle("LLVM", "a.h", "none",
81                    "@interface\n"
82                    "@end\n"
83                    "//comment");
84   ASSERT_TRUE((bool)Style);
85   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
86 
87   Style = getStyle("LLVM", "a.h", "none",
88                    "@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", "typedef NS_ENUM(int, Foo) {};\n");
117   ASSERT_TRUE((bool)Style);
118   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
119 
120   Style =
121       getStyle("{}", "a.h", "none", "typedef NS_CLOSED_ENUM(int, 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 =
130       getStyle("{}", "a.h", "none", "inline void Foo() { Log(@\"Foo\"); }\n");
131   ASSERT_TRUE((bool)Style);
132   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
133 
134   Style =
135       getStyle("{}", "a.h", "none", "inline void Foo() { Log(\"Foo\"); }\n");
136   ASSERT_TRUE((bool)Style);
137   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
138 
139   Style =
140       getStyle("{}", "a.h", "none", "inline void Foo() { id = @[1, 2, 3]; }\n");
141   ASSERT_TRUE((bool)Style);
142   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
143 
144   Style = getStyle("{}", "a.h", "none",
145                    "inline void Foo() { id foo = @{1: 2, 3: 4, 5: 6}; }\n");
146   ASSERT_TRUE((bool)Style);
147   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
148 
149   Style = getStyle("{}", "a.h", "none",
150                    "inline void Foo() { int foo[] = {1, 2, 3}; }\n");
151   ASSERT_TRUE((bool)Style);
152   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
153 
154   // ObjC characteristic types.
155   Style = getStyle("{}", "a.h", "none", "extern NSString *kFoo;\n");
156   ASSERT_TRUE((bool)Style);
157   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
158 
159   Style = getStyle("{}", "a.h", "none", "extern NSInteger Foo();\n");
160   ASSERT_TRUE((bool)Style);
161   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
162 
163   Style = getStyle("{}", "a.h", "none", "NSObject *Foo();\n");
164   ASSERT_TRUE((bool)Style);
165   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
166 
167   Style = getStyle("{}", "a.h", "none", "NSSet *Foo();\n");
168   ASSERT_TRUE((bool)Style);
169   EXPECT_EQ(FormatStyle::LK_ObjC, Style->Language);
170 }
171 
172 TEST(FormatTestObjCStyle, AvoidDetectingDesignatedInitializersAsObjCInHeaders) {
173   auto Style = getStyle("LLVM", "a.h", "none",
174                         "static const char *names[] = {[0] = \"foo\",\n"
175                         "[kBar] = \"bar\"};");
176   ASSERT_TRUE((bool)Style);
177   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
178 
179   Style = getStyle("LLVM", "a.h", "none",
180                    "static const char *names[] = {[0] EQ \"foo\",\n"
181                    "[kBar] EQ \"bar\"};");
182   ASSERT_TRUE((bool)Style);
183   EXPECT_EQ(FormatStyle::LK_Cpp, Style->Language);
184 }
185 
186 TEST_F(FormatTestObjC, FormatObjCTryCatch) {
187   verifyFormat("@try {\n"
188                "  f();\n"
189                "} @catch (NSException e) {\n"
190                "  @throw;\n"
191                "} @finally {\n"
192                "  exit(42);\n"
193                "}");
194   verifyFormat("DEBUG({\n"
195                "  @try {\n"
196                "  } @finally {\n"
197                "  }\n"
198                "});\n");
199 }
200 
201 TEST_F(FormatTestObjC, FormatObjCAutoreleasepool) {
202   verifyFormat("@autoreleasepool {\n"
203                "  f();\n"
204                "}\n"
205                "@autoreleasepool {\n"
206                "  f();\n"
207                "}\n");
208   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
209   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
210   verifyFormat("@autoreleasepool\n"
211                "{\n"
212                "  f();\n"
213                "}\n"
214                "@autoreleasepool\n"
215                "{\n"
216                "  f();\n"
217                "}\n");
218 }
219 
220 TEST_F(FormatTestObjC, FormatObjCGenerics) {
221   Style.ColumnLimit = 40;
222   verifyFormat("int aaaaaaaaaaaaaaaa(\n"
223                "    NSArray<aaaaaaaaaaaaaaaaaa *>\n"
224                "        aaaaaaaaaaaaaaaaa);\n");
225   verifyFormat("int aaaaaaaaaaaaaaaa(\n"
226                "    NSArray<aaaaaaaaaaaaaaaaaaa<\n"
227                "        aaaaaaaaaaaaaaaa *> *>\n"
228                "        aaaaaaaaaaaaaaaaa);\n");
229 }
230 
231 TEST_F(FormatTestObjC, FormatObjCSynchronized) {
232   verifyFormat("@synchronized(self) {\n"
233                "  f();\n"
234                "}\n"
235                "@synchronized(self) {\n"
236                "  f();\n"
237                "}\n");
238   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
239   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
240   verifyFormat("@synchronized(self)\n"
241                "{\n"
242                "  f();\n"
243                "}\n"
244                "@synchronized(self)\n"
245                "{\n"
246                "  f();\n"
247                "}\n");
248 }
249 
250 TEST_F(FormatTestObjC, FormatObjCInterface) {
251   verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
252                "@public\n"
253                "  int field1;\n"
254                "@protected\n"
255                "  int field2;\n"
256                "@private\n"
257                "  int field3;\n"
258                "@package\n"
259                "  int field4;\n"
260                "}\n"
261                "+ (id)init;\n"
262                "@end");
263 
264   verifyFormat("@interface /* wait for it */ Foo\n"
265                "+ (id)init;\n"
266                "// Look, a comment!\n"
267                "- (int)answerWith:(int)i;\n"
268                "@end");
269 
270   verifyFormat("@interface Foo\n"
271                "@end\n"
272                "@interface Bar\n"
273                "@end");
274 
275   verifyFormat("@interface Foo : Bar\n"
276                "@property(assign, readwrite) NSInteger bar;\n"
277                "+ (id)init;\n"
278                "@end");
279 
280   verifyFormat("FOUNDATION_EXPORT NS_AVAILABLE_IOS(10.0) @interface Foo : Bar\n"
281                "@property(assign, readwrite) NSInteger bar;\n"
282                "+ (id)init;\n"
283                "@end");
284 
285   verifyFormat("@interface Foo : /**/ Bar /**/ <Baz, /**/ Quux>\n"
286                "+ (id)init;\n"
287                "@end");
288 
289   verifyFormat("@interface Foo (HackStuff)\n"
290                "+ (id)init;\n"
291                "@end");
292 
293   verifyFormat("@interface Foo ()\n"
294                "+ (id)init;\n"
295                "@end");
296 
297   verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
298                "+ (id)init;\n"
299                "@end");
300 
301   verifyFormat("@interface Foo {\n"
302                "  int _i;\n"
303                "}\n"
304                "+ (id)init;\n"
305                "@end");
306 
307   verifyFormat("@interface Foo : Bar {\n"
308                "  int _i;\n"
309                "}\n"
310                "+ (id)init;\n"
311                "@end");
312 
313   verifyFormat("@interface Foo : Bar <Baz, Quux> {\n"
314                "  int _i;\n"
315                "}\n"
316                "+ (id)init;\n"
317                "@end");
318 
319   verifyFormat("@interface Foo<Baz : Blech> : Bar <Baz, Quux> {\n"
320                "  int _i;\n"
321                "}\n"
322                "+ (id)init;\n"
323                "@end");
324 
325   verifyFormat("@interface Foo<Bar : Baz <Blech>> : Xyzzy <Corge> {\n"
326                "  int _i;\n"
327                "}\n"
328                "+ (id)init;\n"
329                "@end");
330 
331   verifyFormat("@interface Foo<Bar : Baz <Blech>> : Xyzzy <Corge> <Quux> {\n"
332                "  int _i;\n"
333                "}\n"
334                "+ (id)init;\n"
335                "@end");
336 
337   verifyFormat("@interface Foo : Bar <Baz> <Blech>\n"
338                "@end");
339 
340   verifyFormat("@interface Foo : Bar <Baz> <Blech, Xyzzy, Corge>\n"
341                "@end");
342 
343   verifyFormat("@interface Foo (HackStuff) {\n"
344                "  int _i;\n"
345                "}\n"
346                "+ (id)init;\n"
347                "@end");
348 
349   verifyFormat("@interface Foo () {\n"
350                "  int _i;\n"
351                "}\n"
352                "+ (id)init;\n"
353                "@end");
354 
355   verifyFormat("@interface Foo (HackStuff) <MyProtocol> {\n"
356                "  int _i;\n"
357                "}\n"
358                "+ (id)init;\n"
359                "@end");
360   verifyFormat("@interface Foo\n"
361                "- (void)foo {\n"
362                "}\n"
363                "@end\n"
364                "@implementation Bar\n"
365                "- (void)bar {\n"
366                "}\n"
367                "@end");
368   Style.ColumnLimit = 40;
369   verifyFormat("@interface ccccccccccccc () <\n"
370                "    ccccccccccccc, ccccccccccccc,\n"
371                "    ccccccccccccc, ccccccccccccc> {\n"
372                "}");
373   verifyFormat("@interface ccccccccccccc (ccccccccccc) <\n"
374                "    ccccccccccccc> {\n"
375                "}");
376   Style.ObjCBinPackProtocolList = FormatStyle::BPS_Never;
377   verifyFormat("@interface ddddddddddddd () <\n"
378                "    ddddddddddddd,\n"
379                "    ddddddddddddd,\n"
380                "    ddddddddddddd,\n"
381                "    ddddddddddddd> {\n"
382                "}");
383 
384   Style.BinPackParameters = false;
385   Style.ObjCBinPackProtocolList = FormatStyle::BPS_Auto;
386   verifyFormat("@interface eeeeeeeeeeeee () <\n"
387                "    eeeeeeeeeeeee,\n"
388                "    eeeeeeeeeeeee,\n"
389                "    eeeeeeeeeeeee,\n"
390                "    eeeeeeeeeeeee> {\n"
391                "}");
392   Style.ObjCBinPackProtocolList = FormatStyle::BPS_Always;
393   verifyFormat("@interface fffffffffffff () <\n"
394                "    fffffffffffff, fffffffffffff,\n"
395                "    fffffffffffff, fffffffffffff> {\n"
396                "}");
397 
398   Style = getGoogleStyle(FormatStyle::LK_ObjC);
399   verifyFormat("@interface Foo : NSObject <NSSomeDelegate> {\n"
400                " @public\n"
401                "  int field1;\n"
402                " @protected\n"
403                "  int field2;\n"
404                " @private\n"
405                "  int field3;\n"
406                " @package\n"
407                "  int field4;\n"
408                "}\n"
409                "+ (id)init;\n"
410                "@end");
411   verifyFormat("@interface Foo : Bar <Baz, Quux>\n"
412                "+ (id)init;\n"
413                "@end");
414   verifyFormat("@interface Foo (HackStuff) <MyProtocol>\n"
415                "+ (id)init;\n"
416                "@end");
417   Style.ColumnLimit = 40;
418   // BinPackParameters should be true by default.
419   verifyFormat("void eeeeeeee(int eeeee, int eeeee,\n"
420                "              int eeeee, int eeeee);\n");
421   // ObjCBinPackProtocolList should be BPS_Never by default.
422   verifyFormat("@interface fffffffffffff () <\n"
423                "    fffffffffffff,\n"
424                "    fffffffffffff,\n"
425                "    fffffffffffff,\n"
426                "    fffffffffffff> {\n"
427                "}");
428   verifyFormat("@interface ggggggggggggg\n"
429                "    : ggggggggggggg <ggggggggggggg>\n"
430                "      <ggggggggggggg>\n"
431                "@end");
432 }
433 
434 TEST_F(FormatTestObjC, FormatObjCImplementation) {
435   verifyFormat("@implementation Foo : NSObject {\n"
436                "@public\n"
437                "  int field1;\n"
438                "@protected\n"
439                "  int field2;\n"
440                "@private\n"
441                "  int field3;\n"
442                "@package\n"
443                "  int field4;\n"
444                "}\n"
445                "+ (id)init {\n}\n"
446                "@end");
447 
448   verifyFormat("@implementation Foo\n"
449                "+ (id)init {\n"
450                "  if (true)\n"
451                "    return nil;\n"
452                "}\n"
453                "// Look, a comment!\n"
454                "- (int)answerWith:(int)i {\n"
455                "  return i;\n"
456                "}\n"
457                "+ (int)answerWith:(int)i {\n"
458                "  return i;\n"
459                "}\n"
460                "@end");
461 
462   verifyFormat("@implementation Foo\n"
463                "@end\n"
464                "@implementation Bar\n"
465                "@end");
466 
467   EXPECT_EQ("@implementation Foo : Bar\n"
468             "+ (id)init {\n}\n"
469             "- (void)foo {\n}\n"
470             "@end",
471             format("@implementation Foo : Bar\n"
472                    "+(id)init{}\n"
473                    "-(void)foo{}\n"
474                    "@end"));
475 
476   verifyFormat("@implementation Foo {\n"
477                "  int _i;\n"
478                "}\n"
479                "+ (id)init {\n}\n"
480                "@end");
481 
482   verifyFormat("@implementation Foo : Bar {\n"
483                "  int _i;\n"
484                "}\n"
485                "+ (id)init {\n}\n"
486                "@end");
487 
488   verifyFormat("@implementation Foo (HackStuff)\n"
489                "+ (id)init {\n}\n"
490                "@end");
491   verifyFormat("@implementation ObjcClass\n"
492                "- (void)method;\n"
493                "{}\n"
494                "@end");
495 
496   Style = getGoogleStyle(FormatStyle::LK_ObjC);
497   verifyFormat("@implementation Foo : NSObject {\n"
498                " @public\n"
499                "  int field1;\n"
500                " @protected\n"
501                "  int field2;\n"
502                " @private\n"
503                "  int field3;\n"
504                " @package\n"
505                "  int field4;\n"
506                "}\n"
507                "+ (id)init {\n}\n"
508                "@end");
509 }
510 
511 TEST_F(FormatTestObjC, FormatObjCProtocol) {
512   verifyFormat("@protocol Foo\n"
513                "@property(weak) id delegate;\n"
514                "- (NSUInteger)numberOfThings;\n"
515                "@end");
516 
517   verifyFormat("@protocol MyProtocol <NSObject>\n"
518                "- (NSUInteger)numberOfThings;\n"
519                "@end");
520 
521   verifyFormat("@protocol Foo;\n"
522                "@protocol Bar;\n");
523 
524   verifyFormat("@protocol Foo\n"
525                "@end\n"
526                "@protocol Bar\n"
527                "@end");
528 
529   verifyFormat("FOUNDATION_EXPORT NS_AVAILABLE_IOS(10.0) @protocol Foo\n"
530                "@property(assign, readwrite) NSInteger bar;\n"
531                "@end");
532 
533   verifyFormat("@protocol myProtocol\n"
534                "- (void)mandatoryWithInt:(int)i;\n"
535                "@optional\n"
536                "- (void)optional;\n"
537                "@required\n"
538                "- (void)required;\n"
539                "@optional\n"
540                "@property(assign) int madProp;\n"
541                "@end\n");
542 
543   verifyFormat("@property(nonatomic, assign, readonly)\n"
544                "    int *looooooooooooooooooooooooooooongNumber;\n"
545                "@property(nonatomic, assign, readonly)\n"
546                "    NSString *looooooooooooooooooooooooooooongName;");
547 
548   verifyFormat("@implementation PR18406\n"
549                "}\n"
550                "@end");
551 
552   Style = getGoogleStyle(FormatStyle::LK_ObjC);
553   verifyFormat("@protocol MyProtocol <NSObject>\n"
554                "- (NSUInteger)numberOfThings;\n"
555                "@end");
556 }
557 
558 TEST_F(FormatTestObjC, FormatObjCMethodDeclarations) {
559   verifyFormat("- (void)doSomethingWith:(GTMFoo *)theFoo\n"
560                "                   rect:(NSRect)theRect\n"
561                "               interval:(float)theInterval {\n"
562                "}");
563   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
564                "      longKeyword:(NSRect)theRect\n"
565                "    longerKeyword:(float)theInterval\n"
566                "            error:(NSError **)theError {\n"
567                "}");
568   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
569                "          longKeyword:(NSRect)theRect\n"
570                "    evenLongerKeyword:(float)theInterval\n"
571                "                error:(NSError **)theError {\n"
572                "}");
573   verifyFormat("+ (instancetype)new;\n");
574   Style.ColumnLimit = 60;
575   verifyFormat("- (instancetype)initXxxxxx:(id<x>)x\n"
576                "                         y:(id<yyyyyyyyyyyyyyyyyyyy>)y\n"
577                "    NS_DESIGNATED_INITIALIZER;");
578   verifyFormat("- (void)drawRectOn:(id)surface\n"
579                "            ofSize:(size_t)height\n"
580                "                  :(size_t)width;");
581   Style.ColumnLimit = 40;
582   // Make sure selectors with 0, 1, or more arguments are indented when wrapped.
583   verifyFormat("- (aaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
584                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n");
585   verifyFormat("- (aaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
586                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa:(int)a;\n");
587   verifyFormat("- (aaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
588                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa:(int)a\n"
589                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa:(int)a;\n");
590   verifyFormat("- (aaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
591                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa:(int)a\n"
592                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa:(int)a;\n");
593   verifyFormat("- (aaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
594                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa:(int)a\n"
595                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa:(int)a;\n");
596 
597   // Continuation indent width should win over aligning colons if the function
598   // name is long.
599   Style = getGoogleStyle(FormatStyle::LK_ObjC);
600   Style.ColumnLimit = 40;
601   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
602                "    dontAlignNamef:(NSRect)theRect {\n"
603                "}");
604 
605   // Make sure we don't break aligning for short parameter names.
606   verifyFormat("- (void)shortf:(GTMFoo *)theFoo\n"
607                "       aShortf:(NSRect)theRect {\n"
608                "}");
609 
610   // Format pairs correctly.
611   Style.ColumnLimit = 80;
612   verifyFormat("- (void)drawRectOn:(id)surface\n"
613                "            ofSize:(aaaaaaaa)height\n"
614                "                  :(size_t)width\n"
615                "          atOrigin:(size_t)x\n"
616                "                  :(size_t)y\n"
617                "             aaaaa:(a)yyy\n"
618                "               bbb:(d)cccc;");
619   verifyFormat("- (void)drawRectOn:(id)surface ofSize:(aaa)height:(bbb)width;");
620 
621   // BraceWrapping AfterFunction is respected for ObjC methods
622   Style = getGoogleStyle(FormatStyle::LK_ObjC);
623   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
624   Style.BraceWrapping.AfterFunction = true;
625   verifyFormat("@implementation Foo\n"
626                "- (void)foo:(id)bar\n"
627                "{\n"
628                "}\n"
629                "@end\n");
630 }
631 
632 TEST_F(FormatTestObjC, FormatObjCMethodExpr) {
633   verifyFormat("[foo bar:baz];");
634   verifyFormat("[foo bar]->baz;");
635   verifyFormat("return [foo bar:baz];");
636   verifyFormat("return (a)[foo bar:baz];");
637   verifyFormat("f([foo bar:baz]);");
638   verifyFormat("f(2, [foo bar:baz]);");
639   verifyFormat("f(2, a ? b : c);");
640   verifyFormat("[[self initWithInt:4] bar:[baz quux:arrrr]];");
641 
642   // Unary operators.
643   verifyFormat("int a = +[foo bar:baz];");
644   verifyFormat("int a = -[foo bar:baz];");
645   verifyFormat("int a = ![foo bar:baz];");
646   verifyFormat("int a = ~[foo bar:baz];");
647   verifyFormat("int a = ++[foo bar:baz];");
648   verifyFormat("int a = --[foo bar:baz];");
649   verifyFormat("int a = sizeof [foo bar:baz];");
650   verifyFormat("int a = alignof [foo bar:baz];");
651   verifyFormat("int a = &[foo bar:baz];");
652   verifyFormat("int a = *[foo bar:baz];");
653   // FIXME: Make casts work, without breaking f()[4].
654   // verifyFormat("int a = (int)[foo bar:baz];");
655   // verifyFormat("return (int)[foo bar:baz];");
656   // verifyFormat("(void)[foo bar:baz];");
657   verifyFormat("return (MyType *)[self.tableView cellForRowAtIndexPath:cell];");
658 
659   // Binary operators.
660   verifyFormat("[foo bar:baz], [foo bar:baz];");
661   verifyFormat("[foo bar:baz] = [foo bar:baz];");
662   verifyFormat("[foo bar:baz] *= [foo bar:baz];");
663   verifyFormat("[foo bar:baz] /= [foo bar:baz];");
664   verifyFormat("[foo bar:baz] %= [foo bar:baz];");
665   verifyFormat("[foo bar:baz] += [foo bar:baz];");
666   verifyFormat("[foo bar:baz] -= [foo bar:baz];");
667   verifyFormat("[foo bar:baz] <<= [foo bar:baz];");
668   verifyFormat("[foo bar:baz] >>= [foo bar:baz];");
669   verifyFormat("[foo bar:baz] &= [foo bar:baz];");
670   verifyFormat("[foo bar:baz] ^= [foo bar:baz];");
671   verifyFormat("[foo bar:baz] |= [foo bar:baz];");
672   verifyFormat("[foo bar:baz] ? [foo bar:baz] : [foo bar:baz];");
673   verifyFormat("[foo bar:baz] || [foo bar:baz];");
674   verifyFormat("[foo bar:baz] && [foo bar:baz];");
675   verifyFormat("[foo bar:baz] | [foo bar:baz];");
676   verifyFormat("[foo bar:baz] ^ [foo bar:baz];");
677   verifyFormat("[foo bar:baz] & [foo bar:baz];");
678   verifyFormat("[foo bar:baz] == [foo bar:baz];");
679   verifyFormat("[foo bar:baz] != [foo bar:baz];");
680   verifyFormat("[foo bar:baz] >= [foo bar:baz];");
681   verifyFormat("[foo bar:baz] <= [foo bar:baz];");
682   verifyFormat("[foo bar:baz] > [foo bar:baz];");
683   verifyFormat("[foo bar:baz] < [foo bar:baz];");
684   verifyFormat("[foo bar:baz] >> [foo bar:baz];");
685   verifyFormat("[foo bar:baz] << [foo bar:baz];");
686   verifyFormat("[foo bar:baz] - [foo bar:baz];");
687   verifyFormat("[foo bar:baz] + [foo bar:baz];");
688   verifyFormat("[foo bar:baz] * [foo bar:baz];");
689   verifyFormat("[foo bar:baz] / [foo bar:baz];");
690   verifyFormat("[foo bar:baz] % [foo bar:baz];");
691   // Whew!
692 
693   verifyFormat("return in[42];");
694   verifyFormat("for (auto v : in[1]) {\n}");
695   verifyFormat("for (int i = 0; i < in[a]; ++i) {\n}");
696   verifyFormat("for (int i = 0; in[a] < i; ++i) {\n}");
697   verifyFormat("for (int i = 0; i < n; ++i, ++in[a]) {\n}");
698   verifyFormat("for (int i = 0; i < n; ++i, in[a]++) {\n}");
699   verifyFormat("for (int i = 0; i < f(in[a]); ++i, in[a]++) {\n}");
700   verifyFormat("for (id foo in [self getStuffFor:bla]) {\n"
701                "}");
702   verifyFormat("[self aaaaa:MACRO(a, b:, c:)];");
703   verifyFormat("[self aaaaa:MACRO(a, b:c:, d:e:)];");
704   verifyFormat("[self aaaaa:MACRO(a, b:c:d:, e:f:g:)];");
705   verifyFormat("int XYMyFoo(int a, int b) NS_SWIFT_NAME(foo(self:scale:));");
706   verifyFormat("[self aaaaa:(1 + 2) bbbbb:3];");
707   verifyFormat("[self aaaaa:(Type)a bbbbb:3];");
708 
709   verifyFormat("[self stuffWithInt:(4 + 2) float:4.5];");
710   verifyFormat("[self stuffWithInt:a ? b : c float:4.5];");
711   verifyFormat("[self stuffWithInt:a ? [self foo:bar] : c];");
712   verifyFormat("[self stuffWithInt:a ? (e ? f : g) : c];");
713   verifyFormat("[cond ? obj1 : obj2 methodWithParam:param]");
714   verifyFormat("[button setAction:@selector(zoomOut:)];");
715   verifyFormat("[color getRed:&r green:&g blue:&b alpha:&a];");
716 
717   verifyFormat("arr[[self indexForFoo:a]];");
718   verifyFormat("throw [self errorFor:a];");
719   verifyFormat("@throw [self errorFor:a];");
720 
721   verifyFormat("[(id)foo bar:(id)baz quux:(id)snorf];");
722   verifyFormat("[(id)foo bar:(id) ? baz : quux];");
723   verifyFormat("4 > 4 ? (id)a : (id)baz;");
724 
725   unsigned PreviousColumnLimit = Style.ColumnLimit;
726   Style.ColumnLimit = 50;
727   // Instead of:
728   // bool a =
729   //     ([object a:42] == 0 || [object a:42
730   //                                    b:42] == 0);
731   verifyFormat("bool a = ([object a:42] == 0 ||\n"
732                "          [object a:42 b:42] == 0);");
733   Style.ColumnLimit = PreviousColumnLimit;
734   verifyFormat("bool a = ([aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaa ||\n"
735                "          [aaaaaaaa aaaaa] == aaaaaaaaaaaaaaaaaaaa);");
736 
737   // This tests that the formatter doesn't break after "backing" but before ":",
738   // which would be at 80 columns.
739   verifyFormat(
740       "void f() {\n"
741       "  if ((self = [super initWithContentRect:contentRect\n"
742       "                               styleMask:styleMask ?: otherMask\n"
743       "                                 backing:NSBackingStoreBuffered\n"
744       "                                   defer:YES]))");
745 
746   verifyFormat(
747       "[foo checkThatBreakingAfterColonWorksOk:\n"
748       "         [bar ifItDoes:reduceOverallLineLengthLikeInThisCase]];");
749 
750   verifyFormat("[myObj short:arg1 // Force line break\n"
751                "          longKeyword:arg2 != nil ? arg2 : @\"longKeyword\"\n"
752                "    evenLongerKeyword:arg3 ?: @\"evenLongerKeyword\"\n"
753                "                error:arg4];");
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   verifyFormat("[contentsContainer replaceSubview:[subviews objectAtIndex:0]\n"
764                "                             with:contentsNativeView];");
765 
766   verifyFormat(
767       "[pboard addTypes:[NSArray arrayWithObject:kBookmarkButtonDragType]\n"
768       "           owner:nillllll];");
769 
770   verifyFormat(
771       "[pboard setData:[NSData dataWithBytes:&button length:sizeof(button)]\n"
772       "        forType:kBookmarkButtonDragType];");
773 
774   verifyFormat("[defaultCenter addObserver:self\n"
775                "                  selector:@selector(willEnterFullscreen)\n"
776                "                      name:kWillEnterFullscreenNotification\n"
777                "                    object:nil];");
778   verifyFormat("[image_rep drawInRect:drawRect\n"
779                "             fromRect:NSZeroRect\n"
780                "            operation:NSCompositeCopy\n"
781                "             fraction:1.0\n"
782                "       respectFlipped:NO\n"
783                "                hints:nil];");
784   verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
785                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
786   verifyFormat("[aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
787                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
788   verifyFormat("[aaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaa[aaaaaaaaaaaaaaaaaaaaa]\n"
789                "    aaaaaaaaaaaaaaaaaaaaaa];");
790 
791   verifyFormat(
792       "scoped_nsobject<NSTextField> message(\n"
793       "    // The frame will be fixed up when |-setMessageText:| is called.\n"
794       "    [[NSTextField alloc] initWithFrame:NSMakeRect(0, 0, 0, 0)]);");
795   verifyFormat("[self aaaaaa:bbbbbbbbbbbbb\n"
796                "    aaaaaaaaaa:bbbbbbbbbbbbbbbbb\n"
797                "         aaaaa:bbbbbbbbbbb + bbbbbbbbbbbb\n"
798                "          aaaa:bbb];");
799   verifyFormat("[self param:function( //\n"
800                "                parameter)]");
801   verifyFormat(
802       "[self aaaaaaaaaa:aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
803       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa |\n"
804       "                 aaaaaaaaaaaaaaa | aaaaaaaaaaaaaaa];");
805 
806   // Variadic parameters.
807   verifyFormat(
808       "NSArray *myStrings = [NSArray stringarray:@\"a\", @\"b\", nil];");
809   verifyFormat(
810       "[self aaaaaaaaaaaaa:aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
811       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa,\n"
812       "                    aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaa];");
813 
814   verifyFormat("[self // break\n"
815                "      a:a\n"
816                "    aaa:aaa];");
817 
818   // Formats pair-parameters.
819   verifyFormat("[I drawRectOn:surface ofSize:aa:bbb atOrigin:cc:dd];");
820   verifyFormat("[I drawRectOn:surface //\n"
821                "       ofSize:aa:bbb\n"
822                "     atOrigin:cc:dd];");
823 
824   // Inline block as a first argument.
825   verifyFormat("[object justBlock:^{\n"
826                "  a = 42;\n"
827                "}];");
828   verifyFormat("[object\n"
829                "    justBlock:^{\n"
830                "      a = 42;\n"
831                "    }\n"
832                "     notBlock:42\n"
833                "            a:42];");
834   verifyFormat("[object\n"
835                "    firstBlock:^{\n"
836                "      a = 42;\n"
837                "    }\n"
838                "    blockWithLongerName:^{\n"
839                "      a = 42;\n"
840                "    }];");
841   verifyFormat("[object\n"
842                "    blockWithLongerName:^{\n"
843                "      a = 42;\n"
844                "    }\n"
845                "    secondBlock:^{\n"
846                "      a = 42;\n"
847                "    }];");
848   verifyFormat("[object\n"
849                "    firstBlock:^{\n"
850                "      a = 42;\n"
851                "    }\n"
852                "    notBlock:42\n"
853                "    secondBlock:^{\n"
854                "      a = 42;\n"
855                "    }];");
856 
857   // Space between cast rparen and selector name component.
858   verifyFormat("[((Foo *)foo) bar];");
859   verifyFormat("[((Foo *)foo) bar:1 blech:2];");
860 
861   Style.ColumnLimit = 20;
862   verifyFormat("aaaaa = [a aa:aa\n"
863                "           aa:aa];");
864   verifyFormat("aaaaaa = [aa aa:aa\n"
865                "             aa:aa];");
866 
867   // Message receiver taking multiple lines.
868   // Non-corner case.
869   verifyFormat("[[object block:^{\n"
870                "  return 42;\n"
871                "}] a:42 b:42];");
872   // Arguments just fit into one line.
873   verifyFormat("[[object block:^{\n"
874                "  return 42;\n"
875                "}] aaaaaaa:42 b:42];");
876   // Arguments just over a column limit.
877   verifyFormat("[[object block:^{\n"
878                "  return 42;\n"
879                "}] aaaaaaa:42\n"
880                "        bb:42];");
881   // Arguments just fit into one line.
882   Style.ColumnLimit = 23;
883   verifyFormat("[[obj a:42\n"
884                "      b:42\n"
885                "      c:42\n"
886                "      d:42] e:42 f:42];");
887 
888   // Arguments do not fit into one line with a receiver.
889   Style.ColumnLimit = 20;
890   verifyFormat("[[obj a:42] a:42\n"
891                "            b:42];");
892   verifyFormat("[[obj a:42] a:42\n"
893                "            b:42\n"
894                "            c:42];");
895   verifyFormat("[[obj aaaaaa:42\n"
896                "           b:42]\n"
897                "    cc:42\n"
898                "     d:42];");
899 
900   // Avoid breaking receiver expression.
901   Style.ColumnLimit = 30;
902   verifyFormat("fooooooo =\n"
903                "    [[obj fooo] aaa:42\n"
904                "                aaa:42];");
905   verifyFormat("[[[obj foo] bar] aa:42\n"
906                "                 bb:42\n"
907                "                 cc:42];");
908 
909   // Avoid breaking between unary operators and ObjC method expressions.
910   Style.ColumnLimit = 45;
911   verifyFormat("if (a012345678901234567890123 &&\n"
912                "    ![foo bar]) {\n"
913                "}");
914   verifyFormat("if (a012345678901234567890123 &&\n"
915                "    +[foo bar]) {\n"
916                "}");
917   verifyFormat("if (a012345678901234567890123 &&\n"
918                "    -[foo bar]) {\n"
919                "}");
920 
921   Style.ColumnLimit = 70;
922   verifyFormat(
923       "void f() {\n"
924       "  popup_wdow_.reset([[RenderWidgetPopupWindow alloc]\n"
925       "      iniithContentRect:NSMakRet(origin_global.x, origin_global.y,\n"
926       "                                 pos.width(), pos.height())\n"
927       "                syeMask:NSBorderlessWindowMask\n"
928       "                  bking:NSBackingStoreBuffered\n"
929       "                    der:NO]);\n"
930       "}");
931 
932   Style.ColumnLimit = 60;
933   verifyFormat("[call aaaaaaaa.aaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa.aaaaaaaa\n"
934                "        .aaaaaaaa];"); // FIXME: Indentation seems off.
935   // FIXME: This violates the column limit.
936   verifyFormat(
937       "[aaaaaaaaaaaaaaaaaaaaaaaaa\n"
938       "    aaaaaaaaaaaaaaaaa:aaaaaaaa\n"
939       "                  aaa:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
940 
941   Style = getChromiumStyle(FormatStyle::LK_ObjC);
942   Style.ColumnLimit = 80;
943   verifyFormat(
944       "void f() {\n"
945       "  popup_window_.reset([[RenderWidgetPopupWindow alloc]\n"
946       "      initWithContentRect:NSMakeRect(origin_global.x, origin_global.y,\n"
947       "                                     pos.width(), pos.height())\n"
948       "                styleMask:NSBorderlessWindowMask\n"
949       "                  backing:NSBackingStoreBuffered\n"
950       "                    defer:NO]);\n"
951       "}");
952 
953   // Respect continuation indent and colon alignment (e.g. when object name is
954   // short, and first selector is the longest one)
955   Style = getLLVMStyle();
956   Style.Language = FormatStyle::LK_ObjC;
957   Style.ContinuationIndentWidth = 8;
958   verifyFormat("[self performSelectorOnMainThread:@selector(loadAccessories)\n"
959                "                       withObject:nil\n"
960                "                    waitUntilDone:false];");
961   verifyFormat("[self performSelector:@selector(loadAccessories)\n"
962                "        withObjectOnMainThread:nil\n"
963                "                 waitUntilDone:false];");
964   verifyFormat(
965       "[aaaaaaaaaaaaaaaaaaaaaaaaa\n"
966       "        performSelectorOnMainThread:@selector(loadAccessories)\n"
967       "                         withObject:nil\n"
968       "                      waitUntilDone:false];");
969   verifyFormat(
970       "[self // force wrapping\n"
971       "        performSelectorOnMainThread:@selector(loadAccessories)\n"
972       "                         withObject:nil\n"
973       "                      waitUntilDone:false];");
974 }
975 
976 TEST_F(FormatTestObjC, ObjCAt) {
977   verifyFormat("@autoreleasepool");
978   verifyFormat("@catch");
979   verifyFormat("@class");
980   verifyFormat("@compatibility_alias");
981   verifyFormat("@defs");
982   verifyFormat("@dynamic");
983   verifyFormat("@encode");
984   verifyFormat("@end");
985   verifyFormat("@finally");
986   verifyFormat("@implementation");
987   verifyFormat("@import");
988   verifyFormat("@interface");
989   verifyFormat("@optional");
990   verifyFormat("@package");
991   verifyFormat("@private");
992   verifyFormat("@property");
993   verifyFormat("@protected");
994   verifyFormat("@protocol");
995   verifyFormat("@public");
996   verifyFormat("@required");
997   verifyFormat("@selector");
998   verifyFormat("@synchronized");
999   verifyFormat("@synthesize");
1000   verifyFormat("@throw");
1001   verifyFormat("@try");
1002 
1003   EXPECT_EQ("@interface", format("@ interface"));
1004 
1005   // The precise formatting of this doesn't matter, nobody writes code like
1006   // this.
1007   verifyFormat("@ /*foo*/ interface");
1008 }
1009 
1010 TEST_F(FormatTestObjC, ObjCBlockTypesAndVariables) {
1011   verifyFormat("void DoStuffWithBlockType(int (^)(char));");
1012   verifyFormat("int (^foo)(char, float);");
1013   verifyFormat("int (^foo[10])(char, float);");
1014   verifyFormat("int (^foo[kNumEntries])(char, float);");
1015   verifyFormat("int (^foo[kNumEntries + 10])(char, float);");
1016   verifyFormat("int (^foo[(kNumEntries + 10)])(char, float);");
1017 }
1018 
1019 TEST_F(FormatTestObjC, ObjCSnippets) {
1020   verifyFormat("@autoreleasepool {\n"
1021                "  foo();\n"
1022                "}");
1023   verifyFormat("@class Foo, Bar;");
1024   verifyFormat("@compatibility_alias AliasName ExistingClass;");
1025   verifyFormat("@dynamic textColor;");
1026   verifyFormat("char *buf1 = @encode(int *);");
1027   verifyFormat("char *buf1 = @encode(typeof(4 * 5));");
1028   verifyFormat("char *buf1 = @encode(int **);");
1029   verifyFormat("Protocol *proto = @protocol(p1);");
1030   verifyFormat("SEL s = @selector(foo:);");
1031   verifyFormat("@synchronized(self) {\n"
1032                "  f();\n"
1033                "}");
1034 
1035   verifyFormat("@import foo.bar;\n"
1036                "@import baz;");
1037 
1038   verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
1039 
1040   verifyFormat("@property(assign, nonatomic) CGFloat hoverAlpha;");
1041   verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
1042 
1043   verifyFormat("extern UIWindow *MainWindow(void) "
1044                "NS_SWIFT_NAME(getter:MyHelper.mainWindow());");
1045 
1046   verifyFormat("extern UIWindow *MainWindow(void) "
1047                "CF_SWIFT_NAME(getter:MyHelper.mainWindow());");
1048 
1049   Style.ColumnLimit = 50;
1050   verifyFormat("@interface Foo\n"
1051                "- (void)doStuffWithFoo:(id)name\n"
1052                "                   bar:(id)bar\n"
1053                "                   baz:(id)baz\n"
1054                "    NS_SWIFT_NAME(doStuff(withFoo:bar:baz:));\n"
1055                "@end");
1056 
1057   Style = getMozillaStyle();
1058   verifyFormat("@property (assign, getter=isEditable) BOOL editable;");
1059   verifyFormat("@property BOOL editable;");
1060 
1061   Style = getWebKitStyle();
1062   verifyFormat("@property (assign, getter=isEditable) BOOL editable;");
1063   verifyFormat("@property BOOL editable;");
1064 
1065   Style = getGoogleStyle(FormatStyle::LK_ObjC);
1066   verifyFormat("@synthesize dropArrowPosition = dropArrowPosition_;");
1067   verifyFormat("@property(assign, getter=isEditable) BOOL editable;");
1068 }
1069 
1070 TEST_F(FormatTestObjC, ObjCForIn) {
1071   verifyFormat("- (void)test {\n"
1072                "  for (NSString *n in arrayOfStrings) {\n"
1073                "    foo(n);\n"
1074                "  }\n"
1075                "}");
1076   verifyFormat("- (void)test {\n"
1077                "  for (NSString *n in (__bridge NSArray *)arrayOfStrings) {\n"
1078                "    foo(n);\n"
1079                "  }\n"
1080                "}");
1081   verifyFormat("for (Foo *x in bar) {\n}");
1082   verifyFormat("for (Foo *x in [bar baz]) {\n}");
1083   verifyFormat("for (Foo *x in [bar baz:blech]) {\n}");
1084   verifyFormat("for (Foo *x in [bar baz:blech, 1, 2, 3, 0]) {\n}");
1085   verifyFormat("for (Foo *x in [bar baz:^{\n"
1086                "       [uh oh];\n"
1087                "     }]) {\n}");
1088 }
1089 
1090 TEST_F(FormatTestObjC, ObjCCxxKeywords) {
1091   verifyFormat("+ (instancetype)new {\n"
1092                "  return nil;\n"
1093                "}\n");
1094   verifyFormat("+ (instancetype)myNew {\n"
1095                "  return [self new];\n"
1096                "}\n");
1097   verifyFormat("SEL NewSelector(void) { return @selector(new); }\n");
1098   verifyFormat("SEL MacroSelector(void) { return MACRO(new); }\n");
1099   verifyFormat("+ (instancetype)delete {\n"
1100                "  return nil;\n"
1101                "}\n");
1102   verifyFormat("+ (instancetype)myDelete {\n"
1103                "  return [self delete];\n"
1104                "}\n");
1105   verifyFormat("SEL DeleteSelector(void) { return @selector(delete); }\n");
1106   verifyFormat("SEL MacroSelector(void) { return MACRO(delete); }\n");
1107   verifyFormat("MACRO(new:)\n");
1108   verifyFormat("MACRO(delete:)\n");
1109   verifyFormat("foo = @{MACRO(new:) : MACRO(delete:)}\n");
1110   verifyFormat("@implementation Foo\n"
1111                "// Testing\n"
1112                "- (Class)class {\n"
1113                "}\n"
1114                "- (void)foo {\n"
1115                "}\n"
1116                "@end\n");
1117   verifyFormat("@implementation Foo\n"
1118                "- (Class)class {\n"
1119                "}\n"
1120                "- (void)foo {\n"
1121                "}\n"
1122                "@end");
1123   verifyFormat("@implementation Foo\n"
1124                "+ (Class)class {\n"
1125                "}\n"
1126                "- (void)foo {\n"
1127                "}\n"
1128                "@end");
1129   verifyFormat("@implementation Foo\n"
1130                "- (Class)class:(Class)klass {\n"
1131                "}\n"
1132                "- (void)foo {\n"
1133                "}\n"
1134                "@end");
1135   verifyFormat("@implementation Foo\n"
1136                "+ (Class)class:(Class)klass {\n"
1137                "}\n"
1138                "- (void)foo {\n"
1139                "}\n"
1140                "@end");
1141 
1142   verifyFormat("@interface Foo\n"
1143                "// Testing\n"
1144                "- (Class)class;\n"
1145                "- (void)foo;\n"
1146                "@end\n");
1147   verifyFormat("@interface Foo\n"
1148                "- (Class)class;\n"
1149                "- (void)foo;\n"
1150                "@end");
1151   verifyFormat("@interface Foo\n"
1152                "+ (Class)class;\n"
1153                "- (void)foo;\n"
1154                "@end");
1155   verifyFormat("@interface Foo\n"
1156                "- (Class)class:(Class)klass;\n"
1157                "- (void)foo;\n"
1158                "@end");
1159   verifyFormat("@interface Foo\n"
1160                "+ (Class)class:(Class)klass;\n"
1161                "- (void)foo;\n"
1162                "@end");
1163 }
1164 
1165 TEST_F(FormatTestObjC, ObjCLiterals) {
1166   verifyFormat("@\"String\"");
1167   verifyFormat("@1");
1168   verifyFormat("@+4.8");
1169   verifyFormat("@-4");
1170   verifyFormat("@1LL");
1171   verifyFormat("@.5");
1172   verifyFormat("@'c'");
1173   verifyFormat("@true");
1174 
1175   verifyFormat("NSNumber *smallestInt = @(-INT_MAX - 1);");
1176   verifyFormat("NSNumber *piOverTwo = @(M_PI / 2);");
1177   verifyFormat("NSNumber *favoriteColor = @(Green);");
1178   verifyFormat("NSString *path = @(getenv(\"PATH\"));");
1179 
1180   verifyFormat("[dictionary setObject:@(1) forKey:@\"number\"];");
1181 }
1182 
1183 TEST_F(FormatTestObjC, ObjCDictLiterals) {
1184   verifyFormat("@{");
1185   verifyFormat("@{}");
1186   verifyFormat("@{@\"one\" : @1}");
1187   verifyFormat("return @{@\"one\" : @1;");
1188   verifyFormat("@{@\"one\" : @1}");
1189 
1190   verifyFormat("@{@\"one\" : @{@2 : @1}}");
1191   verifyFormat("@{\n"
1192                "  @\"one\" : @{@2 : @1},\n"
1193                "}");
1194 
1195   verifyFormat("@{1 > 2 ? @\"one\" : @\"two\" : 1 > 2 ? @1 : @2}");
1196   verifyIncompleteFormat("[self setDict:@{}");
1197   verifyIncompleteFormat("[self setDict:@{@1 : @2}");
1198   verifyFormat("NSLog(@\"%@\", @{@1 : @2, @2 : @3}[@1]);");
1199   verifyFormat(
1200       "NSDictionary *masses = @{@\"H\" : @1.0078, @\"He\" : @4.0026};");
1201   verifyFormat(
1202       "NSDictionary *settings = @{AVEncoderKey : @(AVAudioQualityMax)};");
1203 
1204   verifyFormat("NSDictionary *d = @{\n"
1205                "  @\"nam\" : NSUserNam(),\n"
1206                "  @\"dte\" : [NSDate date],\n"
1207                "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
1208                "};");
1209   verifyFormat(
1210       "@{\n"
1211       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
1212       "regularFont,\n"
1213       "};");
1214   verifyFormat(
1215       "@{\n"
1216       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee :\n"
1217       "      reeeeeeeeeeeeeeeeeeeeeeeegularFont,\n"
1218       "};");
1219 
1220   // We should try to be robust in case someone forgets the "@".
1221   verifyFormat("NSDictionary *d = {\n"
1222                "  @\"nam\" : NSUserNam(),\n"
1223                "  @\"dte\" : [NSDate date],\n"
1224                "  @\"processInfo\" : [NSProcessInfo processInfo]\n"
1225                "};");
1226   verifyFormat("NSMutableDictionary *dictionary =\n"
1227                "    [NSMutableDictionary dictionaryWithDictionary:@{\n"
1228                "      aaaaaaaaaaaaaaaaaaaaa : aaaaaaaaaaaaa,\n"
1229                "      bbbbbbbbbbbbbbbbbb : bbbbb,\n"
1230                "      cccccccccccccccc : ccccccccccccccc\n"
1231                "    }];");
1232 
1233   // Ensure that casts before the key are kept on the same line as the key.
1234   verifyFormat(
1235       "NSDictionary *d = @{\n"
1236       "  (aaaaaaaa id)aaaaaaaaa : (aaaaaaaa id)aaaaaaaaaaaaaaaaaaaaaaaa,\n"
1237       "  (aaaaaaaa id)aaaaaaaaaaaaaa : (aaaaaaaa id)aaaaaaaaaaaaaa,\n"
1238       "};");
1239   Style.ColumnLimit = 40;
1240   verifyFormat("int Foo() {\n"
1241                "  a12345 = @{a12345 : a12345};\n"
1242                "}");
1243   verifyFormat("int Foo() {\n"
1244                "  a12345 = @{a12345 : @(a12345)};\n"
1245                "}");
1246   verifyFormat("int Foo() {\n"
1247                "  a12345 = @{(Foo *)a12345 : @(a12345)};\n"
1248                "}");
1249   verifyFormat("int Foo() {\n"
1250                "  a12345 = @{@(a12345) : a12345};\n"
1251                "}");
1252   verifyFormat("int Foo() {\n"
1253                "  a12345 = @{@(a12345) : @YES};\n"
1254                "}");
1255   Style.SpacesInContainerLiterals = false;
1256   verifyFormat("int Foo() {\n"
1257                "  b12345 = @{b12345: b12345};\n"
1258                "}");
1259   verifyFormat("int Foo() {\n"
1260                "  b12345 = @{(Foo *)b12345: @(b12345)};\n"
1261                "}");
1262   Style.SpacesInContainerLiterals = true;
1263 
1264   Style = getGoogleStyle(FormatStyle::LK_ObjC);
1265   verifyFormat(
1266       "@{\n"
1267       "  NSFontAttributeNameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee : "
1268       "regularFont,\n"
1269       "};");
1270 }
1271 
1272 TEST_F(FormatTestObjC, ObjCArrayLiterals) {
1273   verifyIncompleteFormat("@[");
1274   verifyFormat("@[]");
1275   verifyFormat(
1276       "NSArray *array = @[ @\" Hey \", NSApp, [NSNumber numberWithInt:42] ];");
1277   verifyFormat("return @[ @3, @[], @[ @4, @5 ] ];");
1278   verifyFormat("NSArray *array = @[ [foo description] ];");
1279 
1280   verifyFormat(
1281       "NSArray *some_variable = @[\n"
1282       "  aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
1283       "  @\"aaaaaaaaaaaaaaaaa\",\n"
1284       "  @\"aaaaaaaaaaaaaaaaa\",\n"
1285       "  @\"aaaaaaaaaaaaaaaaa\",\n"
1286       "];");
1287   verifyFormat(
1288       "NSArray *some_variable = @[\n"
1289       "  aaaa == bbbbbbbbbbb ? @\"aaaaaaaaaaaa\" : @\"aaaaaaaaaaaaaa\",\n"
1290       "  @\"aaaaaaaaaaaaaaaa\", @\"aaaaaaaaaaaaaaaa\", @\"aaaaaaaaaaaaaaaa\"\n"
1291       "];");
1292   verifyFormat("NSArray *some_variable = @[\n"
1293                "  @\"aaaaaaaaaaaaaaaaa\",\n"
1294                "  @\"aaaaaaaaaaaaaaaaa\",\n"
1295                "  @\"aaaaaaaaaaaaaaaaa\",\n"
1296                "  @\"aaaaaaaaaaaaaaaaa\",\n"
1297                "];");
1298   verifyFormat("NSArray *array = @[\n"
1299                "  @\"a\",\n"
1300                "  @\"a\",\n" // Trailing comma -> one per line.
1301                "];");
1302 
1303   // We should try to be robust in case someone forgets the "@".
1304   verifyFormat("NSArray *some_variable = [\n"
1305                "  @\"aaaaaaaaaaaaaaaaa\",\n"
1306                "  @\"aaaaaaaaaaaaaaaaa\",\n"
1307                "  @\"aaaaaaaaaaaaaaaaa\",\n"
1308                "  @\"aaaaaaaaaaaaaaaaa\",\n"
1309                "];");
1310   verifyFormat(
1311       "- (NSAttributedString *)attributedStringForSegment:(NSUInteger)segment\n"
1312       "                                             index:(NSUInteger)index\n"
1313       "                                nonDigitAttributes:\n"
1314       "                                    (NSDictionary *)noDigitAttributes;");
1315   verifyFormat("[someFunction someLooooooooooooongParameter:@[\n"
1316                "  NSBundle.mainBundle.infoDictionary[@\"a\"]\n"
1317                "]];");
1318   Style.ColumnLimit = 40;
1319   verifyFormat("int Foo() {\n"
1320                "  a12345 = @[ a12345, a12345 ];\n"
1321                "}");
1322   verifyFormat("int Foo() {\n"
1323                "  a123 = @[ (Foo *)a12345, @(a12345) ];\n"
1324                "}");
1325   Style.SpacesInContainerLiterals = false;
1326   verifyFormat("int Foo() {\n"
1327                "  b12345 = @[b12345, b12345];\n"
1328                "}");
1329   verifyFormat("int Foo() {\n"
1330                "  b12345 = @[(Foo *)b12345, @(b12345)];\n"
1331                "}");
1332   Style.SpacesInContainerLiterals = true;
1333   Style.ColumnLimit = 20;
1334   // We can't break string literals inside NSArray literals
1335   // (that raises -Wobjc-string-concatenation).
1336   verifyFormat("NSArray *foo = @[\n"
1337                "  @\"aaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
1338                "];\n");
1339 }
1340 
1341 TEST_F(FormatTestObjC, BreaksCallStatementWhereSemiJustOverTheLimit) {
1342   Style.ColumnLimit = 60;
1343   // If the statement starting with 'a = ...' is put on a single line, the ';'
1344   // is at line 61.
1345   verifyFormat("int f(int a) {\n"
1346                "  a = [self aaaaaaaaaa:bbbbbbbbb\n"
1347                "             ccccccccc:dddddddd\n"
1348                "                    ee:fddd];\n"
1349                "}");
1350 }
1351 
1352 TEST_F(FormatTestObjC, AlwaysBreakBeforeMultilineStrings) {
1353   Style = getGoogleStyle(FormatStyle::LK_ObjC);
1354   Style.ColumnLimit = 40;
1355   verifyFormat("aaaa = @\"bbbb\"\n"
1356                "       @\"cccc\";");
1357   verifyFormat("aaaa(@\"bbbb\"\n"
1358                "     @\"cccc\");");
1359   verifyFormat("aaaa(qqq, @\"bbbb\"\n"
1360                "          @\"cccc\");");
1361   verifyFormat("[aaaa qqqq:@\"bbbb\"\n"
1362                "           @\"cccc\"];");
1363   verifyFormat("aaaa = [aaaa qqqq:@\"bbbb\"\n"
1364                "                  @\"cccc\"];");
1365   verifyFormat("[aaaa qqqq:@\"bbbb\"\n"
1366                "           @\"cccc\"\n"
1367                "        rr:42\n"
1368                "    ssssss:@\"ee\"\n"
1369                "           @\"fffff\"];");
1370 }
1371 
1372 TEST_F(FormatTestObjC, DisambiguatesCallsFromCppLambdas) {
1373   verifyFormat("x = ([a foo:bar] && b->c == 'd');");
1374   verifyFormat("x = ([a foo:bar] + b->c == 'd');");
1375   verifyFormat("x = ([a foo:bar] + !b->c == 'd');");
1376   verifyFormat("x = ([a foo:bar] + ~b->c == 'd');");
1377   verifyFormat("x = ([a foo:bar] - b->c == 'd');");
1378   verifyFormat("x = ([a foo:bar] / b->c == 'd');");
1379   verifyFormat("x = ([a foo:bar] % b->c == 'd');");
1380   verifyFormat("x = ([a foo:bar] | b->c == 'd');");
1381   verifyFormat("x = ([a foo:bar] || b->c == 'd');");
1382   verifyFormat("x = ([a foo:bar] && b->c == 'd');");
1383   verifyFormat("x = ([a foo:bar] == b->c == 'd');");
1384   verifyFormat("x = ([a foo:bar] != b->c == 'd');");
1385   verifyFormat("x = ([a foo:bar] <= b->c == 'd');");
1386   verifyFormat("x = ([a foo:bar] >= b->c == 'd');");
1387   verifyFormat("x = ([a foo:bar] << b->c == 'd');");
1388   verifyFormat("x = ([a foo:bar] ? b->c == 'd' : 'e');");
1389   // FIXME: The following are wrongly classified as C++ lambda expressions.
1390   // For example this code:
1391   //   x = ([a foo:bar] & b->c == 'd');
1392   // is formatted as:
1393   //   x = ([a foo:bar] & b -> c == 'd');
1394   // verifyFormat("x = ([a foo:bar] & b->c == 'd');");
1395   // verifyFormat("x = ([a foo:bar] > b->c == 'd');");
1396   // verifyFormat("x = ([a foo:bar] < b->c == 'd');");
1397   // verifyFormat("x = ([a foo:bar] >> b->c == 'd');");
1398 }
1399 
1400 TEST_F(FormatTestObjC, DisambiguatesCallsFromStructuredBindings) {
1401   verifyFormat("int f() {\n"
1402                "  if (a && [f arg])\n"
1403                "    return 0;\n"
1404                "}");
1405   verifyFormat("int f() {\n"
1406                "  if (a & [f arg])\n"
1407                "    return 0;\n"
1408                "}");
1409   verifyFormat("int f() {\n"
1410                "  for (auto &[elem] : list)\n"
1411                "    return 0;\n"
1412                "}");
1413   verifyFormat("int f() {\n"
1414                "  for (auto &&[elem] : list)\n"
1415                "    return 0;\n"
1416                "}");
1417   verifyFormat(
1418       "int f() {\n"
1419       "  for (auto /**/ const /**/ volatile /**/ && /**/ [elem] : list)\n"
1420       "    return 0;\n"
1421       "}");
1422 }
1423 
1424 TEST_F(FormatTestObjC, BreakLineBeforeNestedBlockParam) {
1425   Style = getGoogleStyle(FormatStyle::LK_ObjC);
1426   Style.ObjCBreakBeforeNestedBlockParam = false;
1427   Style.ColumnLimit = 0;
1428 
1429   verifyFormat("[self.test1 t:self callback:^(typeof(self) self, NSNumber *u, "
1430                "NSNumber *v) {\n"
1431                "  u = v;\n"
1432                "}]");
1433 
1434   verifyFormat("[self.test1 t:self w:self callback:^(typeof(self) self, "
1435                "NSNumber *u, NSNumber *v) {\n"
1436                "  u = v;\n"
1437                "}]");
1438 
1439   verifyFormat("[self.test1 t:self w:self callback:^(typeof(self) self, "
1440                "NSNumber *u, NSNumber *v) {\n"
1441                "  u = c;\n"
1442                "} w:self callback2:^(typeof(self) self, NSNumber *a, NSNumber "
1443                "*b, NSNumber *c) {\n"
1444                "  b = c;\n"
1445                "}]");
1446   verifyFormat("[self.test1 t:self w:self callback:^(typeof(self) self, "
1447                "NSNumber *u, NSNumber *v) {\n"
1448                "  u = v;\n"
1449                "} z:self]");
1450 
1451   Style.ColumnLimit = 80;
1452   verifyFormat(
1453       "[self.test_method a:self b:self\n"
1454       "           callback:^(typeof(self) self, NSNumber *u, NSNumber *v) {\n"
1455       "             u = v;\n"
1456       "           }]");
1457 }
1458 
1459 TEST_F(FormatTestObjC, IfNotUnlikely) {
1460   Style = getGoogleStyle(FormatStyle::LK_ObjC);
1461 
1462   verifyFormat("if (argc < 5) [obj func:arg];");
1463   verifyFormat("if (argc < 5) [[obj1 method1:arg1] method2:arg2];");
1464   verifyFormat("if (argc < 5) [[foo bar] baz:i[0]];");
1465   verifyFormat("if (argc < 5) [[foo bar] baz:i[0]][1];");
1466 
1467   verifyFormat("if (argc < 5)\n"
1468                "  [obj func:arg];\n"
1469                "else\n"
1470                "  [obj func:arg2];");
1471 
1472   verifyFormat("if (argc < 5) [[unlikely]]\n"
1473                "  [obj func:arg];\n"
1474                "else [[likely]]\n"
1475                "  [obj func:arg2];");
1476 }
1477 
1478 } // end namespace
1479 } // end namespace format
1480 } // end namespace clang
1481