This repository was archived by the owner on Nov 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathObjCMT.cpp
2269 lines (2050 loc) · 81.7 KB
/
ObjCMT.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Transforms.h"
#include "clang/ARCMigrate/ARCMT.h"
#include "clang/ARCMigrate/ARCMTActions.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/NSAPI.h"
#include "clang/AST/ParentMap.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
#include "clang/Basic/FileManager.h"
#include "clang/Edit/Commit.h"
#include "clang/Edit/EditedSource.h"
#include "clang/Edit/EditsReceiver.h"
#include "clang/Edit/Rewriters.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/MultiplexConsumer.h"
#include "clang/Lex/PPConditionalDirectiveRecord.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Rewrite/Core/Rewriter.h"
#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/YAMLParser.h"
using namespace clang;
using namespace arcmt;
using namespace ento::objc_retain;
namespace {
class ObjCMigrateASTConsumer : public ASTConsumer {
enum CF_BRIDGING_KIND {
CF_BRIDGING_NONE,
CF_BRIDGING_ENABLE,
CF_BRIDGING_MAY_INCLUDE
};
void migrateDecl(Decl *D);
void migrateObjCContainerDecl(ASTContext &Ctx, ObjCContainerDecl *D);
void migrateProtocolConformance(ASTContext &Ctx,
const ObjCImplementationDecl *ImpDecl);
void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
const TypedefDecl *TypedefDcl);
void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
ObjCMethodDecl *OM);
bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
ObjCMethodDecl *OM,
ObjCInstanceTypeFamily OIT_Family = OIT_None);
void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
const FunctionDecl *FuncDecl, bool ResultAnnotated);
void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
void AnnotateImplicitBridging(ASTContext &Ctx);
CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
const FunctionDecl *FuncDecl);
void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
void migrateAddMethodAnnotation(ASTContext &Ctx,
const ObjCMethodDecl *MethodDecl);
void inferDesignatedInitializers(ASTContext &Ctx,
const ObjCImplementationDecl *ImplD);
bool InsertFoundation(ASTContext &Ctx, SourceLocation Loc);
public:
std::string MigrateDir;
unsigned ASTMigrateActions;
FileID FileId;
const TypedefDecl *NSIntegerTypedefed;
const TypedefDecl *NSUIntegerTypedefed;
std::unique_ptr<NSAPI> NSAPIObj;
std::unique_ptr<edit::EditedSource> Editor;
FileRemapper &Remapper;
FileManager &FileMgr;
const PPConditionalDirectiveRecord *PPRec;
Preprocessor &PP;
bool IsOutputFile;
bool FoundationIncluded;
llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
llvm::StringSet<> WhiteListFilenames;
ObjCMigrateASTConsumer(StringRef migrateDir,
unsigned astMigrateActions,
FileRemapper &remapper,
FileManager &fileMgr,
const PPConditionalDirectiveRecord *PPRec,
Preprocessor &PP,
bool isOutputFile,
ArrayRef<std::string> WhiteList)
: MigrateDir(migrateDir),
ASTMigrateActions(astMigrateActions),
NSIntegerTypedefed(nullptr), NSUIntegerTypedefed(nullptr),
Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
IsOutputFile(isOutputFile),
FoundationIncluded(false){
// FIXME: StringSet should have insert(iter, iter) to use here.
for (const std::string &Val : WhiteList)
WhiteListFilenames.insert(Val);
}
protected:
void Initialize(ASTContext &Context) override {
NSAPIObj.reset(new NSAPI(Context));
Editor.reset(new edit::EditedSource(Context.getSourceManager(),
Context.getLangOpts(),
PPRec));
}
bool HandleTopLevelDecl(DeclGroupRef DG) override {
for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
migrateDecl(*I);
return true;
}
void HandleInterestingDecl(DeclGroupRef DG) override {
// Ignore decls from the PCH.
}
void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) override {
ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
}
void HandleTranslationUnit(ASTContext &Ctx) override;
bool canModifyFile(StringRef Path) {
if (WhiteListFilenames.empty())
return true;
return WhiteListFilenames.find(llvm::sys::path::filename(Path))
!= WhiteListFilenames.end();
}
bool canModifyFile(const FileEntry *FE) {
if (!FE)
return false;
return canModifyFile(FE->getName());
}
bool canModifyFile(FileID FID) {
if (FID.isInvalid())
return false;
return canModifyFile(PP.getSourceManager().getFileEntryForID(FID));
}
bool canModify(const Decl *D) {
if (!D)
return false;
if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(D))
return canModify(CatImpl->getCategoryDecl());
if (const ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D))
return canModify(Impl->getClassInterface());
if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
return canModify(cast<Decl>(MD->getDeclContext()));
FileID FID = PP.getSourceManager().getFileID(D->getLocation());
return canModifyFile(FID);
}
};
} // end anonymous namespace
ObjCMigrateAction::ObjCMigrateAction(
std::unique_ptr<FrontendAction> WrappedAction,
StringRef migrateDir,
unsigned migrateAction)
: WrapperFrontendAction(std::move(WrappedAction)), MigrateDir(migrateDir),
ObjCMigAction(migrateAction),
CompInst(nullptr) {
if (MigrateDir.empty())
MigrateDir = "."; // user current directory if none is given.
}
std::unique_ptr<ASTConsumer>
ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
PPConditionalDirectiveRecord *
PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Consumers.push_back(WrapperFrontendAction::CreateASTConsumer(CI, InFile));
Consumers.push_back(llvm::make_unique<ObjCMigrateASTConsumer>(
MigrateDir, ObjCMigAction, Remapper, CompInst->getFileManager(), PPRec,
CompInst->getPreprocessor(), false, None));
return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
}
bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
/*ignoreIfFilesChanges=*/true);
CompInst = &CI;
CI.getDiagnostics().setIgnoreAllWarnings(true);
return true;
}
namespace {
// FIXME. This duplicates one in RewriteObjCFoundationAPI.cpp
bool subscriptOperatorNeedsParens(const Expr *FullExpr) {
const Expr* Expr = FullExpr->IgnoreImpCasts();
return !(isa<ArraySubscriptExpr>(Expr) || isa<CallExpr>(Expr) ||
isa<DeclRefExpr>(Expr) || isa<CXXNamedCastExpr>(Expr) ||
isa<CXXConstructExpr>(Expr) || isa<CXXThisExpr>(Expr) ||
isa<CXXTypeidExpr>(Expr) ||
isa<CXXUnresolvedConstructExpr>(Expr) ||
isa<ObjCMessageExpr>(Expr) || isa<ObjCPropertyRefExpr>(Expr) ||
isa<ObjCProtocolExpr>(Expr) || isa<MemberExpr>(Expr) ||
isa<ObjCIvarRefExpr>(Expr) || isa<ParenExpr>(FullExpr) ||
isa<ParenListExpr>(Expr) || isa<SizeOfPackExpr>(Expr));
}
/// \brief - Rewrite message expression for Objective-C setter and getters into
/// property-dot syntax.
bool rewriteToPropertyDotSyntax(const ObjCMessageExpr *Msg,
Preprocessor &PP,
const NSAPI &NS, edit::Commit &commit,
const ParentMap *PMap) {
if (!Msg || Msg->isImplicit() ||
(Msg->getReceiverKind() != ObjCMessageExpr::Instance &&
Msg->getReceiverKind() != ObjCMessageExpr::SuperInstance))
return false;
if (const Expr *Receiver = Msg->getInstanceReceiver())
if (Receiver->getType()->isObjCBuiltinType())
return false;
const ObjCMethodDecl *Method = Msg->getMethodDecl();
if (!Method)
return false;
if (!Method->isPropertyAccessor())
return false;
const ObjCPropertyDecl *Prop = Method->findPropertyDecl();
if (!Prop)
return false;
SourceRange MsgRange = Msg->getSourceRange();
bool ReceiverIsSuper =
(Msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
// for 'super' receiver is nullptr.
const Expr *receiver = Msg->getInstanceReceiver();
bool NeedsParen =
ReceiverIsSuper ? false : subscriptOperatorNeedsParens(receiver);
bool IsGetter = (Msg->getNumArgs() == 0);
if (IsGetter) {
// Find space location range between receiver expression and getter method.
SourceLocation BegLoc =
ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
BegLoc = PP.getLocForEndOfToken(BegLoc);
SourceLocation EndLoc = Msg->getSelectorLoc(0);
SourceRange SpaceRange(BegLoc, EndLoc);
std::string PropertyDotString;
// rewrite getter method expression into: receiver.property or
// (receiver).property
if (NeedsParen) {
commit.insertBefore(receiver->getLocStart(), "(");
PropertyDotString = ").";
}
else
PropertyDotString = ".";
PropertyDotString += Prop->getName();
commit.replace(SpaceRange, PropertyDotString);
// remove '[' ']'
commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
} else {
if (NeedsParen)
commit.insertWrap("(", receiver->getSourceRange(), ")");
std::string PropertyDotString = ".";
PropertyDotString += Prop->getName();
PropertyDotString += " =";
const Expr*const* Args = Msg->getArgs();
const Expr *RHS = Args[0];
if (!RHS)
return false;
SourceLocation BegLoc =
ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
BegLoc = PP.getLocForEndOfToken(BegLoc);
SourceLocation EndLoc = RHS->getLocStart();
EndLoc = EndLoc.getLocWithOffset(-1);
const char *colon = PP.getSourceManager().getCharacterData(EndLoc);
// Add a space after '=' if there is no space between RHS and '='
if (colon && colon[0] == ':')
PropertyDotString += " ";
SourceRange Range(BegLoc, EndLoc);
commit.replace(Range, PropertyDotString);
// remove '[' ']'
commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
}
return true;
}
class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
ObjCMigrateASTConsumer &Consumer;
ParentMap &PMap;
public:
ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
: Consumer(consumer), PMap(PMap) { }
bool shouldVisitTemplateInstantiations() const { return false; }
bool shouldWalkTypesOfTypeLocs() const { return false; }
bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
edit::Commit commit(*Consumer.Editor);
edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Consumer.Editor->commit(commit);
}
if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
edit::Commit commit(*Consumer.Editor);
edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
Consumer.Editor->commit(commit);
}
if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_PropertyDotSyntax) {
edit::Commit commit(*Consumer.Editor);
rewriteToPropertyDotSyntax(E, Consumer.PP, *Consumer.NSAPIObj,
commit, &PMap);
Consumer.Editor->commit(commit);
}
return true;
}
bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
// Do depth first; we want to rewrite the subexpressions first so that if
// we have to move expressions we will move them already rewritten.
for (Stmt *SubStmt : E->children())
if (!TraverseStmt(SubStmt))
return false;
return WalkUpFromObjCMessageExpr(E);
}
};
class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
ObjCMigrateASTConsumer &Consumer;
std::unique_ptr<ParentMap> PMap;
public:
BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
bool shouldVisitTemplateInstantiations() const { return false; }
bool shouldWalkTypesOfTypeLocs() const { return false; }
bool TraverseStmt(Stmt *S) {
PMap.reset(new ParentMap(S));
ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
return true;
}
};
} // end anonymous namespace
void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
if (!D)
return;
if (isa<ObjCMethodDecl>(D))
return; // Wait for the ObjC container declaration.
BodyMigrator(*this).TraverseDecl(D);
}
static void append_attr(std::string &PropertyString, const char *attr,
bool &LParenAdded) {
if (!LParenAdded) {
PropertyString += "(";
LParenAdded = true;
}
else
PropertyString += ", ";
PropertyString += attr;
}
static
void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
const std::string& TypeString,
const char *name) {
const char *argPtr = TypeString.c_str();
int paren = 0;
while (*argPtr) {
switch (*argPtr) {
case '(':
PropertyString += *argPtr;
paren++;
break;
case ')':
PropertyString += *argPtr;
paren--;
break;
case '^':
case '*':
PropertyString += (*argPtr);
if (paren == 1) {
PropertyString += name;
name = "";
}
break;
default:
PropertyString += *argPtr;
break;
}
argPtr++;
}
}
static const char *PropertyMemoryAttribute(ASTContext &Context, QualType ArgType) {
Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
bool RetainableObject = ArgType->isObjCRetainableType();
if (RetainableObject &&
(propertyLifetime == Qualifiers::OCL_Strong
|| propertyLifetime == Qualifiers::OCL_None)) {
if (const ObjCObjectPointerType *ObjPtrTy =
ArgType->getAs<ObjCObjectPointerType>()) {
ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
if (IDecl &&
IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
return "copy";
else
return "strong";
}
else if (ArgType->isBlockPointerType())
return "copy";
} else if (propertyLifetime == Qualifiers::OCL_Weak)
// TODO. More precise determination of 'weak' attribute requires
// looking into setter's implementation for backing weak ivar.
return "weak";
else if (RetainableObject)
return ArgType->isBlockPointerType() ? "copy" : "strong";
return nullptr;
}
static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
const ObjCMethodDecl *Setter,
const NSAPI &NS, edit::Commit &commit,
unsigned LengthOfPrefix,
bool Atomic, bool UseNsIosOnlyMacro,
bool AvailabilityArgsMatch) {
ASTContext &Context = NS.getASTContext();
bool LParenAdded = false;
std::string PropertyString = "@property ";
if (UseNsIosOnlyMacro && NS.isMacroDefined("NS_NONATOMIC_IOSONLY")) {
PropertyString += "(NS_NONATOMIC_IOSONLY";
LParenAdded = true;
} else if (!Atomic) {
PropertyString += "(nonatomic";
LParenAdded = true;
}
std::string PropertyNameString = Getter->getNameAsString();
StringRef PropertyName(PropertyNameString);
if (LengthOfPrefix > 0) {
if (!LParenAdded) {
PropertyString += "(getter=";
LParenAdded = true;
}
else
PropertyString += ", getter=";
PropertyString += PropertyNameString;
}
// Property with no setter may be suggested as a 'readonly' property.
if (!Setter)
append_attr(PropertyString, "readonly", LParenAdded);
// Short circuit 'delegate' properties that contain the name "delegate" or
// "dataSource", or have exact name "target" to have 'assign' attribute.
if (PropertyName.equals("target") ||
(PropertyName.find("delegate") != StringRef::npos) ||
(PropertyName.find("dataSource") != StringRef::npos)) {
QualType QT = Getter->getReturnType();
if (!QT->isRealType())
append_attr(PropertyString, "assign", LParenAdded);
} else if (!Setter) {
QualType ResType = Context.getCanonicalType(Getter->getReturnType());
if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ResType))
append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
} else {
const ParmVarDecl *argDecl = *Setter->param_begin();
QualType ArgType = Context.getCanonicalType(argDecl->getType());
if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ArgType))
append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
}
if (LParenAdded)
PropertyString += ')';
QualType RT = Getter->getReturnType();
if (!isa<TypedefType>(RT)) {
// strip off any ARC lifetime qualifier.
QualType CanResultTy = Context.getCanonicalType(RT);
if (CanResultTy.getQualifiers().hasObjCLifetime()) {
Qualifiers Qs = CanResultTy.getQualifiers();
Qs.removeObjCLifetime();
RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
}
}
PropertyString += " ";
PrintingPolicy SubPolicy(Context.getPrintingPolicy());
SubPolicy.SuppressStrongLifetime = true;
SubPolicy.SuppressLifetimeQualifiers = true;
std::string TypeString = RT.getAsString(SubPolicy);
if (LengthOfPrefix > 0) {
// property name must strip off "is" and lower case the first character
// after that; e.g. isContinuous will become continuous.
StringRef PropertyNameStringRef(PropertyNameString);
PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
PropertyNameString = PropertyNameStringRef;
bool NoLowering = (isUppercase(PropertyNameString[0]) &&
PropertyNameString.size() > 1 &&
isUppercase(PropertyNameString[1]));
if (!NoLowering)
PropertyNameString[0] = toLowercase(PropertyNameString[0]);
}
if (RT->isBlockPointerType() || RT->isFunctionPointerType())
MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
TypeString,
PropertyNameString.c_str());
else {
char LastChar = TypeString[TypeString.size()-1];
PropertyString += TypeString;
if (LastChar != '*')
PropertyString += ' ';
PropertyString += PropertyNameString;
}
SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
Selector GetterSelector = Getter->getSelector();
SourceLocation EndGetterSelectorLoc =
StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
EndGetterSelectorLoc),
PropertyString);
if (Setter && AvailabilityArgsMatch) {
SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
// Get location past ';'
EndLoc = EndLoc.getLocWithOffset(1);
SourceLocation BeginOfSetterDclLoc = Setter->getLocStart();
// FIXME. This assumes that setter decl; is immediately preceded by eoln.
// It is trying to remove the setter method decl. line entirely.
BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
}
}
static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) {
if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) {
StringRef Name = CatDecl->getName();
return Name.endswith("Deprecated");
}
return false;
}
void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx,
ObjCContainerDecl *D) {
if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D))
return;
for (auto *Method : D->methods()) {
if (Method->isDeprecated())
continue;
bool PropertyInferred = migrateProperty(Ctx, D, Method);
// If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to
// the getter method as it ends up on the property itself which we don't want
// to do unless -objcmt-returns-innerpointer-property option is on.
if (!PropertyInferred ||
(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
migrateNsReturnsInnerPointer(Ctx, Method);
}
if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
return;
for (auto *Prop : D->instance_properties()) {
if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
!Prop->isDeprecated())
migratePropertyNsReturnsInnerPointer(Ctx, Prop);
}
}
static bool
ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
const ObjCImplementationDecl *ImpDecl,
const ObjCInterfaceDecl *IDecl,
ObjCProtocolDecl *Protocol) {
// In auto-synthesis, protocol properties are not synthesized. So,
// a conforming protocol must have its required properties declared
// in class interface.
bool HasAtleastOneRequiredProperty = false;
if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
for (const auto *Property : PDecl->instance_properties()) {
if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
continue;
HasAtleastOneRequiredProperty = true;
DeclContext::lookup_result R = IDecl->lookup(Property->getDeclName());
if (R.size() == 0) {
// Relax the rule and look into class's implementation for a synthesize
// or dynamic declaration. Class is implementing a property coming from
// another protocol. This still makes the target protocol as conforming.
if (!ImpDecl->FindPropertyImplDecl(
Property->getDeclName().getAsIdentifierInfo(),
Property->getQueryKind()))
return false;
}
else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
if ((ClassProperty->getPropertyAttributes()
!= Property->getPropertyAttributes()) ||
!Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
return false;
}
else
return false;
}
// At this point, all required properties in this protocol conform to those
// declared in the class.
// Check that class implements the required methods of the protocol too.
bool HasAtleastOneRequiredMethod = false;
if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
if (PDecl->meth_begin() == PDecl->meth_end())
return HasAtleastOneRequiredProperty;
for (const auto *MD : PDecl->methods()) {
if (MD->isImplicit())
continue;
if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
continue;
DeclContext::lookup_result R = ImpDecl->lookup(MD->getDeclName());
if (R.size() == 0)
return false;
bool match = false;
HasAtleastOneRequiredMethod = true;
for (unsigned I = 0, N = R.size(); I != N; ++I)
if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
match = true;
break;
}
if (!match)
return false;
}
}
return HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod;
}
static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
const NSAPI &NS, edit::Commit &commit) {
const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
std::string ClassString;
SourceLocation EndLoc =
IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
if (Protocols.empty()) {
ClassString = '<';
for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
ClassString += ConformingProtocols[i]->getNameAsString();
if (i != (e-1))
ClassString += ", ";
}
ClassString += "> ";
}
else {
ClassString = ", ";
for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
ClassString += ConformingProtocols[i]->getNameAsString();
if (i != (e-1))
ClassString += ", ";
}
ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
EndLoc = *PL;
}
commit.insertAfterToken(EndLoc, ClassString);
return true;
}
static StringRef GetUnsignedName(StringRef NSIntegerName) {
StringRef UnsignedName = llvm::StringSwitch<StringRef>(NSIntegerName)
.Case("int8_t", "uint8_t")
.Case("int16_t", "uint16_t")
.Case("int32_t", "uint32_t")
.Case("NSInteger", "NSUInteger")
.Case("int64_t", "uint64_t")
.Default(NSIntegerName);
return UnsignedName;
}
static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
const TypedefDecl *TypedefDcl,
const NSAPI &NS, edit::Commit &commit,
StringRef NSIntegerName,
bool NSOptions) {
std::string ClassString;
if (NSOptions) {
ClassString = "typedef NS_OPTIONS(";
ClassString += GetUnsignedName(NSIntegerName);
}
else {
ClassString = "typedef NS_ENUM(";
ClassString += NSIntegerName;
}
ClassString += ", ";
ClassString += TypedefDcl->getIdentifier()->getName();
ClassString += ')';
SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
commit.replace(R, ClassString);
SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
NS.getASTContext(), /*IsDecl*/true);
if (EndOfEnumDclLoc.isValid()) {
SourceRange EnumDclRange(EnumDcl->getLocStart(), EndOfEnumDclLoc);
commit.insertFromRange(TypedefDcl->getLocStart(), EnumDclRange);
}
else
return false;
SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
NS.getASTContext(), /*IsDecl*/true);
if (EndTypedefDclLoc.isValid()) {
SourceRange TDRange(TypedefDcl->getLocStart(), EndTypedefDclLoc);
commit.remove(TDRange);
}
else
return false;
EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
/*IsDecl*/true);
if (EndOfEnumDclLoc.isValid()) {
SourceLocation BeginOfEnumDclLoc = EnumDcl->getLocStart();
// FIXME. This assumes that enum decl; is immediately preceded by eoln.
// It is trying to remove the enum decl. lines entirely.
BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
return true;
}
return false;
}
static void rewriteToNSMacroDecl(ASTContext &Ctx,
const EnumDecl *EnumDcl,
const TypedefDecl *TypedefDcl,
const NSAPI &NS, edit::Commit &commit,
bool IsNSIntegerType) {
QualType DesignatedEnumType = EnumDcl->getIntegerType();
assert(!DesignatedEnumType.isNull()
&& "rewriteToNSMacroDecl - underlying enum type is null");
PrintingPolicy Policy(Ctx.getPrintingPolicy());
std::string TypeString = DesignatedEnumType.getAsString(Policy);
std::string ClassString = IsNSIntegerType ? "NS_ENUM(" : "NS_OPTIONS(";
ClassString += TypeString;
ClassString += ", ";
ClassString += TypedefDcl->getIdentifier()->getName();
ClassString += ") ";
SourceLocation EndLoc = EnumDcl->getBraceRange().getBegin();
if (EndLoc.isInvalid())
return;
CharSourceRange R = CharSourceRange::getCharRange(EnumDcl->getLocStart(), EndLoc);
commit.replace(R, ClassString);
// This is to remove spaces between '}' and typedef name.
SourceLocation StartTypedefLoc = EnumDcl->getLocEnd();
StartTypedefLoc = StartTypedefLoc.getLocWithOffset(+1);
SourceLocation EndTypedefLoc = TypedefDcl->getLocEnd();
commit.remove(SourceRange(StartTypedefLoc, EndTypedefLoc));
}
static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
const EnumDecl *EnumDcl) {
bool PowerOfTwo = true;
bool AllHexdecimalEnumerator = true;
uint64_t MaxPowerOfTwoVal = 0;
for (auto Enumerator : EnumDcl->enumerators()) {
const Expr *InitExpr = Enumerator->getInitExpr();
if (!InitExpr) {
PowerOfTwo = false;
AllHexdecimalEnumerator = false;
continue;
}
InitExpr = InitExpr->IgnoreParenCasts();
if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
if (BO->isShiftOp() || BO->isBitwiseOp())
return true;
uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
if (PowerOfTwo && EnumVal) {
if (!llvm::isPowerOf2_64(EnumVal))
PowerOfTwo = false;
else if (EnumVal > MaxPowerOfTwoVal)
MaxPowerOfTwoVal = EnumVal;
}
if (AllHexdecimalEnumerator && EnumVal) {
bool FoundHexdecimalEnumerator = false;
SourceLocation EndLoc = Enumerator->getLocEnd();
Token Tok;
if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
if (Tok.isLiteral() && Tok.getLength() > 2) {
if (const char *StringLit = Tok.getLiteralData())
FoundHexdecimalEnumerator =
(StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
}
if (!FoundHexdecimalEnumerator)
AllHexdecimalEnumerator = false;
}
}
return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
}
void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
const ObjCImplementationDecl *ImpDecl) {
const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
return;
// Find all implicit conforming protocols for this class
// and make them explicit.
llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls)
if (!ExplicitProtocols.count(ProtDecl))
PotentialImplicitProtocols.push_back(ProtDecl);
if (PotentialImplicitProtocols.empty())
return;
// go through list of non-optional methods and properties in each protocol
// in the PotentialImplicitProtocols list. If class implements every one of the
// methods and properties, then this class conforms to this protocol.
llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
PotentialImplicitProtocols[i]))
ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
if (ConformingProtocols.empty())
return;
// Further reduce number of conforming protocols. If protocol P1 is in the list
// protocol P2 (P2<P1>), No need to include P1.
llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
bool DropIt = false;
ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
if (PDecl == TargetPDecl)
continue;
if (PDecl->lookupProtocolNamed(
TargetPDecl->getDeclName().getAsIdentifierInfo())) {
DropIt = true;
break;
}
}
if (!DropIt)
MinimalConformingProtocols.push_back(TargetPDecl);
}
if (MinimalConformingProtocols.empty())
return;
edit::Commit commit(*Editor);
rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
*NSAPIObj, commit);
Editor->commit(commit);
}
void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
const TypedefDecl *TypedefDcl) {
QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
if (NSAPIObj->isObjCNSIntegerType(qt))
NSIntegerTypedefed = TypedefDcl;
else if (NSAPIObj->isObjCNSUIntegerType(qt))
NSUIntegerTypedefed = TypedefDcl;
}
bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
const EnumDecl *EnumDcl,
const TypedefDecl *TypedefDcl) {
if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
EnumDcl->isDeprecated())
return false;
if (!TypedefDcl) {
if (NSIntegerTypedefed) {
TypedefDcl = NSIntegerTypedefed;
NSIntegerTypedefed = nullptr;
}
else if (NSUIntegerTypedefed) {
TypedefDcl = NSUIntegerTypedefed;
NSUIntegerTypedefed = nullptr;
}
else
return false;
FileID FileIdOfTypedefDcl =
PP.getSourceManager().getFileID(TypedefDcl->getLocation());
FileID FileIdOfEnumDcl =
PP.getSourceManager().getFileID(EnumDcl->getLocation());
if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
return false;
}
if (TypedefDcl->isDeprecated())
return false;
QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
StringRef NSIntegerName = NSAPIObj->GetNSIntegralKind(qt);
if (NSIntegerName.empty()) {
// Also check for typedef enum {...} TD;
if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
if (EnumTy->getDecl() == EnumDcl) {
bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
if (!InsertFoundation(Ctx, TypedefDcl->getLocStart()))
return false;
edit::Commit commit(*Editor);
rewriteToNSMacroDecl(Ctx, EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Editor->commit(commit);
return true;
}
}
return false;
}
// We may still use NS_OPTIONS based on what we find in the enumertor list.
bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
if (!InsertFoundation(Ctx, TypedefDcl->getLocStart()))
return false;
edit::Commit commit(*Editor);
bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
commit, NSIntegerName, NSOptions);
Editor->commit(commit);
return Res;
}
static void ReplaceWithInstancetype(ASTContext &Ctx,
const ObjCMigrateASTConsumer &ASTC,
ObjCMethodDecl *OM) {
if (OM->getReturnType() == Ctx.getObjCInstanceType())
return; // already has instancetype.
SourceRange R;
std::string ClassString;
if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
TypeLoc TL = TSInfo->getTypeLoc();
R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
ClassString = "instancetype";
}
else {
R = SourceRange(OM->getLocStart(), OM->getLocStart());
ClassString = OM->isInstanceMethod() ? '-' : '+';
ClassString += " (instancetype)";
}
edit::Commit commit(*ASTC.Editor);
commit.replace(R, ClassString);
ASTC.Editor->commit(commit);
}
static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
ObjCMethodDecl *OM) {
ObjCInterfaceDecl *IDecl = OM->getClassInterface();
SourceRange R;
std::string ClassString;
if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
TypeLoc TL = TSInfo->getTypeLoc();
R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
ClassString = IDecl->getName();
ClassString += "*";
}
}
else {
R = SourceRange(OM->getLocStart(), OM->getLocStart());
ClassString = "+ (";
ClassString += IDecl->getName(); ClassString += "*)";
}
edit::Commit commit(*ASTC.Editor);
commit.replace(R, ClassString);
ASTC.Editor->commit(commit);
}
void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
ObjCContainerDecl *CDecl,
ObjCMethodDecl *OM) {