blob: 038101ae4a4ddaf7e30f93750b879b7624ac76e0 [file] [log] [blame]
Ted Kremenekf7639e12012-03-06 20:06:33 +00001//===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Fariborz Jahanian85e988b2013-07-18 22:17:33 +000010#include "Transforms.h"
Hans Wennborgbf6dda52013-12-12 02:24:20 +000011#include "clang/ARCMigrate/ARCMT.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000012#include "clang/ARCMigrate/ARCMTActions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000013#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000015#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/NSAPI.h"
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +000017#include "clang/AST/ParentMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000019#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Basic/FileManager.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/EditedSource.h"
23#include "clang/Edit/EditsReceiver.h"
24#include "clang/Edit/Rewriters.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000025#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/MultiplexConsumer.h"
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000027#include "clang/Lex/PPConditionalDirectiveRecord.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Lex/Preprocessor.h"
29#include "clang/Rewrite/Core/Rewriter.h"
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000030#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000031#include "llvm/ADT/SmallString.h"
David Blaikie13156b62014-11-19 03:06:06 +000032#include "llvm/ADT/StringSet.h"
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +000033#include "llvm/Support/Path.h"
Hans Wennborgbf6dda52013-12-12 02:24:20 +000034#include "llvm/Support/SourceMgr.h"
35#include "llvm/Support/YAMLParser.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000036
37using namespace clang;
38using namespace arcmt;
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000039using namespace ento::objc_retain;
Ted Kremenekf7639e12012-03-06 20:06:33 +000040
41namespace {
42
43class ObjCMigrateASTConsumer : public ASTConsumer {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000044 enum CF_BRIDGING_KIND {
45 CF_BRIDGING_NONE,
46 CF_BRIDGING_ENABLE,
47 CF_BRIDGING_MAY_INCLUDE
48 };
Fangrui Song6907ce22018-07-30 19:24:48 +000049
Ted Kremenekf7639e12012-03-06 20:06:33 +000050 void migrateDecl(Decl *D);
Fariborz Jahaniane1b98432015-04-02 21:36:03 +000051 void migrateObjCContainerDecl(ASTContext &Ctx, ObjCContainerDecl *D);
Fariborz Jahanian1be01532013-07-12 22:32:19 +000052 void migrateProtocolConformance(ASTContext &Ctx,
53 const ObjCImplementationDecl *ImpDecl);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +000054 void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +000055 bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
Fariborz Jahanian92463272013-07-18 20:11:45 +000056 const TypedefDecl *TypedefDcl);
Fariborz Jahanian8c45e282013-10-02 22:49:59 +000057 void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000058 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
59 ObjCMethodDecl *OM);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000060 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +000061 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
Fariborz Jahanian10b74352013-09-24 20:20:52 +000062 void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000063 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000064 ObjCMethodDecl *OM,
65 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fangrui Song6907ce22018-07-30 19:24:48 +000066
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000067 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000068 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000069 const FunctionDecl *FuncDecl, bool ResultAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000070 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000071 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
Fangrui Song6907ce22018-07-30 19:24:48 +000072
Fariborz Jahanian301b5212013-08-20 22:42:13 +000073 void AnnotateImplicitBridging(ASTContext &Ctx);
Fangrui Song6907ce22018-07-30 19:24:48 +000074
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000075 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
76 const FunctionDecl *FuncDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +000077
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000078 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +000079
Fariborz Jahanian89f6d102013-09-04 00:10:06 +000080 void migrateAddMethodAnnotation(ASTContext &Ctx,
81 const ObjCMethodDecl *MethodDecl);
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +000082
83 void inferDesignatedInitializers(ASTContext &Ctx,
84 const ObjCImplementationDecl *ImplD);
Fangrui Song6907ce22018-07-30 19:24:48 +000085
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +000086 bool InsertFoundation(ASTContext &Ctx, SourceLocation Loc);
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +000087
Ted Kremenekf7639e12012-03-06 20:06:33 +000088public:
89 std::string MigrateDir;
Fariborz Jahanian182486c2013-10-02 17:08:12 +000090 unsigned ASTMigrateActions;
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +000091 FileID FileId;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +000092 const TypedefDecl *NSIntegerTypedefed;
93 const TypedefDecl *NSUIntegerTypedefed;
Ahmed Charlesb8984322014-03-07 20:03:18 +000094 std::unique_ptr<NSAPI> NSAPIObj;
95 std::unique_ptr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000096 FileRemapper &Remapper;
97 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000098 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000099 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000100 bool IsOutputFile;
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +0000101 bool FoundationIncluded;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000102 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000103 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
David Blaikie13156b62014-11-19 03:06:06 +0000104 llvm::StringSet<> WhiteListFilenames;
David Blaikie3c8c46e2014-11-19 05:48:40 +0000105
Ted Kremenekf7639e12012-03-06 20:06:33 +0000106 ObjCMigrateASTConsumer(StringRef migrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000107 unsigned astMigrateActions,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000108 FileRemapper &remapper,
109 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000110 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000111 Preprocessor &PP,
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000112 bool isOutputFile,
113 ArrayRef<std::string> WhiteList)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000114 : MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000115 ASTMigrateActions(astMigrateActions),
Craig Topper8ae12032014-05-07 06:21:57 +0000116 NSIntegerTypedefed(nullptr), NSUIntegerTypedefed(nullptr),
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000117 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +0000118 IsOutputFile(isOutputFile),
119 FoundationIncluded(false){
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000120
David Blaikie13156b62014-11-19 03:06:06 +0000121 // FIXME: StringSet should have insert(iter, iter) to use here.
122 for (const std::string &Val : WhiteList)
123 WhiteListFilenames.insert(Val);
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000124 }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000125
126protected:
Craig Topperb45acb82014-03-14 06:02:07 +0000127 void Initialize(ASTContext &Context) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000128 NSAPIObj.reset(new NSAPI(Context));
129 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000130 Context.getLangOpts(),
Argyrios Kyrtzidis7dd31332014-04-28 02:38:51 +0000131 PPRec));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000132 }
133
Craig Topperb45acb82014-03-14 06:02:07 +0000134 bool HandleTopLevelDecl(DeclGroupRef DG) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000135 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
136 migrateDecl(*I);
137 return true;
138 }
Craig Topperb45acb82014-03-14 06:02:07 +0000139 void HandleInterestingDecl(DeclGroupRef DG) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000140 // Ignore decls from the PCH.
141 }
Craig Topperb45acb82014-03-14 06:02:07 +0000142 void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000143 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
144 }
145
Craig Topperb45acb82014-03-14 06:02:07 +0000146 void HandleTranslationUnit(ASTContext &Ctx) override;
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000147
148 bool canModifyFile(StringRef Path) {
149 if (WhiteListFilenames.empty())
150 return true;
151 return WhiteListFilenames.find(llvm::sys::path::filename(Path))
152 != WhiteListFilenames.end();
153 }
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +0000154 bool canModifyFile(const FileEntry *FE) {
155 if (!FE)
156 return false;
157 return canModifyFile(FE->getName());
158 }
159 bool canModifyFile(FileID FID) {
160 if (FID.isInvalid())
161 return false;
162 return canModifyFile(PP.getSourceManager().getFileEntryForID(FID));
163 }
164
165 bool canModify(const Decl *D) {
166 if (!D)
167 return false;
168 if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(D))
169 return canModify(CatImpl->getCategoryDecl());
170 if (const ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D))
171 return canModify(Impl->getClassInterface());
172 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
173 return canModify(cast<Decl>(MD->getDeclContext()));
174
175 FileID FID = PP.getSourceManager().getFileID(D->getLocation());
176 return canModifyFile(FID);
177 }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000178};
179
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000180} // end anonymous namespace
Ted Kremenekf7639e12012-03-06 20:06:33 +0000181
Argyrios Kyrtzidisd35e98f2016-02-07 19:28:36 +0000182ObjCMigrateAction::ObjCMigrateAction(
183 std::unique_ptr<FrontendAction> WrappedAction,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000184 StringRef migrateDir,
185 unsigned migrateAction)
Argyrios Kyrtzidisd35e98f2016-02-07 19:28:36 +0000186 : WrapperFrontendAction(std::move(WrappedAction)), MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000187 ObjCMigAction(migrateAction),
Craig Topper8ae12032014-05-07 06:21:57 +0000188 CompInst(nullptr) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000189 if (MigrateDir.empty())
190 MigrateDir = "."; // user current directory if none is given.
191}
192
David Blaikie6beb6aa2014-08-10 19:56:51 +0000193std::unique_ptr<ASTConsumer>
194ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000195 PPConditionalDirectiveRecord *
196 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +0000197 CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000198 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
199 Consumers.push_back(WrapperFrontendAction::CreateASTConsumer(CI, InFile));
200 Consumers.push_back(llvm::make_unique<ObjCMigrateASTConsumer>(
201 MigrateDir, ObjCMigAction, Remapper, CompInst->getFileManager(), PPRec,
Craig Topper5fc8fc22014-08-27 06:28:36 +0000202 CompInst->getPreprocessor(), false, None));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000203 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000204}
205
206bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
207 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
208 /*ignoreIfFilesChanges=*/true);
209 CompInst = &CI;
210 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000211 return true;
212}
213
214namespace {
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000215 // FIXME. This duplicates one in RewriteObjCFoundationAPI.cpp
216 bool subscriptOperatorNeedsParens(const Expr *FullExpr) {
217 const Expr* Expr = FullExpr->IgnoreImpCasts();
Alexander Kornienkoad988852015-11-06 01:26:37 +0000218 return !(isa<ArraySubscriptExpr>(Expr) || isa<CallExpr>(Expr) ||
219 isa<DeclRefExpr>(Expr) || isa<CXXNamedCastExpr>(Expr) ||
220 isa<CXXConstructExpr>(Expr) || isa<CXXThisExpr>(Expr) ||
221 isa<CXXTypeidExpr>(Expr) ||
222 isa<CXXUnresolvedConstructExpr>(Expr) ||
223 isa<ObjCMessageExpr>(Expr) || isa<ObjCPropertyRefExpr>(Expr) ||
224 isa<ObjCProtocolExpr>(Expr) || isa<MemberExpr>(Expr) ||
225 isa<ObjCIvarRefExpr>(Expr) || isa<ParenExpr>(FullExpr) ||
226 isa<ParenListExpr>(Expr) || isa<SizeOfPackExpr>(Expr));
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000227 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000228
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000229 /// - Rewrite message expression for Objective-C setter and getters into
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000230 /// property-dot syntax.
231 bool rewriteToPropertyDotSyntax(const ObjCMessageExpr *Msg,
232 Preprocessor &PP,
233 const NSAPI &NS, edit::Commit &commit,
234 const ParentMap *PMap) {
235 if (!Msg || Msg->isImplicit() ||
Fariborz Jahaniandf833a42014-12-09 22:36:47 +0000236 (Msg->getReceiverKind() != ObjCMessageExpr::Instance &&
237 Msg->getReceiverKind() != ObjCMessageExpr::SuperInstance))
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000238 return false;
Fariborz Jahanian30609b82015-01-23 19:23:42 +0000239 if (const Expr *Receiver = Msg->getInstanceReceiver())
240 if (Receiver->getType()->isObjCBuiltinType())
241 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000242
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000243 const ObjCMethodDecl *Method = Msg->getMethodDecl();
244 if (!Method)
245 return false;
246 if (!Method->isPropertyAccessor())
247 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000248
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000249 const ObjCPropertyDecl *Prop = Method->findPropertyDecl();
250 if (!Prop)
251 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000252
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000253 SourceRange MsgRange = Msg->getSourceRange();
Fariborz Jahaniandf833a42014-12-09 22:36:47 +0000254 bool ReceiverIsSuper =
255 (Msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
256 // for 'super' receiver is nullptr.
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000257 const Expr *receiver = Msg->getInstanceReceiver();
Fariborz Jahaniandf833a42014-12-09 22:36:47 +0000258 bool NeedsParen =
259 ReceiverIsSuper ? false : subscriptOperatorNeedsParens(receiver);
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000260 bool IsGetter = (Msg->getNumArgs() == 0);
261 if (IsGetter) {
262 // Find space location range between receiver expression and getter method.
Fariborz Jahaniandf833a42014-12-09 22:36:47 +0000263 SourceLocation BegLoc =
264 ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000265 BegLoc = PP.getLocForEndOfToken(BegLoc);
266 SourceLocation EndLoc = Msg->getSelectorLoc(0);
267 SourceRange SpaceRange(BegLoc, EndLoc);
268 std::string PropertyDotString;
269 // rewrite getter method expression into: receiver.property or
270 // (receiver).property
271 if (NeedsParen) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000272 commit.insertBefore(receiver->getBeginLoc(), "(");
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000273 PropertyDotString = ").";
274 }
275 else
276 PropertyDotString = ".";
277 PropertyDotString += Prop->getName();
278 commit.replace(SpaceRange, PropertyDotString);
Fangrui Song6907ce22018-07-30 19:24:48 +0000279
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000280 // remove '[' ']'
281 commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
282 commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
283 } else {
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000284 if (NeedsParen)
Fariborz Jahaniandf833a42014-12-09 22:36:47 +0000285 commit.insertWrap("(", receiver->getSourceRange(), ")");
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000286 std::string PropertyDotString = ".";
287 PropertyDotString += Prop->getName();
288 PropertyDotString += " =";
289 const Expr*const* Args = Msg->getArgs();
290 const Expr *RHS = Args[0];
291 if (!RHS)
292 return false;
Fariborz Jahaniandf833a42014-12-09 22:36:47 +0000293 SourceLocation BegLoc =
294 ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000295 BegLoc = PP.getLocForEndOfToken(BegLoc);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000296 SourceLocation EndLoc = RHS->getBeginLoc();
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000297 EndLoc = EndLoc.getLocWithOffset(-1);
Fariborz Jahanianf9317f12015-01-23 21:58:46 +0000298 const char *colon = PP.getSourceManager().getCharacterData(EndLoc);
299 // Add a space after '=' if there is no space between RHS and '='
300 if (colon && colon[0] == ':')
301 PropertyDotString += " ";
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000302 SourceRange Range(BegLoc, EndLoc);
303 commit.replace(Range, PropertyDotString);
304 // remove '[' ']'
305 commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
306 commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
307 }
308 return true;
309 }
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000310
Ted Kremenekf7639e12012-03-06 20:06:33 +0000311class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
312 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000313 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000314
315public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000316 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
317 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000318
319 bool shouldVisitTemplateInstantiations() const { return false; }
320 bool shouldWalkTypesOfTypeLocs() const { return false; }
321
322 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000323 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000324 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000325 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000326 Consumer.Editor->commit(commit);
327 }
328
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000329 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000330 edit::Commit commit(*Consumer.Editor);
331 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
332 Consumer.Editor->commit(commit);
333 }
334
Fariborz Jahaniana6556f72014-10-31 21:19:45 +0000335 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_PropertyDotSyntax) {
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000336 edit::Commit commit(*Consumer.Editor);
337 rewriteToPropertyDotSyntax(E, Consumer.PP, *Consumer.NSAPIObj,
338 commit, &PMap);
339 Consumer.Editor->commit(commit);
340 }
341
Ted Kremenekf7639e12012-03-06 20:06:33 +0000342 return true;
343 }
344
345 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
346 // Do depth first; we want to rewrite the subexpressions first so that if
347 // we have to move expressions we will move them already rewritten.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000348 for (Stmt *SubStmt : E->children())
349 if (!TraverseStmt(SubStmt))
Ted Kremenekf7639e12012-03-06 20:06:33 +0000350 return false;
351
352 return WalkUpFromObjCMessageExpr(E);
353 }
354};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000355
356class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
357 ObjCMigrateASTConsumer &Consumer;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000358 std::unique_ptr<ParentMap> PMap;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000359
360public:
361 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
362
363 bool shouldVisitTemplateInstantiations() const { return false; }
364 bool shouldWalkTypesOfTypeLocs() const { return false; }
365
366 bool TraverseStmt(Stmt *S) {
367 PMap.reset(new ParentMap(S));
368 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
369 return true;
370 }
371};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +0000372} // end anonymous namespace
Ted Kremenekf7639e12012-03-06 20:06:33 +0000373
374void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
375 if (!D)
376 return;
377 if (isa<ObjCMethodDecl>(D))
378 return; // Wait for the ObjC container declaration.
379
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000380 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000381}
382
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000383static void append_attr(std::string &PropertyString, const char *attr,
384 bool &LParenAdded) {
385 if (!LParenAdded) {
386 PropertyString += "(";
387 LParenAdded = true;
388 }
389 else
390 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000391 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000392}
393
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000394static
395void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
396 const std::string& TypeString,
397 const char *name) {
398 const char *argPtr = TypeString.c_str();
399 int paren = 0;
400 while (*argPtr) {
401 switch (*argPtr) {
402 case '(':
403 PropertyString += *argPtr;
404 paren++;
405 break;
406 case ')':
407 PropertyString += *argPtr;
408 paren--;
409 break;
410 case '^':
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000411 case '*':
412 PropertyString += (*argPtr);
413 if (paren == 1) {
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000414 PropertyString += name;
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000415 name = "";
416 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000417 break;
418 default:
419 PropertyString += *argPtr;
420 break;
421 }
422 argPtr++;
423 }
424}
425
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000426static const char *PropertyMemoryAttribute(ASTContext &Context, QualType ArgType) {
427 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
428 bool RetainableObject = ArgType->isObjCRetainableType();
Fariborz Jahanian49e69ee2013-12-12 01:02:00 +0000429 if (RetainableObject &&
430 (propertyLifetime == Qualifiers::OCL_Strong
431 || propertyLifetime == Qualifiers::OCL_None)) {
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000432 if (const ObjCObjectPointerType *ObjPtrTy =
433 ArgType->getAs<ObjCObjectPointerType>()) {
434 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
435 if (IDecl &&
436 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
437 return "copy";
438 else
Fariborz Jahanian54c8eaa2013-11-21 00:58:17 +0000439 return "strong";
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000440 }
441 else if (ArgType->isBlockPointerType())
442 return "copy";
443 } else if (propertyLifetime == Qualifiers::OCL_Weak)
444 // TODO. More precise determination of 'weak' attribute requires
445 // looking into setter's implementation for backing weak ivar.
446 return "weak";
447 else if (RetainableObject)
Fariborz Jahanian54c8eaa2013-11-21 00:58:17 +0000448 return ArgType->isBlockPointerType() ? "copy" : "strong";
Craig Topper8ae12032014-05-07 06:21:57 +0000449 return nullptr;
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000450}
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000451
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000452static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000453 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000454 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000455 unsigned LengthOfPrefix,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +0000456 bool Atomic, bool UseNsIosOnlyMacro,
457 bool AvailabilityArgsMatch) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000458 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000459 bool LParenAdded = false;
460 std::string PropertyString = "@property ";
Richard Smith20e883e2015-04-29 23:20:19 +0000461 if (UseNsIosOnlyMacro && NS.isMacroDefined("NS_NONATOMIC_IOSONLY")) {
Fariborz Jahanianbed1be92013-11-12 19:25:50 +0000462 PropertyString += "(NS_NONATOMIC_IOSONLY";
463 LParenAdded = true;
464 } else if (!Atomic) {
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000465 PropertyString += "(nonatomic";
466 LParenAdded = true;
467 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000468
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000469 std::string PropertyNameString = Getter->getNameAsString();
470 StringRef PropertyName(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000471 if (LengthOfPrefix > 0) {
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000472 if (!LParenAdded) {
473 PropertyString += "(getter=";
474 LParenAdded = true;
475 }
476 else
477 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000478 PropertyString += PropertyNameString;
479 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000480 // Property with no setter may be suggested as a 'readonly' property.
Fariborz Jahaniand9aef7882013-11-21 17:49:34 +0000481 if (!Setter)
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000482 append_attr(PropertyString, "readonly", LParenAdded);
Fangrui Song6907ce22018-07-30 19:24:48 +0000483
484
Fariborz Jahanian33304e302013-10-16 18:52:17 +0000485 // Short circuit 'delegate' properties that contain the name "delegate" or
486 // "dataSource", or have exact name "target" to have 'assign' attribute.
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000487 if (PropertyName.equals("target") ||
488 (PropertyName.find("delegate") != StringRef::npos) ||
Fariborz Jahanian78bff052013-10-16 20:44:26 +0000489 (PropertyName.find("dataSource") != StringRef::npos)) {
Alp Toker314cc812014-01-25 16:55:45 +0000490 QualType QT = Getter->getReturnType();
Fariborz Jahanian78bff052013-10-16 20:44:26 +0000491 if (!QT->isRealType())
492 append_attr(PropertyString, "assign", LParenAdded);
Fariborz Jahaniand9aef7882013-11-21 17:49:34 +0000493 } else if (!Setter) {
Alp Toker314cc812014-01-25 16:55:45 +0000494 QualType ResType = Context.getCanonicalType(Getter->getReturnType());
Fariborz Jahaniand9aef7882013-11-21 17:49:34 +0000495 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ResType))
496 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
497 } else {
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000498 const ParmVarDecl *argDecl = *Setter->param_begin();
499 QualType ArgType = Context.getCanonicalType(argDecl->getType());
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000500 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ArgType))
501 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000502 }
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000503 if (LParenAdded)
504 PropertyString += ')';
Alp Toker314cc812014-01-25 16:55:45 +0000505 QualType RT = Getter->getReturnType();
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000506 if (!isa<TypedefType>(RT)) {
507 // strip off any ARC lifetime qualifier.
508 QualType CanResultTy = Context.getCanonicalType(RT);
509 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
510 Qualifiers Qs = CanResultTy.getQualifiers();
511 Qs.removeObjCLifetime();
512 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
513 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000514 }
515 PropertyString += " ";
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000516 PrintingPolicy SubPolicy(Context.getPrintingPolicy());
517 SubPolicy.SuppressStrongLifetime = true;
Fariborz Jahaniande557f82013-10-09 17:37:28 +0000518 SubPolicy.SuppressLifetimeQualifiers = true;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000519 std::string TypeString = RT.getAsString(SubPolicy);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000520 if (LengthOfPrefix > 0) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000521 // property name must strip off "is" and lower case the first character
522 // after that; e.g. isContinuous will become continuous.
523 StringRef PropertyNameStringRef(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000524 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000525 PropertyNameString = PropertyNameStringRef;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000526 bool NoLowering = (isUppercase(PropertyNameString[0]) &&
527 PropertyNameString.size() > 1 &&
528 isUppercase(PropertyNameString[1]));
Fariborz Jahanian34fea362013-09-11 18:27:16 +0000529 if (!NoLowering)
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000530 PropertyNameString[0] = toLowercase(PropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000531 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000532 if (RT->isBlockPointerType() || RT->isFunctionPointerType())
533 MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
534 TypeString,
535 PropertyNameString.c_str());
536 else {
537 char LastChar = TypeString[TypeString.size()-1];
538 PropertyString += TypeString;
539 if (LastChar != '*')
540 PropertyString += ' ';
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000541 PropertyString += PropertyNameString;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000542 }
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000543 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
544 Selector GetterSelector = Getter->getSelector();
Fangrui Song6907ce22018-07-30 19:24:48 +0000545
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000546 SourceLocation EndGetterSelectorLoc =
547 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000548 commit.replace(CharSourceRange::getCharRange(Getter->getBeginLoc(),
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000549 EndGetterSelectorLoc),
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000550 PropertyString);
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000551 if (Setter && AvailabilityArgsMatch) {
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000552 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
553 // Get location past ';'
554 EndLoc = EndLoc.getLocWithOffset(1);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000555 SourceLocation BeginOfSetterDclLoc = Setter->getBeginLoc();
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000556 // FIXME. This assumes that setter decl; is immediately preceded by eoln.
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000557 // It is trying to remove the setter method decl. line entirely.
558 BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
559 commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000560 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000561}
562
Fariborz Jahanian48a44d42013-11-19 18:17:31 +0000563static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) {
564 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) {
565 StringRef Name = CatDecl->getName();
566 return Name.endswith("Deprecated");
567 }
568 return false;
569}
570
Fariborz Jahaniane1b98432015-04-02 21:36:03 +0000571void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000572 ObjCContainerDecl *D) {
Fariborz Jahanian48a44d42013-11-19 18:17:31 +0000573 if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D))
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000574 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000575
Aaron Ballmanaff18c02014-03-13 19:03:34 +0000576 for (auto *Method : D->methods()) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000577 if (Method->isDeprecated())
578 continue;
Fariborz Jahanianec7cea92013-11-08 01:15:17 +0000579 bool PropertyInferred = migrateProperty(Ctx, D, Method);
580 // If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to
581 // the getter method as it ends up on the property itself which we don't want
582 // to do unless -objcmt-returns-innerpointer-property option is on.
583 if (!PropertyInferred ||
584 (ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
Fariborz Jahanian22626e72013-11-08 02:00:22 +0000585 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
586 migrateNsReturnsInnerPointer(Ctx, Method);
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000587 }
Fariborz Jahanian23417072013-11-05 22:28:30 +0000588 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
589 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000590
Manman Rena7a8b1f2016-01-26 18:05:23 +0000591 for (auto *Prop : D->instance_properties()) {
Fariborz Jahanian8c45e282013-10-02 22:49:59 +0000592 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000593 !Prop->isDeprecated())
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000594 migratePropertyNsReturnsInnerPointer(Ctx, Prop);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000595 }
596}
597
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000598static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000599ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000600 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000601 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000602 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000603 // In auto-synthesis, protocol properties are not synthesized. So,
604 // a conforming protocol must have its required properties declared
605 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000606 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000607 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
Manman Rena7a8b1f2016-01-26 18:05:23 +0000608 for (const auto *Property : PDecl->instance_properties()) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000609 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
610 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000611 HasAtleastOneRequiredProperty = true;
Richard Smithcf4bdde2015-02-21 02:45:19 +0000612 DeclContext::lookup_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000613 if (R.size() == 0) {
614 // Relax the rule and look into class's implementation for a synthesize
615 // or dynamic declaration. Class is implementing a property coming from
616 // another protocol. This still makes the target protocol as conforming.
617 if (!ImpDecl->FindPropertyImplDecl(
Manman Ren5b786402016-01-28 18:49:28 +0000618 Property->getDeclName().getAsIdentifierInfo(),
619 Property->getQueryKind()))
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000620 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000621 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000622 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
623 if ((ClassProperty->getPropertyAttributes()
624 != Property->getPropertyAttributes()) ||
625 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
626 return false;
627 }
628 else
629 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000630 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000631
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000632 // At this point, all required properties in this protocol conform to those
633 // declared in the class.
634 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000635 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000636 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
637 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000638 return HasAtleastOneRequiredProperty;
Aaron Ballmanaff18c02014-03-13 19:03:34 +0000639 for (const auto *MD : PDecl->methods()) {
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000640 if (MD->isImplicit())
641 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000642 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
643 continue;
Richard Smithcf4bdde2015-02-21 02:45:19 +0000644 DeclContext::lookup_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000645 if (R.size() == 0)
646 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000647 bool match = false;
648 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000649 for (unsigned I = 0, N = R.size(); I != N; ++I)
650 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
651 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
652 match = true;
653 break;
654 }
655 if (!match)
656 return false;
657 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000658 }
Alexander Kornienkoad988852015-11-06 01:26:37 +0000659 return HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000660}
661
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000662static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
663 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
664 const NSAPI &NS, edit::Commit &commit) {
665 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
666 std::string ClassString;
667 SourceLocation EndLoc =
668 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
Fangrui Song6907ce22018-07-30 19:24:48 +0000669
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000670 if (Protocols.empty()) {
671 ClassString = '<';
672 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
673 ClassString += ConformingProtocols[i]->getNameAsString();
674 if (i != (e-1))
675 ClassString += ", ";
676 }
677 ClassString += "> ";
678 }
679 else {
680 ClassString = ", ";
681 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
682 ClassString += ConformingProtocols[i]->getNameAsString();
683 if (i != (e-1))
684 ClassString += ", ";
685 }
686 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
687 EndLoc = *PL;
688 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000689
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000690 commit.insertAfterToken(EndLoc, ClassString);
691 return true;
692}
693
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000694static StringRef GetUnsignedName(StringRef NSIntegerName) {
695 StringRef UnsignedName = llvm::StringSwitch<StringRef>(NSIntegerName)
696 .Case("int8_t", "uint8_t")
697 .Case("int16_t", "uint16_t")
698 .Case("int32_t", "uint32_t")
699 .Case("NSInteger", "NSUInteger")
700 .Case("int64_t", "uint64_t")
701 .Default(NSIntegerName);
702 return UnsignedName;
703}
704
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000705static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
706 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000707 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000708 StringRef NSIntegerName,
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000709 bool NSOptions) {
710 std::string ClassString;
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000711 if (NSOptions) {
712 ClassString = "typedef NS_OPTIONS(";
713 ClassString += GetUnsignedName(NSIntegerName);
714 }
715 else {
716 ClassString = "typedef NS_ENUM(";
717 ClassString += NSIntegerName;
718 }
719 ClassString += ", ";
Fangrui Song6907ce22018-07-30 19:24:48 +0000720
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000721 ClassString += TypedefDcl->getIdentifier()->getName();
722 ClassString += ')';
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000723 SourceRange R(EnumDcl->getBeginLoc(), EnumDcl->getBeginLoc());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000724 commit.replace(R, ClassString);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000725 SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
726 EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
727 NS.getASTContext(), /*IsDecl*/true);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000728 if (EndOfEnumDclLoc.isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000729 SourceRange EnumDclRange(EnumDcl->getBeginLoc(), EndOfEnumDclLoc);
730 commit.insertFromRange(TypedefDcl->getBeginLoc(), EnumDclRange);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000731 }
732 else
733 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000734
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000735 SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
736 EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
737 NS.getASTContext(), /*IsDecl*/true);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000738 if (EndTypedefDclLoc.isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000739 SourceRange TDRange(TypedefDcl->getBeginLoc(), EndTypedefDclLoc);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000740 commit.remove(TDRange);
741 }
742 else
743 return false;
744
745 EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
Fariborz Jahanian1d27ffd2013-10-11 17:35:22 +0000746 /*IsDecl*/true);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000747 if (EndOfEnumDclLoc.isValid()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000748 SourceLocation BeginOfEnumDclLoc = EnumDcl->getBeginLoc();
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000749 // FIXME. This assumes that enum decl; is immediately preceded by eoln.
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000750 // It is trying to remove the enum decl. lines entirely.
751 BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
752 commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000753 return true;
754 }
755 return false;
756}
757
Fariborz Jahanian1406c872014-12-10 18:25:24 +0000758static void rewriteToNSMacroDecl(ASTContext &Ctx,
759 const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000760 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000761 const NSAPI &NS, edit::Commit &commit,
762 bool IsNSIntegerType) {
Fariborz Jahanian7b012d32015-03-02 23:58:02 +0000763 QualType DesignatedEnumType = EnumDcl->getIntegerType();
764 assert(!DesignatedEnumType.isNull()
Fariborz Jahanian1406c872014-12-10 18:25:24 +0000765 && "rewriteToNSMacroDecl - underlying enum type is null");
Fangrui Song6907ce22018-07-30 19:24:48 +0000766
Fariborz Jahanian1406c872014-12-10 18:25:24 +0000767 PrintingPolicy Policy(Ctx.getPrintingPolicy());
Fariborz Jahanian7b012d32015-03-02 23:58:02 +0000768 std::string TypeString = DesignatedEnumType.getAsString(Policy);
Fariborz Jahanian1406c872014-12-10 18:25:24 +0000769 std::string ClassString = IsNSIntegerType ? "NS_ENUM(" : "NS_OPTIONS(";
770 ClassString += TypeString;
771 ClassString += ", ";
Fangrui Song6907ce22018-07-30 19:24:48 +0000772
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000773 ClassString += TypedefDcl->getIdentifier()->getName();
Argyrios Kyrtzidis88737a52016-07-15 19:22:34 +0000774 ClassString += ") ";
775 SourceLocation EndLoc = EnumDcl->getBraceRange().getBegin();
776 if (EndLoc.isInvalid())
777 return;
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000778 CharSourceRange R =
779 CharSourceRange::getCharRange(EnumDcl->getBeginLoc(), EndLoc);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000780 commit.replace(R, ClassString);
Fariborz Jahanian77a835b2014-10-01 20:46:32 +0000781 // This is to remove spaces between '}' and typedef name.
782 SourceLocation StartTypedefLoc = EnumDcl->getLocEnd();
783 StartTypedefLoc = StartTypedefLoc.getLocWithOffset(+1);
784 SourceLocation EndTypedefLoc = TypedefDcl->getLocEnd();
Fangrui Song6907ce22018-07-30 19:24:48 +0000785
Fariborz Jahanian77a835b2014-10-01 20:46:32 +0000786 commit.remove(SourceRange(StartTypedefLoc, EndTypedefLoc));
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000787}
788
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000789static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000790 const EnumDecl *EnumDcl) {
791 bool PowerOfTwo = true;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000792 bool AllHexdecimalEnumerator = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000793 uint64_t MaxPowerOfTwoVal = 0;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000794 for (auto Enumerator : EnumDcl->enumerators()) {
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000795 const Expr *InitExpr = Enumerator->getInitExpr();
796 if (!InitExpr) {
797 PowerOfTwo = false;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000798 AllHexdecimalEnumerator = false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000799 continue;
800 }
Fariborz Jahanian6e1798e2013-09-17 23:32:51 +0000801 InitExpr = InitExpr->IgnoreParenCasts();
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000802 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
803 if (BO->isShiftOp() || BO->isBitwiseOp())
804 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000805
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000806 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000807 if (PowerOfTwo && EnumVal) {
808 if (!llvm::isPowerOf2_64(EnumVal))
809 PowerOfTwo = false;
810 else if (EnumVal > MaxPowerOfTwoVal)
811 MaxPowerOfTwoVal = EnumVal;
812 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000813 if (AllHexdecimalEnumerator && EnumVal) {
814 bool FoundHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000815 SourceLocation EndLoc = Enumerator->getLocEnd();
816 Token Tok;
817 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
818 if (Tok.isLiteral() && Tok.getLength() > 2) {
819 if (const char *StringLit = Tok.getLiteralData())
820 FoundHexdecimalEnumerator =
821 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
822 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000823 if (!FoundHexdecimalEnumerator)
824 AllHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000825 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000826 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000827 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000828}
829
Fangrui Song6907ce22018-07-30 19:24:48 +0000830void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000831 const ObjCImplementationDecl *ImpDecl) {
832 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000833 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000834 return;
835 // Find all implicit conforming protocols for this class
836 // and make them explicit.
837 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
838 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000839 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fangrui Song6907ce22018-07-30 19:24:48 +0000840
Craig Topperc6914d02014-08-25 04:15:02 +0000841 for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls)
842 if (!ExplicitProtocols.count(ProtDecl))
843 PotentialImplicitProtocols.push_back(ProtDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +0000844
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000845 if (PotentialImplicitProtocols.empty())
846 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000847
848 // go through list of non-optional methods and properties in each protocol
849 // in the PotentialImplicitProtocols list. If class implements every one of the
850 // methods and properties, then this class conforms to this protocol.
851 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
852 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000853 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000854 PotentialImplicitProtocols[i]))
855 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fangrui Song6907ce22018-07-30 19:24:48 +0000856
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000857 if (ConformingProtocols.empty())
858 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000859
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000860 // Further reduce number of conforming protocols. If protocol P1 is in the list
861 // protocol P2 (P2<P1>), No need to include P1.
862 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
863 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
864 bool DropIt = false;
865 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
866 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
867 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
868 if (PDecl == TargetPDecl)
869 continue;
870 if (PDecl->lookupProtocolNamed(
871 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
872 DropIt = true;
873 break;
874 }
875 }
876 if (!DropIt)
877 MinimalConformingProtocols.push_back(TargetPDecl);
878 }
Fariborz Jahanian769c04e2013-12-17 01:01:33 +0000879 if (MinimalConformingProtocols.empty())
880 return;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000881 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000882 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
883 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000884 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000885}
886
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000887void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
888 const TypedefDecl *TypedefDcl) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000889
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000890 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
891 if (NSAPIObj->isObjCNSIntegerType(qt))
892 NSIntegerTypedefed = TypedefDcl;
893 else if (NSAPIObj->isObjCNSUIntegerType(qt))
894 NSUIntegerTypedefed = TypedefDcl;
895}
896
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000897bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
Fariborz Jahanian92463272013-07-18 20:11:45 +0000898 const EnumDecl *EnumDcl,
899 const TypedefDecl *TypedefDcl) {
900 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
Fariborz Jahanian4732d43cc2015-01-26 17:41:03 +0000901 EnumDcl->isDeprecated())
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000902 return false;
903 if (!TypedefDcl) {
904 if (NSIntegerTypedefed) {
905 TypedefDcl = NSIntegerTypedefed;
Craig Topper8ae12032014-05-07 06:21:57 +0000906 NSIntegerTypedefed = nullptr;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000907 }
908 else if (NSUIntegerTypedefed) {
909 TypedefDcl = NSUIntegerTypedefed;
Craig Topper8ae12032014-05-07 06:21:57 +0000910 NSUIntegerTypedefed = nullptr;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000911 }
912 else
913 return false;
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +0000914 FileID FileIdOfTypedefDcl =
915 PP.getSourceManager().getFileID(TypedefDcl->getLocation());
916 FileID FileIdOfEnumDcl =
917 PP.getSourceManager().getFileID(EnumDcl->getLocation());
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000918 if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
919 return false;
920 }
921 if (TypedefDcl->isDeprecated())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000922 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000923
Fariborz Jahanian92463272013-07-18 20:11:45 +0000924 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000925 StringRef NSIntegerName = NSAPIObj->GetNSIntegralKind(qt);
Fangrui Song6907ce22018-07-30 19:24:48 +0000926
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000927 if (NSIntegerName.empty()) {
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000928 // Also check for typedef enum {...} TD;
929 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
930 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000931 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000932 if (!InsertFoundation(Ctx, TypedefDcl->getBeginLoc()))
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000933 return false;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000934 edit::Commit commit(*Editor);
Fariborz Jahanian1406c872014-12-10 18:25:24 +0000935 rewriteToNSMacroDecl(Ctx, EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000936 Editor->commit(commit);
Fariborz Jahaniande79e812013-10-17 22:23:32 +0000937 return true;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000938 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000939 }
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000940 return false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000941 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000942
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000943 // We may still use NS_OPTIONS based on what we find in the enumertor list.
944 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000945 if (!InsertFoundation(Ctx, TypedefDcl->getBeginLoc()))
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000946 return false;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000947 edit::Commit commit(*Editor);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000948 bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000949 commit, NSIntegerName, NSOptions);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000950 Editor->commit(commit);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000951 return Res;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000952}
953
Argyrios Kyrtzidisc02a0db2014-05-21 00:24:20 +0000954static void ReplaceWithInstancetype(ASTContext &Ctx,
955 const ObjCMigrateASTConsumer &ASTC,
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000956 ObjCMethodDecl *OM) {
Argyrios Kyrtzidisc02a0db2014-05-21 00:24:20 +0000957 if (OM->getReturnType() == Ctx.getObjCInstanceType())
958 return; // already has instancetype.
959
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000960 SourceRange R;
961 std::string ClassString;
Alp Toker314cc812014-01-25 16:55:45 +0000962 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000963 TypeLoc TL = TSInfo->getTypeLoc();
964 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
965 ClassString = "instancetype";
966 }
967 else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000968 R = SourceRange(OM->getBeginLoc(), OM->getBeginLoc());
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000969 ClassString = OM->isInstanceMethod() ? '-' : '+';
970 ClassString += " (instancetype)";
971 }
972 edit::Commit commit(*ASTC.Editor);
973 commit.replace(R, ClassString);
974 ASTC.Editor->commit(commit);
975}
976
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000977static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
978 ObjCMethodDecl *OM) {
979 ObjCInterfaceDecl *IDecl = OM->getClassInterface();
980 SourceRange R;
981 std::string ClassString;
Alp Toker314cc812014-01-25 16:55:45 +0000982 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000983 TypeLoc TL = TSInfo->getTypeLoc();
984 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
985 ClassString = IDecl->getName();
986 ClassString += "*";
987 }
988 }
989 else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000990 R = SourceRange(OM->getBeginLoc(), OM->getBeginLoc());
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000991 ClassString = "+ (";
992 ClassString += IDecl->getName(); ClassString += "*)";
993 }
994 edit::Commit commit(*ASTC.Editor);
995 commit.replace(R, ClassString);
996 ASTC.Editor->commit(commit);
997}
998
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000999void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
1000 ObjCContainerDecl *CDecl,
1001 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +00001002 ObjCInstanceTypeFamily OIT_Family =
1003 Selector::getInstTypeMethodFamily(OM->getSelector());
Fangrui Song6907ce22018-07-30 19:24:48 +00001004
Fariborz Jahanian267bae32013-07-24 19:18:37 +00001005 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +00001006 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001007 case OIT_None:
1008 migrateFactoryMethod(Ctx, CDecl, OM);
1009 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +00001010 case OIT_Array:
1011 ClassName = "NSArray";
1012 break;
1013 case OIT_Dictionary:
1014 ClassName = "NSDictionary";
1015 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001016 case OIT_Singleton:
1017 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +00001018 return;
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +00001019 case OIT_Init:
Alp Toker314cc812014-01-25 16:55:45 +00001020 if (OM->getReturnType()->isObjCIdType())
Argyrios Kyrtzidisc02a0db2014-05-21 00:24:20 +00001021 ReplaceWithInstancetype(Ctx, *this, OM);
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +00001022 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001023 case OIT_ReturnsSelf:
1024 migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
1025 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +00001026 }
Alp Toker314cc812014-01-25 16:55:45 +00001027 if (!OM->getReturnType()->isObjCIdType())
Fariborz Jahanian71221352013-07-23 22:42:28 +00001028 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001029
Fariborz Jahanian71221352013-07-23 22:42:28 +00001030 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1031 if (!IDecl) {
1032 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1033 IDecl = CatDecl->getClassInterface();
1034 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1035 IDecl = ImpDecl->getClassInterface();
1036 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +00001037 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001038 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
1039 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +00001040 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +00001041 }
Argyrios Kyrtzidisc02a0db2014-05-21 00:24:20 +00001042 ReplaceWithInstancetype(Ctx, *this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +00001043}
1044
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001045static bool TypeIsInnerPointer(QualType T) {
1046 if (!T->isAnyPointerType())
1047 return false;
1048 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
Fariborz Jahanian73466ca2013-09-26 21:43:47 +00001049 T->isBlockPointerType() || T->isFunctionPointerType() ||
1050 ento::coreFoundation::isCFObjectRef(T))
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001051 return false;
Fariborz Jahanian9d5fffb2013-09-09 23:56:14 +00001052 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
1053 // is not an innter pointer type.
1054 QualType OrigT = T;
1055 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
1056 T = TD->getDecl()->getUnderlyingType();
1057 if (OrigT == T || !T->isPointerType())
1058 return true;
1059 const PointerType* PT = T->getAs<PointerType>();
1060 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
1061 if (UPointeeT->isRecordType()) {
1062 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
1063 if (!RecordTy->getDecl()->isCompleteDefinition())
1064 return false;
1065 }
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001066 return true;
1067}
1068
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001069/// Check whether the two versions match.
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001070static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) {
1071 return (X == Y);
1072}
1073
1074/// AvailabilityAttrsMatch - This routine checks that if comparing two
1075/// availability attributes, all their components match. It returns
1076/// true, if not dealing with availability or when all components of
1077/// availability attributes match. This routine is only called when
1078/// the attributes are of the same kind.
1079static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) {
1080 const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1);
1081 if (!AA1)
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001082 return true;
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001083 const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2);
Fangrui Song6907ce22018-07-30 19:24:48 +00001084
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001085 VersionTuple Introduced1 = AA1->getIntroduced();
1086 VersionTuple Deprecated1 = AA1->getDeprecated();
1087 VersionTuple Obsoleted1 = AA1->getObsoleted();
1088 bool IsUnavailable1 = AA1->getUnavailable();
1089 VersionTuple Introduced2 = AA2->getIntroduced();
1090 VersionTuple Deprecated2 = AA2->getDeprecated();
1091 VersionTuple Obsoleted2 = AA2->getObsoleted();
1092 bool IsUnavailable2 = AA2->getUnavailable();
1093 return (versionsMatch(Introduced1, Introduced2) &&
1094 versionsMatch(Deprecated1, Deprecated2) &&
1095 versionsMatch(Obsoleted1, Obsoleted2) &&
1096 IsUnavailable1 == IsUnavailable2);
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001097}
1098
1099static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2,
1100 bool &AvailabilityArgsMatch) {
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001101 // This list is very small, so this need not be optimized.
1102 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
1103 bool match = false;
1104 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00001105 // Matching attribute kind only. Except for Availability attributes,
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001106 // we are not getting into details of the attributes. For all practical purposes
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001107 // this is sufficient.
1108 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001109 if (AvailabilityArgsMatch)
1110 AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]);
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001111 match = true;
1112 break;
1113 }
1114 }
1115 if (!match)
1116 return false;
1117 }
1118 return true;
1119}
1120
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001121/// AttributesMatch - This routine checks list of attributes for two
1122/// decls. It returns false, if there is a mismatch in kind of
1123/// attributes seen in the decls. It returns true if the two decls
1124/// have list of same kind of attributes. Furthermore, when there
1125/// are availability attributes in the two decls, it sets the
1126/// AvailabilityArgsMatch to false if availability attributes have
1127/// different versions, etc.
1128static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2,
1129 bool &AvailabilityArgsMatch) {
1130 if (!Decl1->hasAttrs() || !Decl2->hasAttrs()) {
1131 AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs());
1132 return true;
1133 }
1134 AvailabilityArgsMatch = true;
1135 const AttrVec &Attrs1 = Decl1->getAttrs();
1136 const AttrVec &Attrs2 = Decl2->getAttrs();
1137 bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch);
1138 if (match && (Attrs2.size() > Attrs1.size()))
1139 return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch);
1140 return match;
1141}
1142
Fariborz Jahanian5d783df2013-09-27 22:55:54 +00001143static bool IsValidIdentifier(ASTContext &Ctx,
1144 const char *Name) {
1145 if (!isIdentifierHead(Name[0]))
1146 return false;
1147 std::string NameString = Name;
1148 NameString[0] = toLowercase(NameString[0]);
1149 IdentifierInfo *II = &Ctx.Idents.get(NameString);
1150 return II->getTokenID() == tok::identifier;
1151}
1152
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001153bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001154 ObjCContainerDecl *D,
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001155 ObjCMethodDecl *Method) {
1156 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
1157 Method->param_size() != 0)
1158 return false;
1159 // Is this method candidate to be a getter?
Alp Toker314cc812014-01-25 16:55:45 +00001160 QualType GRT = Method->getReturnType();
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001161 if (GRT->isVoidType())
1162 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001163
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001164 Selector GetterSelector = Method->getSelector();
Fariborz Jahanian7391a7b5a2013-09-25 00:17:07 +00001165 ObjCInstanceTypeFamily OIT_Family =
1166 Selector::getInstTypeMethodFamily(GetterSelector);
Fangrui Song6907ce22018-07-30 19:24:48 +00001167
Fariborz Jahanian7391a7b5a2013-09-25 00:17:07 +00001168 if (OIT_Family != OIT_None)
1169 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001170
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001171 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
1172 Selector SetterSelector =
1173 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1174 PP.getSelectorTable(),
1175 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001176 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanianca399602013-09-11 17:05:15 +00001177 unsigned LengthOfPrefix = 0;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001178 if (!SetterMethod) {
1179 // try a different naming convention for getter: isXxxxx
1180 StringRef getterNameString = getterName->getName();
Fariborz Jahanianca399602013-09-11 17:05:15 +00001181 bool IsPrefix = getterNameString.startswith("is");
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +00001182 // Note that we don't want to change an isXXX method of retainable object
1183 // type to property (readonly or otherwise).
1184 if (IsPrefix && GRT->isObjCRetainableType())
1185 return false;
1186 if (IsPrefix || getterNameString.startswith("get")) {
Fariborz Jahanianca399602013-09-11 17:05:15 +00001187 LengthOfPrefix = (IsPrefix ? 2 : 3);
1188 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
1189 // Make sure that first character after "is" or "get" prefix can
1190 // start an identifier.
Fariborz Jahanian5d783df2013-09-27 22:55:54 +00001191 if (!IsValidIdentifier(Ctx, CGetterName))
Fariborz Jahanianca399602013-09-11 17:05:15 +00001192 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001193 if (CGetterName[0] && isUppercase(CGetterName[0])) {
1194 getterName = &Ctx.Idents.get(CGetterName);
1195 SetterSelector =
1196 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1197 PP.getSelectorTable(),
1198 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001199 SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001200 }
1201 }
1202 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001203
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001204 if (SetterMethod) {
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001205 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
1206 return false;
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001207 bool AvailabilityArgsMatch;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001208 if (SetterMethod->isDeprecated() ||
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001209 !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch))
Fariborz Jahanianf6c65052013-09-17 22:41:25 +00001210 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001211
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001212 // Is this a valid setter, matching the target getter?
Alp Toker314cc812014-01-25 16:55:45 +00001213 QualType SRT = SetterMethod->getReturnType();
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001214 if (!SRT->isVoidType())
1215 return false;
1216 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
1217 QualType ArgType = argDecl->getType();
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001218 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001219 return false;
1220 edit::Commit commit(*Editor);
1221 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001222 LengthOfPrefix,
1223 (ASTMigrateActions &
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001224 FrontendOptions::ObjCMT_AtomicProperty) != 0,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001225 (ASTMigrateActions &
1226 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001227 AvailabilityArgsMatch);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001228 Editor->commit(commit);
1229 return true;
1230 }
Fariborz Jahanian182486c2013-10-02 17:08:12 +00001231 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001232 // Try a non-void method with no argument (and no setter or property of same name
1233 // as a 'readonly' property.
1234 edit::Commit commit(*Editor);
Craig Topper8ae12032014-05-07 06:21:57 +00001235 rewriteToObjCProperty(Method, nullptr /*SetterMethod*/, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001236 LengthOfPrefix,
1237 (ASTMigrateActions &
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001238 FrontendOptions::ObjCMT_AtomicProperty) != 0,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001239 (ASTMigrateActions &
1240 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001241 /*AvailabilityArgsMatch*/false);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001242 Editor->commit(commit);
1243 return true;
1244 }
1245 return false;
1246}
1247
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001248void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
1249 ObjCMethodDecl *OM) {
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001250 if (OM->isImplicit() ||
Fariborz Jahanian7c1a4452013-09-26 22:43:41 +00001251 !OM->isInstanceMethod() ||
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001252 OM->hasAttr<ObjCReturnsInnerPointerAttr>())
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001253 return;
Alp Toker314cc812014-01-25 16:55:45 +00001254
1255 QualType RT = OM->getReturnType();
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001256 if (!TypeIsInnerPointer(RT) ||
Richard Smith20e883e2015-04-29 23:20:19 +00001257 !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001258 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001259
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001260 edit::Commit commit(*Editor);
1261 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
1262 Editor->commit(commit);
1263}
1264
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001265void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
1266 ObjCPropertyDecl *P) {
1267 QualType T = P->getType();
Richard Smith20e883e2015-04-29 23:20:19 +00001268
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001269 if (!TypeIsInnerPointer(T) ||
Richard Smith20e883e2015-04-29 23:20:19 +00001270 !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001271 return;
1272 edit::Commit commit(*Editor);
1273 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
1274 Editor->commit(commit);
1275}
1276
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001277void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
Fariborz Jahanian71221352013-07-23 22:42:28 +00001278 ObjCContainerDecl *CDecl) {
Fariborz Jahanian48a44d42013-11-19 18:17:31 +00001279 if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl))
Fariborz Jahaniane47a14a2013-09-18 15:43:52 +00001280 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001281
Fariborz Jahanian71221352013-07-23 22:42:28 +00001282 // migrate methods which can have instancetype as their result type.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001283 for (auto *Method : CDecl->methods()) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001284 if (Method->isDeprecated())
1285 continue;
Fariborz Jahanian71221352013-07-23 22:42:28 +00001286 migrateMethodInstanceType(Ctx, CDecl, Method);
1287 }
1288}
1289
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001290void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
1291 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001292 ObjCMethodDecl *OM,
1293 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +00001294 if (OM->isInstanceMethod() ||
Alp Toker314cc812014-01-25 16:55:45 +00001295 OM->getReturnType() == Ctx.getObjCInstanceType() ||
1296 !OM->getReturnType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001297 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001298
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001299 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1300 // NSYYYNamE with matching names be at least 3 characters long.
1301 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1302 if (!IDecl) {
1303 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1304 IDecl = CatDecl->getClassInterface();
1305 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1306 IDecl = ImpDecl->getClassInterface();
1307 }
1308 if (!IDecl)
1309 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001310
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001311 std::string StringClassName = IDecl->getName();
1312 StringRef LoweredClassName(StringClassName);
1313 std::string StringLoweredClassName = LoweredClassName.lower();
1314 LoweredClassName = StringLoweredClassName;
Fangrui Song6907ce22018-07-30 19:24:48 +00001315
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001316 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001317 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1318 if (!MethodIdName)
1319 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001320
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001321 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001322 if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001323 StringRef STRefMethodName(MethodName);
1324 size_t len = 0;
1325 if (STRefMethodName.startswith("standard"))
1326 len = strlen("standard");
1327 else if (STRefMethodName.startswith("shared"))
1328 len = strlen("shared");
1329 else if (STRefMethodName.startswith("default"))
1330 len = strlen("default");
1331 else
1332 return;
1333 MethodName = STRefMethodName.substr(len);
1334 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001335 std::string MethodNameSubStr = MethodName.substr(0, 3);
1336 StringRef MethodNamePrefix(MethodNameSubStr);
1337 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1338 MethodNamePrefix = StringLoweredMethodNamePrefix;
1339 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1340 if (Ix == StringRef::npos)
1341 return;
1342 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1343 StringRef LoweredMethodName(MethodName);
1344 std::string StringLoweredMethodName = LoweredMethodName.lower();
1345 LoweredMethodName = StringLoweredMethodName;
1346 if (!LoweredMethodName.startswith(ClassNamePostfix))
1347 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001348 if (OIT_Family == OIT_ReturnsSelf)
1349 ReplaceWithClasstype(*this, OM);
1350 else
Argyrios Kyrtzidisc02a0db2014-05-21 00:24:20 +00001351 ReplaceWithInstancetype(Ctx, *this, OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001352}
1353
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001354static bool IsVoidStarType(QualType Ty) {
1355 if (!Ty->isPointerType())
1356 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00001357
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001358 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1359 Ty = TD->getDecl()->getUnderlyingType();
Fangrui Song6907ce22018-07-30 19:24:48 +00001360
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001361 // Is the type void*?
1362 const PointerType* PT = Ty->getAs<PointerType>();
1363 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1364 return true;
1365 return IsVoidStarType(PT->getPointeeType());
1366}
1367
Fariborz Jahanian94279392013-08-20 18:54:39 +00001368/// AuditedType - This routine audits the type AT and returns false if it is one of known
1369/// CF object types or of the "void *" variety. It returns true if we don't care about the type
1370/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001371static bool AuditedType (QualType AT) {
1372 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001373 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001374 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +00001375 if (ento::coreFoundation::isCFObjectRef(AT) ||
1376 IsVoidStarType(AT) ||
1377 // If an ObjC object is type, assuming that it is not a CF function and
1378 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +00001379 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001380 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +00001381 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001382 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001383}
1384
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001385void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001386 if (CFFunctionIBCandidates.empty())
1387 return;
Richard Smith20e883e2015-04-29 23:20:19 +00001388 if (!NSAPIObj->isMacroDefined("CF_IMPLICIT_BRIDGING_ENABLED")) {
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001389 CFFunctionIBCandidates.clear();
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001390 FileId = FileID();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001391 return;
1392 }
1393 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001394 const Decl *FirstFD = CFFunctionIBCandidates[0];
1395 const Decl *LastFD =
1396 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001397 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1398 edit::Commit commit(*Editor);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001399 commit.insertBefore(FirstFD->getBeginLoc(), PragmaString);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001400 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1401 SourceLocation EndLoc = LastFD->getLocEnd();
1402 // get location just past end of function location.
1403 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001404 if (isa<FunctionDecl>(LastFD)) {
1405 // For Methods, EndLoc points to the ending semcolon. So,
1406 // not of these extra work is needed.
1407 Token Tok;
1408 // get locaiton of token that comes after end of function.
1409 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1410 if (!Failed)
1411 EndLoc = Tok.getLocation();
1412 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001413 commit.insertAfterToken(EndLoc, PragmaString);
1414 Editor->commit(commit);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001415 FileId = FileID();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001416 CFFunctionIBCandidates.clear();
1417}
1418
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001419void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001420 if (Decl->isDeprecated())
1421 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001422
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001423 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001424 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001425 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001426 "provided CF_IMPLICIT_BRIDGING_ENABLE");
1427 return;
1428 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001429
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001430 // Finction must be annotated first.
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001431 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1432 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1433 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001434 CFFunctionIBCandidates.push_back(Decl);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001435 if (FileId.isInvalid())
1436 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001437 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001438 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1439 if (!CFFunctionIBCandidates.empty()) {
1440 CFFunctionIBCandidates.push_back(Decl);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001441 if (FileId.isInvalid())
1442 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001443 }
1444 }
1445 else
1446 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001447 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001448 else {
1449 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001450 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001451 }
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001452}
1453
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001454void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1455 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001456 const FunctionDecl *FuncDecl,
1457 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001458 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001459 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001460 RetEffect Ret = CE.getReturnValue();
Craig Topper8ae12032014-05-07 06:21:57 +00001461 const char *AnnotationString = nullptr;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001462 if (Ret.getObjKind() == RetEffect::CF) {
Richard Smith20e883e2015-04-29 23:20:19 +00001463 if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001464 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001465 else if (Ret.notOwned() &&
Richard Smith20e883e2015-04-29 23:20:19 +00001466 NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001467 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1468 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001469 else if (Ret.getObjKind() == RetEffect::ObjC) {
Richard Smith20e883e2015-04-29 23:20:19 +00001470 if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001471 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001472 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001473
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001474 if (AnnotationString) {
1475 edit::Commit commit(*Editor);
1476 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1477 Editor->commit(commit);
1478 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001479 }
Craig Topper00bbdcf2014-06-28 23:22:23 +00001480 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001481 unsigned i = 0;
1482 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1483 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +00001484 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001485 ArgEffect AE = AEArgs[i];
Aaron Ballman9ead1242013-12-19 02:39:40 +00001486 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
Richard Smith20e883e2015-04-29 23:20:19 +00001487 NSAPIObj->isMacroDefined("CF_CONSUMED")) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001488 edit::Commit commit(*Editor);
1489 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1490 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +00001491 }
Aaron Ballman9ead1242013-12-19 02:39:40 +00001492 else if (AE == DecRefMsg && !pd->hasAttr<NSConsumedAttr>() &&
Richard Smith20e883e2015-04-29 23:20:19 +00001493 NSAPIObj->isMacroDefined("NS_CONSUMED")) {
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001494 edit::Commit commit(*Editor);
1495 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1496 Editor->commit(commit);
1497 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001498 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001499}
1500
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001501ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1502 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1503 ASTContext &Ctx,
1504 const FunctionDecl *FuncDecl) {
1505 if (FuncDecl->hasBody())
1506 return CF_BRIDGING_NONE;
Fangrui Song6907ce22018-07-30 19:24:48 +00001507
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001508 CallEffects CE = CallEffects::getEffect(FuncDecl);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001509 bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() ||
1510 FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1511 FuncDecl->hasAttr<NSReturnsRetainedAttr>() ||
1512 FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1513 FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>());
Fangrui Song6907ce22018-07-30 19:24:48 +00001514
Eric Christopherbe528662015-12-16 23:10:46 +00001515 // Trivial case of when function is annotated and has no argument.
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001516 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1517 return CF_BRIDGING_NONE;
Fangrui Song6907ce22018-07-30 19:24:48 +00001518
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001519 bool ReturnCFAudited = false;
1520 if (!FuncIsReturnAnnotated) {
1521 RetEffect Ret = CE.getReturnValue();
1522 if (Ret.getObjKind() == RetEffect::CF &&
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001523 (Ret.isOwned() || Ret.notOwned()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001524 ReturnCFAudited = true;
Alp Toker314cc812014-01-25 16:55:45 +00001525 else if (!AuditedType(FuncDecl->getReturnType()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001526 return CF_BRIDGING_NONE;
1527 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001528
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001529 // At this point result type is audited for potential inclusion.
1530 // Now, how about argument types.
Craig Topper00bbdcf2014-06-28 23:22:23 +00001531 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001532 unsigned i = 0;
1533 bool ArgCFAudited = false;
1534 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1535 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1536 const ParmVarDecl *pd = *pi;
1537 ArgEffect AE = AEArgs[i];
1538 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
Aaron Ballman9ead1242013-12-19 02:39:40 +00001539 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>())
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001540 ArgCFAudited = true;
1541 else if (AE == IncRef)
1542 ArgCFAudited = true;
1543 }
1544 else {
1545 QualType AT = pd->getType();
1546 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001547 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001548 return CF_BRIDGING_NONE;
1549 }
1550 }
1551 }
1552 if (ReturnCFAudited || ArgCFAudited)
1553 return CF_BRIDGING_ENABLE;
Fangrui Song6907ce22018-07-30 19:24:48 +00001554
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001555 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001556}
1557
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001558void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1559 ObjCContainerDecl *CDecl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001560 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001561 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001562
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001563 // migrate methods which can have instancetype as their result type.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001564 for (const auto *Method : CDecl->methods())
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001565 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001566}
1567
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001568void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1569 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001570 const ObjCMethodDecl *MethodDecl,
1571 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001572 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001573 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001574 RetEffect Ret = CE.getReturnValue();
Craig Topper8ae12032014-05-07 06:21:57 +00001575 const char *AnnotationString = nullptr;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001576 if (Ret.getObjKind() == RetEffect::CF) {
Richard Smith20e883e2015-04-29 23:20:19 +00001577 if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001578 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001579 else if (Ret.notOwned() &&
Richard Smith20e883e2015-04-29 23:20:19 +00001580 NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001581 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1582 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001583 else if (Ret.getObjKind() == RetEffect::ObjC) {
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001584 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1585 switch (OMF) {
1586 case clang::OMF_alloc:
1587 case clang::OMF_new:
1588 case clang::OMF_copy:
1589 case clang::OMF_init:
1590 case clang::OMF_mutableCopy:
1591 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001592
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001593 default:
Richard Smith20e883e2015-04-29 23:20:19 +00001594 if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001595 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001596 break;
1597 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001598 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001599
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001600 if (AnnotationString) {
1601 edit::Commit commit(*Editor);
1602 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1603 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001604 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001605 }
Craig Topper00bbdcf2014-06-28 23:22:23 +00001606 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001607 unsigned i = 0;
1608 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1609 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1610 const ParmVarDecl *pd = *pi;
1611 ArgEffect AE = AEArgs[i];
Aaron Ballman9ead1242013-12-19 02:39:40 +00001612 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
Richard Smith20e883e2015-04-29 23:20:19 +00001613 NSAPIObj->isMacroDefined("CF_CONSUMED")) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001614 edit::Commit commit(*Editor);
1615 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1616 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001617 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001618 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001619}
1620
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001621void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001622 ASTContext &Ctx,
1623 const ObjCMethodDecl *MethodDecl) {
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001624 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001625 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001626
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001627 CallEffects CE = CallEffects::getEffect(MethodDecl);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001628 bool MethodIsReturnAnnotated = (MethodDecl->hasAttr<CFReturnsRetainedAttr>() ||
1629 MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1630 MethodDecl->hasAttr<NSReturnsRetainedAttr>() ||
1631 MethodDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1632 MethodDecl->hasAttr<NSReturnsAutoreleasedAttr>());
Richard Smith20e883e2015-04-29 23:20:19 +00001633
1634 if (CE.getReceiver() == DecRefMsg &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00001635 !MethodDecl->hasAttr<NSConsumesSelfAttr>() &&
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001636 MethodDecl->getMethodFamily() != OMF_init &&
1637 MethodDecl->getMethodFamily() != OMF_release &&
Richard Smith20e883e2015-04-29 23:20:19 +00001638 NSAPIObj->isMacroDefined("NS_CONSUMES_SELF")) {
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001639 edit::Commit commit(*Editor);
1640 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1641 Editor->commit(commit);
1642 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001643
Eric Christopherbe528662015-12-16 23:10:46 +00001644 // Trivial case of when function is annotated and has no argument.
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001645 if (MethodIsReturnAnnotated &&
1646 (MethodDecl->param_begin() == MethodDecl->param_end()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001647 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001648
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001649 if (!MethodIsReturnAnnotated) {
1650 RetEffect Ret = CE.getReturnValue();
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001651 if ((Ret.getObjKind() == RetEffect::CF ||
1652 Ret.getObjKind() == RetEffect::ObjC) &&
1653 (Ret.isOwned() || Ret.notOwned())) {
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001654 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1655 return;
Alp Toker314cc812014-01-25 16:55:45 +00001656 } else if (!AuditedType(MethodDecl->getReturnType()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001657 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001658 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001659
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001660 // At this point result type is either annotated or audited.
1661 // Now, how about argument types.
Craig Topper00bbdcf2014-06-28 23:22:23 +00001662 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001663 unsigned i = 0;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001664 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1665 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1666 const ParmVarDecl *pd = *pi;
1667 ArgEffect AE = AEArgs[i];
Aaron Ballman9ead1242013-12-19 02:39:40 +00001668 if ((AE == DecRef && !pd->hasAttr<CFConsumedAttr>()) || AE == IncRef ||
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001669 !AuditedType(pd->getType())) {
1670 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1671 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001672 }
1673 }
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001674}
1675
Ted Kremenekf7639e12012-03-06 20:06:33 +00001676namespace {
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001677class SuperInitChecker : public RecursiveASTVisitor<SuperInitChecker> {
1678public:
1679 bool shouldVisitTemplateInstantiations() const { return false; }
1680 bool shouldWalkTypesOfTypeLocs() const { return false; }
1681
1682 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
1683 if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
1684 if (E->getMethodFamily() == OMF_init)
1685 return false;
1686 }
1687 return true;
1688 }
1689};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001690} // end anonymous namespace
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001691
1692static bool hasSuperInitCall(const ObjCMethodDecl *MD) {
1693 return !SuperInitChecker().TraverseStmt(MD->getBody());
1694}
1695
1696void ObjCMigrateASTConsumer::inferDesignatedInitializers(
1697 ASTContext &Ctx,
1698 const ObjCImplementationDecl *ImplD) {
1699
1700 const ObjCInterfaceDecl *IFace = ImplD->getClassInterface();
1701 if (!IFace || IFace->hasDesignatedInitializers())
1702 return;
Richard Smith20e883e2015-04-29 23:20:19 +00001703 if (!NSAPIObj->isMacroDefined("NS_DESIGNATED_INITIALIZER"))
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001704 return;
1705
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001706 for (const auto *MD : ImplD->instance_methods()) {
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001707 if (MD->isDeprecated() ||
1708 MD->getMethodFamily() != OMF_init ||
1709 MD->isDesignatedInitializerForTheInterface())
1710 continue;
1711 const ObjCMethodDecl *IFaceM = IFace->getMethod(MD->getSelector(),
1712 /*isInstance=*/true);
1713 if (!IFaceM)
1714 continue;
1715 if (hasSuperInitCall(MD)) {
1716 edit::Commit commit(*Editor);
1717 commit.insert(IFaceM->getLocEnd(), " NS_DESIGNATED_INITIALIZER");
1718 Editor->commit(commit);
1719 }
1720 }
1721}
1722
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +00001723bool ObjCMigrateASTConsumer::InsertFoundation(ASTContext &Ctx,
1724 SourceLocation Loc) {
1725 if (FoundationIncluded)
1726 return true;
1727 if (Loc.isInvalid())
1728 return false;
Argyrios Kyrtzidise59b7702016-07-15 18:11:27 +00001729 auto *nsEnumId = &Ctx.Idents.get("NS_ENUM");
1730 if (PP.getMacroDefinitionAtLoc(nsEnumId, Loc)) {
1731 FoundationIncluded = true;
1732 return true;
1733 }
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +00001734 edit::Commit commit(*Editor);
1735 if (Ctx.getLangOpts().Modules)
Fariborz Jahaniand2241bf2014-10-09 22:04:27 +00001736 commit.insert(Loc, "#ifndef NS_ENUM\n@import Foundation;\n#endif\n");
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +00001737 else
Fariborz Jahaniand2241bf2014-10-09 22:04:27 +00001738 commit.insert(Loc, "#ifndef NS_ENUM\n#import <Foundation/Foundation.h>\n#endif\n");
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +00001739 Editor->commit(commit);
1740 FoundationIncluded = true;
1741 return true;
1742}
1743
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001744namespace {
Ted Kremenekf7639e12012-03-06 20:06:33 +00001745
1746class RewritesReceiver : public edit::EditsReceiver {
1747 Rewriter &Rewrite;
1748
1749public:
1750 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1751
Craig Topperb45acb82014-03-14 06:02:07 +00001752 void insert(SourceLocation loc, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +00001753 Rewrite.InsertText(loc, text);
1754 }
Craig Topperb45acb82014-03-14 06:02:07 +00001755 void replace(CharSourceRange range, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +00001756 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1757 }
1758};
1759
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001760class JSONEditWriter : public edit::EditsReceiver {
1761 SourceManager &SourceMgr;
1762 llvm::raw_ostream &OS;
1763
1764public:
1765 JSONEditWriter(SourceManager &SM, llvm::raw_ostream &OS)
1766 : SourceMgr(SM), OS(OS) {
1767 OS << "[\n";
1768 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001769 ~JSONEditWriter() override { OS << "]\n"; }
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001770
1771private:
1772 struct EntryWriter {
1773 SourceManager &SourceMgr;
1774 llvm::raw_ostream &OS;
1775
1776 EntryWriter(SourceManager &SM, llvm::raw_ostream &OS)
1777 : SourceMgr(SM), OS(OS) {
1778 OS << " {\n";
1779 }
1780 ~EntryWriter() {
1781 OS << " },\n";
1782 }
1783
1784 void writeLoc(SourceLocation Loc) {
1785 FileID FID;
1786 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001787 std::tie(FID, Offset) = SourceMgr.getDecomposedLoc(Loc);
Yaron Keren8b563662015-10-03 10:46:20 +00001788 assert(FID.isValid());
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001789 SmallString<200> Path =
1790 StringRef(SourceMgr.getFileEntryForID(FID)->getName());
1791 llvm::sys::fs::make_absolute(Path);
1792 OS << " \"file\": \"";
1793 OS.write_escaped(Path.str()) << "\",\n";
1794 OS << " \"offset\": " << Offset << ",\n";
1795 }
1796
1797 void writeRemove(CharSourceRange Range) {
1798 assert(Range.isCharRange());
1799 std::pair<FileID, unsigned> Begin =
1800 SourceMgr.getDecomposedLoc(Range.getBegin());
1801 std::pair<FileID, unsigned> End =
1802 SourceMgr.getDecomposedLoc(Range.getEnd());
1803 assert(Begin.first == End.first);
1804 assert(Begin.second <= End.second);
1805 unsigned Length = End.second - Begin.second;
1806
1807 OS << " \"remove\": " << Length << ",\n";
1808 }
1809
1810 void writeText(StringRef Text) {
1811 OS << " \"text\": \"";
1812 OS.write_escaped(Text) << "\",\n";
1813 }
1814 };
Fangrui Song6907ce22018-07-30 19:24:48 +00001815
Craig Topperb45acb82014-03-14 06:02:07 +00001816 void insert(SourceLocation Loc, StringRef Text) override {
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001817 EntryWriter Writer(SourceMgr, OS);
1818 Writer.writeLoc(Loc);
1819 Writer.writeText(Text);
1820 }
1821
Craig Topperb45acb82014-03-14 06:02:07 +00001822 void replace(CharSourceRange Range, StringRef Text) override {
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001823 EntryWriter Writer(SourceMgr, OS);
1824 Writer.writeLoc(Range.getBegin());
1825 Writer.writeRemove(Range);
1826 Writer.writeText(Text);
1827 }
1828
Craig Topperb45acb82014-03-14 06:02:07 +00001829 void remove(CharSourceRange Range) override {
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001830 EntryWriter Writer(SourceMgr, OS);
1831 Writer.writeLoc(Range.getBegin());
1832 Writer.writeRemove(Range);
1833 }
1834};
1835
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00001836} // end anonymous namespace
Ted Kremenekf7639e12012-03-06 20:06:33 +00001837
1838void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001839
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001840 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001841 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001842 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1843 D != DEnd; ++D) {
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001844 FileID FID = PP.getSourceManager().getFileID((*D)->getLocation());
Yaron Keren8b563662015-10-03 10:46:20 +00001845 if (FID.isValid())
1846 if (FileId.isValid() && FileId != FID) {
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001847 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1848 AnnotateImplicitBridging(Ctx);
1849 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001850
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001851 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001852 if (canModify(CDecl))
Fariborz Jahaniane1b98432015-04-02 21:36:03 +00001853 migrateObjCContainerDecl(Ctx, CDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001854 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001855 if (canModify(CatDecl))
Fariborz Jahaniane1b98432015-04-02 21:36:03 +00001856 migrateObjCContainerDecl(Ctx, CatDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001857 }
Fariborz Jahaniane1b98432015-04-02 21:36:03 +00001858 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D)) {
Fariborz Jahanian769c04e2013-12-17 01:01:33 +00001859 ObjCProtocolDecls.insert(PDecl->getCanonicalDecl());
Fariborz Jahaniane1b98432015-04-02 21:36:03 +00001860 if (canModify(PDecl))
1861 migrateObjCContainerDecl(Ctx, PDecl);
1862 }
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001863 else if (const ObjCImplementationDecl *ImpDecl =
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001864 dyn_cast<ObjCImplementationDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001865 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) &&
1866 canModify(ImpDecl))
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001867 migrateProtocolConformance(Ctx, ImpDecl);
1868 }
Fariborz Jahanian92463272013-07-18 20:11:45 +00001869 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001870 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1871 continue;
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001872 if (!canModify(ED))
1873 continue;
Fariborz Jahanian92463272013-07-18 20:11:45 +00001874 DeclContext::decl_iterator N = D;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001875 if (++N != DEnd) {
1876 const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
1877 if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
1878 D++;
1879 }
1880 else
Craig Topper8ae12032014-05-07 06:21:57 +00001881 migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */nullptr);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001882 }
1883 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001884 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1885 continue;
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001886 if (!canModify(TD))
1887 continue;
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001888 DeclContext::decl_iterator N = D;
1889 if (++N == DEnd)
1890 continue;
1891 if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
Argyrios Kyrtzidis88737a52016-07-15 19:22:34 +00001892 if (canModify(ED)) {
1893 if (++N != DEnd)
1894 if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) {
1895 // prefer typedef-follows-enum to enum-follows-typedef pattern.
1896 if (migrateNSEnumDecl(Ctx, ED, TDF)) {
1897 ++D; ++D;
1898 CacheObjCNSIntegerTypedefed(TD);
1899 continue;
1900 }
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001901 }
Argyrios Kyrtzidis88737a52016-07-15 19:22:34 +00001902 if (migrateNSEnumDecl(Ctx, ED, TD)) {
1903 ++D;
1904 continue;
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001905 }
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001906 }
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001907 }
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001908 CacheObjCNSIntegerTypedefed(TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001909 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001910 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001911 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1912 canModify(FD))
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001913 migrateCFAnnotation(Ctx, FD);
1914 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001915
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001916 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001917 bool CanModify = canModify(CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001918 // migrate methods which can have instancetype as their result type.
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001919 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) &&
1920 CanModify)
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001921 migrateAllMethodInstaceType(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001922 // annotate methods with CF annotations.
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001923 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1924 CanModify)
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001925 migrateARCSafeAnnotation(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001926 }
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001927
1928 if (const ObjCImplementationDecl *
1929 ImplD = dyn_cast<ObjCImplementationDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001930 if ((ASTMigrateActions & FrontendOptions::ObjCMT_DesignatedInitializer) &&
1931 canModify(ImplD))
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001932 inferDesignatedInitializers(Ctx, ImplD);
1933 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001934 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001935 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1936 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001937 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001938
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001939 if (IsOutputFile) {
Rafael Espindoladae941a2014-08-25 18:17:04 +00001940 std::error_code EC;
1941 llvm::raw_fd_ostream OS(MigrateDir, EC, llvm::sys::fs::F_None);
1942 if (EC) {
Alp Toker29cb66b2014-01-26 06:17:37 +00001943 DiagnosticsEngine &Diags = Ctx.getDiagnostics();
1944 Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
Rafael Espindoladae941a2014-08-25 18:17:04 +00001945 << EC.message();
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001946 return;
1947 }
1948
1949 JSONEditWriter Writer(Ctx.getSourceManager(), OS);
1950 Editor->applyRewrites(Writer);
1951 return;
1952 }
1953
David Blaikiebbafb8a2012-03-11 07:00:24 +00001954 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001955 RewritesReceiver Rec(rewriter);
1956 Editor->applyRewrites(Rec);
1957
1958 for (Rewriter::buffer_iterator
1959 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1960 FileID FID = I->first;
1961 RewriteBuffer &buf = I->second;
1962 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1963 assert(file);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001964 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001965 llvm::raw_svector_ostream vecOS(newText);
1966 buf.write(vecOS);
Rafael Espindola1a1b1562014-08-17 23:12:27 +00001967 std::unique_ptr<llvm::MemoryBuffer> memBuf(
1968 llvm::MemoryBuffer::getMemBufferCopy(
1969 StringRef(newText.data(), newText.size()), file->getName()));
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001970 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001971 FileMgr.FixupRelativePath(filePath);
Rafael Espindola1a1b1562014-08-17 23:12:27 +00001972 Remapper.remap(filePath.str(), std::move(memBuf));
Ted Kremenekf7639e12012-03-06 20:06:33 +00001973 }
1974
1975 if (IsOutputFile) {
1976 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1977 } else {
1978 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1979 }
1980}
1981
1982bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001983 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001984 return true;
1985}
1986
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00001987static std::vector<std::string> getWhiteListFilenames(StringRef DirPath) {
1988 using namespace llvm::sys::fs;
1989 using namespace llvm::sys::path;
1990
1991 std::vector<std::string> Filenames;
1992 if (DirPath.empty() || !is_directory(DirPath))
1993 return Filenames;
Rafael Espindolac0809172014-06-12 14:02:15 +00001994
1995 std::error_code EC;
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00001996 directory_iterator DI = directory_iterator(DirPath, EC);
1997 directory_iterator DE;
1998 for (; !EC && DI != DE; DI = DI.increment(EC)) {
1999 if (is_regular_file(DI->path()))
2000 Filenames.push_back(filename(DI->path()));
2001 }
2002
2003 return Filenames;
2004}
2005
David Blaikie6beb6aa2014-08-10 19:56:51 +00002006std::unique_ptr<ASTConsumer>
2007MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00002008 PPConditionalDirectiveRecord *
2009 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
Argyrios Kyrtzidisee02a8a2013-11-13 23:38:22 +00002010 unsigned ObjCMTAction = CI.getFrontendOpts().ObjCMTAction;
Argyrios Kyrtzidisc47c63b2013-11-14 16:33:20 +00002011 unsigned ObjCMTOpts = ObjCMTAction;
2012 // These are companion flags, they do not enable transformations.
2013 ObjCMTOpts &= ~(FrontendOptions::ObjCMT_AtomicProperty |
2014 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty);
2015 if (ObjCMTOpts == FrontendOptions::ObjCMT_None) {
Argyrios Kyrtzidisee02a8a2013-11-13 23:38:22 +00002016 // If no specific option was given, enable literals+subscripting transforms
2017 // by default.
Argyrios Kyrtzidisc47c63b2013-11-14 16:33:20 +00002018 ObjCMTAction |= FrontendOptions::ObjCMT_Literals |
2019 FrontendOptions::ObjCMT_Subscripting;
Argyrios Kyrtzidisee02a8a2013-11-13 23:38:22 +00002020 }
Craig Topperb8a70532014-09-10 04:53:53 +00002021 CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00002022 std::vector<std::string> WhiteList =
2023 getWhiteListFilenames(CI.getFrontendOpts().ObjCMTWhiteListPath);
David Blaikie6beb6aa2014-08-10 19:56:51 +00002024 return llvm::make_unique<ObjCMigrateASTConsumer>(
2025 CI.getFrontendOpts().OutputFile, ObjCMTAction, Remapper,
2026 CI.getFileManager(), PPRec, CI.getPreprocessor(),
2027 /*isOutputFile=*/true, WhiteList);
Ted Kremenekf7639e12012-03-06 20:06:33 +00002028}
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002029
2030namespace {
2031struct EditEntry {
2032 const FileEntry *File;
2033 unsigned Offset;
2034 unsigned RemoveLen;
2035 std::string Text;
2036
2037 EditEntry() : File(), Offset(), RemoveLen() {}
2038};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002039} // end anonymous namespace
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002040
2041namespace llvm {
2042template<> struct DenseMapInfo<EditEntry> {
2043 static inline EditEntry getEmptyKey() {
2044 EditEntry Entry;
2045 Entry.Offset = unsigned(-1);
2046 return Entry;
2047 }
2048 static inline EditEntry getTombstoneKey() {
2049 EditEntry Entry;
2050 Entry.Offset = unsigned(-2);
2051 return Entry;
2052 }
2053 static unsigned getHashValue(const EditEntry& Val) {
2054 llvm::FoldingSetNodeID ID;
2055 ID.AddPointer(Val.File);
2056 ID.AddInteger(Val.Offset);
2057 ID.AddInteger(Val.RemoveLen);
2058 ID.AddString(Val.Text);
2059 return ID.ComputeHash();
2060 }
2061 static bool isEqual(const EditEntry &LHS, const EditEntry &RHS) {
2062 return LHS.File == RHS.File &&
2063 LHS.Offset == RHS.Offset &&
2064 LHS.RemoveLen == RHS.RemoveLen &&
2065 LHS.Text == RHS.Text;
2066 }
2067};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002068} // end namespace llvm
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002069
2070namespace {
2071class RemapFileParser {
2072 FileManager &FileMgr;
2073
2074public:
2075 RemapFileParser(FileManager &FileMgr) : FileMgr(FileMgr) { }
2076
2077 bool parse(StringRef File, SmallVectorImpl<EditEntry> &Entries) {
2078 using namespace llvm::yaml;
2079
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002080 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
2081 llvm::MemoryBuffer::getFile(File);
2082 if (!FileBufOrErr)
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002083 return true;
2084
2085 llvm::SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00002086 Stream YAMLStream(FileBufOrErr.get()->getMemBufferRef(), SM);
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002087 document_iterator I = YAMLStream.begin();
2088 if (I == YAMLStream.end())
2089 return true;
2090 Node *Root = I->getRoot();
2091 if (!Root)
2092 return true;
2093
2094 SequenceNode *SeqNode = dyn_cast<SequenceNode>(Root);
2095 if (!SeqNode)
2096 return true;
2097
2098 for (SequenceNode::iterator
2099 AI = SeqNode->begin(), AE = SeqNode->end(); AI != AE; ++AI) {
2100 MappingNode *MapNode = dyn_cast<MappingNode>(&*AI);
2101 if (!MapNode)
2102 continue;
2103 parseEdit(MapNode, Entries);
2104 }
2105
2106 return false;
2107 }
2108
2109private:
2110 void parseEdit(llvm::yaml::MappingNode *Node,
2111 SmallVectorImpl<EditEntry> &Entries) {
2112 using namespace llvm::yaml;
2113 EditEntry Entry;
2114 bool Ignore = false;
2115
2116 for (MappingNode::iterator
2117 KVI = Node->begin(), KVE = Node->end(); KVI != KVE; ++KVI) {
2118 ScalarNode *KeyString = dyn_cast<ScalarNode>((*KVI).getKey());
2119 if (!KeyString)
2120 continue;
2121 SmallString<10> KeyStorage;
2122 StringRef Key = KeyString->getValue(KeyStorage);
2123
2124 ScalarNode *ValueString = dyn_cast<ScalarNode>((*KVI).getValue());
2125 if (!ValueString)
2126 continue;
2127 SmallString<64> ValueStorage;
2128 StringRef Val = ValueString->getValue(ValueStorage);
2129
2130 if (Key == "file") {
2131 const FileEntry *FE = FileMgr.getFile(Val);
2132 if (!FE)
2133 Ignore = true;
2134 Entry.File = FE;
2135 } else if (Key == "offset") {
2136 if (Val.getAsInteger(10, Entry.Offset))
2137 Ignore = true;
2138 } else if (Key == "remove") {
2139 if (Val.getAsInteger(10, Entry.RemoveLen))
2140 Ignore = true;
2141 } else if (Key == "text") {
2142 Entry.Text = Val;
2143 }
2144 }
2145
2146 if (!Ignore)
2147 Entries.push_back(Entry);
2148 }
2149};
Eugene Zelenko0a4f3f42016-02-10 19:11:58 +00002150} // end anonymous namespace
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002151
2152static bool reportDiag(const Twine &Err, DiagnosticsEngine &Diag) {
Alp Toker29cb66b2014-01-26 06:17:37 +00002153 Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
2154 << Err.str();
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002155 return true;
2156}
2157
2158static std::string applyEditsToTemp(const FileEntry *FE,
2159 ArrayRef<EditEntry> Edits,
2160 FileManager &FileMgr,
2161 DiagnosticsEngine &Diag) {
2162 using namespace llvm::sys;
2163
2164 SourceManager SM(Diag, FileMgr);
2165 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
2166 LangOptions LangOpts;
2167 edit::EditedSource Editor(SM, LangOpts);
2168 for (ArrayRef<EditEntry>::iterator
2169 I = Edits.begin(), E = Edits.end(); I != E; ++I) {
2170 const EditEntry &Entry = *I;
2171 assert(Entry.File == FE);
2172 SourceLocation Loc =
2173 SM.getLocForStartOfFile(FID).getLocWithOffset(Entry.Offset);
2174 CharSourceRange Range;
2175 if (Entry.RemoveLen != 0) {
2176 Range = CharSourceRange::getCharRange(Loc,
2177 Loc.getLocWithOffset(Entry.RemoveLen));
2178 }
2179
2180 edit::Commit commit(Editor);
2181 if (Range.isInvalid()) {
2182 commit.insert(Loc, Entry.Text);
2183 } else if (Entry.Text.empty()) {
2184 commit.remove(Range);
2185 } else {
2186 commit.replace(Range, Entry.Text);
2187 }
2188 Editor.commit(commit);
2189 }
2190
2191 Rewriter rewriter(SM, LangOpts);
2192 RewritesReceiver Rec(rewriter);
Argyrios Kyrtzidis5312b662017-04-28 00:25:06 +00002193 Editor.applyRewrites(Rec, /*adjustRemovals=*/false);
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002194
2195 const RewriteBuffer *Buf = rewriter.getRewriteBufferFor(FID);
2196 SmallString<512> NewText;
2197 llvm::raw_svector_ostream OS(NewText);
2198 Buf->write(OS);
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002199
2200 SmallString<64> TempPath;
2201 int FD;
2202 if (fs::createTemporaryFile(path::filename(FE->getName()),
Argyrios Kyrtzidis203e9232015-09-09 16:48:47 +00002203 path::extension(FE->getName()).drop_front(), FD,
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002204 TempPath)) {
2205 reportDiag("Could not create file: " + TempPath.str(), Diag);
2206 return std::string();
2207 }
2208
2209 llvm::raw_fd_ostream TmpOut(FD, /*shouldClose=*/true);
2210 TmpOut.write(NewText.data(), NewText.size());
2211 TmpOut.close();
2212
2213 return TempPath.str();
2214}
2215
2216bool arcmt::getFileRemappingsFromFileList(
2217 std::vector<std::pair<std::string,std::string> > &remap,
2218 ArrayRef<StringRef> remapFiles,
2219 DiagnosticConsumer *DiagClient) {
2220 bool hasErrorOccurred = false;
2221
2222 FileSystemOptions FSOpts;
2223 FileManager FileMgr(FSOpts);
2224 RemapFileParser Parser(FileMgr);
2225
2226 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
2227 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
2228 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
2229 DiagClient, /*ShouldOwnClient=*/false));
2230
2231 typedef llvm::DenseMap<const FileEntry *, std::vector<EditEntry> >
2232 FileEditEntriesTy;
2233 FileEditEntriesTy FileEditEntries;
2234
2235 llvm::DenseSet<EditEntry> EntriesSet;
2236
2237 for (ArrayRef<StringRef>::iterator
2238 I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
2239 SmallVector<EditEntry, 16> Entries;
2240 if (Parser.parse(*I, Entries))
2241 continue;
2242
2243 for (SmallVectorImpl<EditEntry>::iterator
2244 EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) {
2245 EditEntry &Entry = *EI;
2246 if (!Entry.File)
2247 continue;
2248 std::pair<llvm::DenseSet<EditEntry>::iterator, bool>
2249 Insert = EntriesSet.insert(Entry);
2250 if (!Insert.second)
2251 continue;
2252
2253 FileEditEntries[Entry.File].push_back(Entry);
2254 }
2255 }
2256
2257 for (FileEditEntriesTy::iterator
2258 I = FileEditEntries.begin(), E = FileEditEntries.end(); I != E; ++I) {
2259 std::string TempFile = applyEditsToTemp(I->first, I->second,
2260 FileMgr, *Diags);
2261 if (TempFile.empty()) {
2262 hasErrorOccurred = true;
2263 continue;
2264 }
2265
Benjamin Kramer3204b152015-05-29 19:42:19 +00002266 remap.emplace_back(I->first->getName(), TempFile);
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002267 }
2268
2269 return hasErrorOccurred;
2270}