blob: d8d84194c5479a8f63515909fff85200434c306f [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"
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +000032#include "llvm/Support/Path.h"
Hans Wennborgbf6dda52013-12-12 02:24:20 +000033#include "llvm/Support/SourceMgr.h"
34#include "llvm/Support/YAMLParser.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000035
36using namespace clang;
37using namespace arcmt;
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000038using namespace ento::objc_retain;
Ted Kremenekf7639e12012-03-06 20:06:33 +000039
40namespace {
41
42class ObjCMigrateASTConsumer : public ASTConsumer {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000043 enum CF_BRIDGING_KIND {
44 CF_BRIDGING_NONE,
45 CF_BRIDGING_ENABLE,
46 CF_BRIDGING_MAY_INCLUDE
47 };
48
Ted Kremenekf7639e12012-03-06 20:06:33 +000049 void migrateDecl(Decl *D);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000050 void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCContainerDecl *D);
Fariborz Jahanian1be01532013-07-12 22:32:19 +000051 void migrateProtocolConformance(ASTContext &Ctx,
52 const ObjCImplementationDecl *ImpDecl);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +000053 void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +000054 bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
Fariborz Jahanian92463272013-07-18 20:11:45 +000055 const TypedefDecl *TypedefDcl);
Fariborz Jahanian8c45e282013-10-02 22:49:59 +000056 void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000057 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
58 ObjCMethodDecl *OM);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000059 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +000060 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
Fariborz Jahanian10b74352013-09-24 20:20:52 +000061 void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000062 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000063 ObjCMethodDecl *OM,
64 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000065
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000066 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000067 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000068 const FunctionDecl *FuncDecl, bool ResultAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000069 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000070 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000071
Fariborz Jahanian301b5212013-08-20 22:42:13 +000072 void AnnotateImplicitBridging(ASTContext &Ctx);
73
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000074 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
75 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000076
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000077 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
78
Fariborz Jahanian89f6d102013-09-04 00:10:06 +000079 void migrateAddMethodAnnotation(ASTContext &Ctx,
80 const ObjCMethodDecl *MethodDecl);
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +000081
82 void inferDesignatedInitializers(ASTContext &Ctx,
83 const ObjCImplementationDecl *ImplD);
84
Ted Kremenekf7639e12012-03-06 20:06:33 +000085public:
86 std::string MigrateDir;
Fariborz Jahanian182486c2013-10-02 17:08:12 +000087 unsigned ASTMigrateActions;
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +000088 FileID FileId;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +000089 const TypedefDecl *NSIntegerTypedefed;
90 const TypedefDecl *NSUIntegerTypedefed;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000091 OwningPtr<NSAPI> NSAPIObj;
92 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000093 FileRemapper &Remapper;
94 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000095 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000096 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000097 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000098 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000099 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000100 llvm::StringMap<char> WhiteListFilenames;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000101
Ted Kremenekf7639e12012-03-06 20:06:33 +0000102 ObjCMigrateASTConsumer(StringRef migrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000103 unsigned astMigrateActions,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000104 FileRemapper &remapper,
105 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000106 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000107 Preprocessor &PP,
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000108 bool isOutputFile,
109 ArrayRef<std::string> WhiteList)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000110 : MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000111 ASTMigrateActions(astMigrateActions),
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +0000112 NSIntegerTypedefed(0), NSUIntegerTypedefed(0),
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000113 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000114 IsOutputFile(isOutputFile) {
115
116 for (ArrayRef<std::string>::iterator
117 I = WhiteList.begin(), E = WhiteList.end(); I != E; ++I) {
118 WhiteListFilenames.GetOrCreateValue(*I);
119 }
120 }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000121
122protected:
123 virtual void Initialize(ASTContext &Context) {
124 NSAPIObj.reset(new NSAPI(Context));
125 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000126 Context.getLangOpts(),
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +0000127 PPRec, false));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000128 }
129
130 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
131 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
132 migrateDecl(*I);
133 return true;
134 }
135 virtual void HandleInterestingDecl(DeclGroupRef DG) {
136 // Ignore decls from the PCH.
137 }
138 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
139 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
140 }
141
142 virtual void HandleTranslationUnit(ASTContext &Ctx);
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000143
144 bool canModifyFile(StringRef Path) {
145 if (WhiteListFilenames.empty())
146 return true;
147 return WhiteListFilenames.find(llvm::sys::path::filename(Path))
148 != WhiteListFilenames.end();
149 }
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +0000150 bool canModifyFile(const FileEntry *FE) {
151 if (!FE)
152 return false;
153 return canModifyFile(FE->getName());
154 }
155 bool canModifyFile(FileID FID) {
156 if (FID.isInvalid())
157 return false;
158 return canModifyFile(PP.getSourceManager().getFileEntryForID(FID));
159 }
160
161 bool canModify(const Decl *D) {
162 if (!D)
163 return false;
164 if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(D))
165 return canModify(CatImpl->getCategoryDecl());
166 if (const ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D))
167 return canModify(Impl->getClassInterface());
168 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
169 return canModify(cast<Decl>(MD->getDeclContext()));
170
171 FileID FID = PP.getSourceManager().getFileID(D->getLocation());
172 return canModifyFile(FID);
173 }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000174};
175
176}
177
178ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000179 StringRef migrateDir,
180 unsigned migrateAction)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000181 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000182 ObjCMigAction(migrateAction),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000183 CompInst(0) {
184 if (MigrateDir.empty())
185 MigrateDir = "."; // user current directory if none is given.
186}
187
188ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
189 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000190 PPConditionalDirectiveRecord *
191 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
192 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000193 ASTConsumer *
194 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
195 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000196 ObjCMigAction,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000197 Remapper,
198 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000199 PPRec,
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000200 CompInst->getPreprocessor(),
201 false,
202 ArrayRef<std::string>());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000203 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
204 return new MultiplexConsumer(Consumers);
205}
206
207bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
208 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
209 /*ignoreIfFilesChanges=*/true);
210 CompInst = &CI;
211 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000212 return true;
213}
214
215namespace {
216class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
217 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000218 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000219
220public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000221 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
222 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000223
224 bool shouldVisitTemplateInstantiations() const { return false; }
225 bool shouldWalkTypesOfTypeLocs() const { return false; }
226
227 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000228 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000229 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000230 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000231 Consumer.Editor->commit(commit);
232 }
233
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000234 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000235 edit::Commit commit(*Consumer.Editor);
236 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
237 Consumer.Editor->commit(commit);
238 }
239
240 return true;
241 }
242
243 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
244 // Do depth first; we want to rewrite the subexpressions first so that if
245 // we have to move expressions we will move them already rewritten.
246 for (Stmt::child_range range = E->children(); range; ++range)
247 if (!TraverseStmt(*range))
248 return false;
249
250 return WalkUpFromObjCMessageExpr(E);
251 }
252};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000253
254class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
255 ObjCMigrateASTConsumer &Consumer;
256 OwningPtr<ParentMap> PMap;
257
258public:
259 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
260
261 bool shouldVisitTemplateInstantiations() const { return false; }
262 bool shouldWalkTypesOfTypeLocs() const { return false; }
263
264 bool TraverseStmt(Stmt *S) {
265 PMap.reset(new ParentMap(S));
266 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
267 return true;
268 }
269};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000270}
271
272void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
273 if (!D)
274 return;
275 if (isa<ObjCMethodDecl>(D))
276 return; // Wait for the ObjC container declaration.
277
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000278 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000279}
280
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000281static void append_attr(std::string &PropertyString, const char *attr,
282 bool &LParenAdded) {
283 if (!LParenAdded) {
284 PropertyString += "(";
285 LParenAdded = true;
286 }
287 else
288 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000289 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000290}
291
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000292static
293void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
294 const std::string& TypeString,
295 const char *name) {
296 const char *argPtr = TypeString.c_str();
297 int paren = 0;
298 while (*argPtr) {
299 switch (*argPtr) {
300 case '(':
301 PropertyString += *argPtr;
302 paren++;
303 break;
304 case ')':
305 PropertyString += *argPtr;
306 paren--;
307 break;
308 case '^':
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000309 case '*':
310 PropertyString += (*argPtr);
311 if (paren == 1) {
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000312 PropertyString += name;
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000313 name = "";
314 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000315 break;
316 default:
317 PropertyString += *argPtr;
318 break;
319 }
320 argPtr++;
321 }
322}
323
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000324static const char *PropertyMemoryAttribute(ASTContext &Context, QualType ArgType) {
325 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
326 bool RetainableObject = ArgType->isObjCRetainableType();
Fariborz Jahanian49e69ee2013-12-12 01:02:00 +0000327 if (RetainableObject &&
328 (propertyLifetime == Qualifiers::OCL_Strong
329 || propertyLifetime == Qualifiers::OCL_None)) {
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000330 if (const ObjCObjectPointerType *ObjPtrTy =
331 ArgType->getAs<ObjCObjectPointerType>()) {
332 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
333 if (IDecl &&
334 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
335 return "copy";
336 else
Fariborz Jahanian54c8eaa2013-11-21 00:58:17 +0000337 return "strong";
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000338 }
339 else if (ArgType->isBlockPointerType())
340 return "copy";
341 } else if (propertyLifetime == Qualifiers::OCL_Weak)
342 // TODO. More precise determination of 'weak' attribute requires
343 // looking into setter's implementation for backing weak ivar.
344 return "weak";
345 else if (RetainableObject)
Fariborz Jahanian54c8eaa2013-11-21 00:58:17 +0000346 return ArgType->isBlockPointerType() ? "copy" : "strong";
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000347 return 0;
348}
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000349
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000350static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000351 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000352 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000353 unsigned LengthOfPrefix,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +0000354 bool Atomic, bool UseNsIosOnlyMacro,
355 bool AvailabilityArgsMatch) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000356 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000357 bool LParenAdded = false;
358 std::string PropertyString = "@property ";
Fariborz Jahanian2e793d62013-11-13 00:08:36 +0000359 if (UseNsIosOnlyMacro && Context.Idents.get("NS_NONATOMIC_IOSONLY").hasMacroDefinition()) {
Fariborz Jahanianbed1be92013-11-12 19:25:50 +0000360 PropertyString += "(NS_NONATOMIC_IOSONLY";
361 LParenAdded = true;
362 } else if (!Atomic) {
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000363 PropertyString += "(nonatomic";
364 LParenAdded = true;
365 }
366
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000367 std::string PropertyNameString = Getter->getNameAsString();
368 StringRef PropertyName(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000369 if (LengthOfPrefix > 0) {
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000370 if (!LParenAdded) {
371 PropertyString += "(getter=";
372 LParenAdded = true;
373 }
374 else
375 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000376 PropertyString += PropertyNameString;
377 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000378 // Property with no setter may be suggested as a 'readonly' property.
Fariborz Jahaniand9aef7882013-11-21 17:49:34 +0000379 if (!Setter)
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000380 append_attr(PropertyString, "readonly", LParenAdded);
Fariborz Jahaniand9aef7882013-11-21 17:49:34 +0000381
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000382
Fariborz Jahanian33304e302013-10-16 18:52:17 +0000383 // Short circuit 'delegate' properties that contain the name "delegate" or
384 // "dataSource", or have exact name "target" to have 'assign' attribute.
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000385 if (PropertyName.equals("target") ||
386 (PropertyName.find("delegate") != StringRef::npos) ||
Fariborz Jahanian78bff052013-10-16 20:44:26 +0000387 (PropertyName.find("dataSource") != StringRef::npos)) {
Alp Toker314cc812014-01-25 16:55:45 +0000388 QualType QT = Getter->getReturnType();
Fariborz Jahanian78bff052013-10-16 20:44:26 +0000389 if (!QT->isRealType())
390 append_attr(PropertyString, "assign", LParenAdded);
Fariborz Jahaniand9aef7882013-11-21 17:49:34 +0000391 } else if (!Setter) {
Alp Toker314cc812014-01-25 16:55:45 +0000392 QualType ResType = Context.getCanonicalType(Getter->getReturnType());
Fariborz Jahaniand9aef7882013-11-21 17:49:34 +0000393 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ResType))
394 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
395 } else {
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000396 const ParmVarDecl *argDecl = *Setter->param_begin();
397 QualType ArgType = Context.getCanonicalType(argDecl->getType());
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000398 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ArgType))
399 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000400 }
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000401 if (LParenAdded)
402 PropertyString += ')';
Alp Toker314cc812014-01-25 16:55:45 +0000403 QualType RT = Getter->getReturnType();
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000404 if (!isa<TypedefType>(RT)) {
405 // strip off any ARC lifetime qualifier.
406 QualType CanResultTy = Context.getCanonicalType(RT);
407 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
408 Qualifiers Qs = CanResultTy.getQualifiers();
409 Qs.removeObjCLifetime();
410 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
411 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000412 }
413 PropertyString += " ";
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000414 PrintingPolicy SubPolicy(Context.getPrintingPolicy());
415 SubPolicy.SuppressStrongLifetime = true;
Fariborz Jahaniande557f82013-10-09 17:37:28 +0000416 SubPolicy.SuppressLifetimeQualifiers = true;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000417 std::string TypeString = RT.getAsString(SubPolicy);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000418 if (LengthOfPrefix > 0) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000419 // property name must strip off "is" and lower case the first character
420 // after that; e.g. isContinuous will become continuous.
421 StringRef PropertyNameStringRef(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000422 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000423 PropertyNameString = PropertyNameStringRef;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000424 bool NoLowering = (isUppercase(PropertyNameString[0]) &&
425 PropertyNameString.size() > 1 &&
426 isUppercase(PropertyNameString[1]));
Fariborz Jahanian34fea362013-09-11 18:27:16 +0000427 if (!NoLowering)
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000428 PropertyNameString[0] = toLowercase(PropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000429 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000430 if (RT->isBlockPointerType() || RT->isFunctionPointerType())
431 MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
432 TypeString,
433 PropertyNameString.c_str());
434 else {
435 char LastChar = TypeString[TypeString.size()-1];
436 PropertyString += TypeString;
437 if (LastChar != '*')
438 PropertyString += ' ';
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000439 PropertyString += PropertyNameString;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000440 }
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000441 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
442 Selector GetterSelector = Getter->getSelector();
443
444 SourceLocation EndGetterSelectorLoc =
445 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000446 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000447 EndGetterSelectorLoc),
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000448 PropertyString);
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000449 if (Setter && AvailabilityArgsMatch) {
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000450 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
451 // Get location past ';'
452 EndLoc = EndLoc.getLocWithOffset(1);
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000453 SourceLocation BeginOfSetterDclLoc = Setter->getLocStart();
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000454 // FIXME. This assumes that setter decl; is immediately preceded by eoln.
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000455 // It is trying to remove the setter method decl. line entirely.
456 BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
457 commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000458 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000459}
460
Fariborz Jahanian48a44d42013-11-19 18:17:31 +0000461static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) {
462 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) {
463 StringRef Name = CatDecl->getName();
464 return Name.endswith("Deprecated");
465 }
466 return false;
467}
468
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000469void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000470 ObjCContainerDecl *D) {
Fariborz Jahanian48a44d42013-11-19 18:17:31 +0000471 if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D))
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000472 return;
Fariborz Jahanian48a44d42013-11-19 18:17:31 +0000473
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000474 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
475 M != MEnd; ++M) {
476 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000477 if (Method->isDeprecated())
478 continue;
Fariborz Jahanianec7cea92013-11-08 01:15:17 +0000479 bool PropertyInferred = migrateProperty(Ctx, D, Method);
480 // If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to
481 // the getter method as it ends up on the property itself which we don't want
482 // to do unless -objcmt-returns-innerpointer-property option is on.
483 if (!PropertyInferred ||
484 (ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
Fariborz Jahanian22626e72013-11-08 02:00:22 +0000485 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
486 migrateNsReturnsInnerPointer(Ctx, Method);
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000487 }
Fariborz Jahanian23417072013-11-05 22:28:30 +0000488 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
489 return;
490
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000491 for (ObjCContainerDecl::prop_iterator P = D->prop_begin(),
492 E = D->prop_end(); P != E; ++P) {
493 ObjCPropertyDecl *Prop = *P;
Fariborz Jahanian8c45e282013-10-02 22:49:59 +0000494 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000495 !Prop->isDeprecated())
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000496 migratePropertyNsReturnsInnerPointer(Ctx, Prop);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000497 }
498}
499
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000500static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000501ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000502 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000503 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000504 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000505 // In auto-synthesis, protocol properties are not synthesized. So,
506 // a conforming protocol must have its required properties declared
507 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000508 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000509 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
510 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
511 E = PDecl->prop_end(); P != E; ++P) {
512 ObjCPropertyDecl *Property = *P;
513 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
514 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000515 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000516 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000517 if (R.size() == 0) {
518 // Relax the rule and look into class's implementation for a synthesize
519 // or dynamic declaration. Class is implementing a property coming from
520 // another protocol. This still makes the target protocol as conforming.
521 if (!ImpDecl->FindPropertyImplDecl(
522 Property->getDeclName().getAsIdentifierInfo()))
523 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000524 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000525 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
526 if ((ClassProperty->getPropertyAttributes()
527 != Property->getPropertyAttributes()) ||
528 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
529 return false;
530 }
531 else
532 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000533 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000534
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000535 // At this point, all required properties in this protocol conform to those
536 // declared in the class.
537 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000538 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000539 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
540 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000541 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000542 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
543 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
544 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000545 if (MD->isImplicit())
546 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000547 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
548 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000549 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000550 if (R.size() == 0)
551 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000552 bool match = false;
553 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000554 for (unsigned I = 0, N = R.size(); I != N; ++I)
555 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
556 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
557 match = true;
558 break;
559 }
560 if (!match)
561 return false;
562 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000563 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000564 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
565 return true;
566 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000567}
568
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000569static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
570 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
571 const NSAPI &NS, edit::Commit &commit) {
572 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
573 std::string ClassString;
574 SourceLocation EndLoc =
575 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
576
577 if (Protocols.empty()) {
578 ClassString = '<';
579 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
580 ClassString += ConformingProtocols[i]->getNameAsString();
581 if (i != (e-1))
582 ClassString += ", ";
583 }
584 ClassString += "> ";
585 }
586 else {
587 ClassString = ", ";
588 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
589 ClassString += ConformingProtocols[i]->getNameAsString();
590 if (i != (e-1))
591 ClassString += ", ";
592 }
593 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
594 EndLoc = *PL;
595 }
596
597 commit.insertAfterToken(EndLoc, ClassString);
598 return true;
599}
600
601static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
602 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000603 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000604 bool IsNSIntegerType,
605 bool NSOptions) {
606 std::string ClassString;
607 if (NSOptions)
608 ClassString = "typedef NS_OPTIONS(NSUInteger, ";
609 else
610 ClassString =
611 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, "
612 : "typedef NS_ENUM(NSUInteger, ";
613
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000614 ClassString += TypedefDcl->getIdentifier()->getName();
615 ClassString += ')';
616 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
617 commit.replace(R, ClassString);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000618 SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
619 EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
620 NS.getASTContext(), /*IsDecl*/true);
621 if (!EndOfEnumDclLoc.isInvalid()) {
622 SourceRange EnumDclRange(EnumDcl->getLocStart(), EndOfEnumDclLoc);
623 commit.insertFromRange(TypedefDcl->getLocStart(), EnumDclRange);
624 }
625 else
626 return false;
627
628 SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
629 EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
630 NS.getASTContext(), /*IsDecl*/true);
631 if (!EndTypedefDclLoc.isInvalid()) {
632 SourceRange TDRange(TypedefDcl->getLocStart(), EndTypedefDclLoc);
633 commit.remove(TDRange);
634 }
635 else
636 return false;
637
638 EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
Fariborz Jahanian1d27ffd2013-10-11 17:35:22 +0000639 /*IsDecl*/true);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000640 if (!EndOfEnumDclLoc.isInvalid()) {
641 SourceLocation BeginOfEnumDclLoc = EnumDcl->getLocStart();
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000642 // FIXME. This assumes that enum decl; is immediately preceded by eoln.
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000643 // It is trying to remove the enum decl. lines entirely.
644 BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
645 commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000646 return true;
647 }
648 return false;
649}
650
Fariborz Jahanian403425b2013-10-17 23:13:13 +0000651static void rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000652 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000653 const NSAPI &NS, edit::Commit &commit,
654 bool IsNSIntegerType) {
655 std::string ClassString =
656 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000657 ClassString += TypedefDcl->getIdentifier()->getName();
658 ClassString += ')';
659 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
660 commit.replace(R, ClassString);
661 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
662 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000663}
664
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000665static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000666 const EnumDecl *EnumDcl) {
667 bool PowerOfTwo = true;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000668 bool AllHexdecimalEnumerator = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000669 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000670 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
671 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
672 EnumConstantDecl *Enumerator = (*EI);
673 const Expr *InitExpr = Enumerator->getInitExpr();
674 if (!InitExpr) {
675 PowerOfTwo = false;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000676 AllHexdecimalEnumerator = false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000677 continue;
678 }
Fariborz Jahanian6e1798e2013-09-17 23:32:51 +0000679 InitExpr = InitExpr->IgnoreParenCasts();
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000680 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
681 if (BO->isShiftOp() || BO->isBitwiseOp())
682 return true;
683
684 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000685 if (PowerOfTwo && EnumVal) {
686 if (!llvm::isPowerOf2_64(EnumVal))
687 PowerOfTwo = false;
688 else if (EnumVal > MaxPowerOfTwoVal)
689 MaxPowerOfTwoVal = EnumVal;
690 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000691 if (AllHexdecimalEnumerator && EnumVal) {
692 bool FoundHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000693 SourceLocation EndLoc = Enumerator->getLocEnd();
694 Token Tok;
695 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
696 if (Tok.isLiteral() && Tok.getLength() > 2) {
697 if (const char *StringLit = Tok.getLiteralData())
698 FoundHexdecimalEnumerator =
699 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
700 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000701 if (!FoundHexdecimalEnumerator)
702 AllHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000703 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000704 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000705 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000706}
707
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000708void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000709 const ObjCImplementationDecl *ImpDecl) {
710 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000711 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000712 return;
713 // Find all implicit conforming protocols for this class
714 // and make them explicit.
715 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
716 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000717 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000718
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000719 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000720 ObjCProtocolDecls.begin(),
721 E = ObjCProtocolDecls.end(); I != E; ++I)
722 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000723 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000724
725 if (PotentialImplicitProtocols.empty())
726 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000727
728 // go through list of non-optional methods and properties in each protocol
729 // in the PotentialImplicitProtocols list. If class implements every one of the
730 // methods and properties, then this class conforms to this protocol.
731 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
732 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000733 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000734 PotentialImplicitProtocols[i]))
735 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000736
737 if (ConformingProtocols.empty())
738 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000739
740 // Further reduce number of conforming protocols. If protocol P1 is in the list
741 // protocol P2 (P2<P1>), No need to include P1.
742 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
743 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
744 bool DropIt = false;
745 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
746 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
747 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
748 if (PDecl == TargetPDecl)
749 continue;
750 if (PDecl->lookupProtocolNamed(
751 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
752 DropIt = true;
753 break;
754 }
755 }
756 if (!DropIt)
757 MinimalConformingProtocols.push_back(TargetPDecl);
758 }
Fariborz Jahanian769c04e2013-12-17 01:01:33 +0000759 if (MinimalConformingProtocols.empty())
760 return;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000761 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000762 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
763 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000764 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000765}
766
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000767void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
768 const TypedefDecl *TypedefDcl) {
769
770 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
771 if (NSAPIObj->isObjCNSIntegerType(qt))
772 NSIntegerTypedefed = TypedefDcl;
773 else if (NSAPIObj->isObjCNSUIntegerType(qt))
774 NSUIntegerTypedefed = TypedefDcl;
775}
776
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000777bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
Fariborz Jahanian92463272013-07-18 20:11:45 +0000778 const EnumDecl *EnumDcl,
779 const TypedefDecl *TypedefDcl) {
780 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000781 EnumDcl->isDeprecated())
782 return false;
783 if (!TypedefDcl) {
784 if (NSIntegerTypedefed) {
785 TypedefDcl = NSIntegerTypedefed;
786 NSIntegerTypedefed = 0;
787 }
788 else if (NSUIntegerTypedefed) {
789 TypedefDcl = NSUIntegerTypedefed;
790 NSUIntegerTypedefed = 0;
791 }
792 else
793 return false;
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +0000794 FileID FileIdOfTypedefDcl =
795 PP.getSourceManager().getFileID(TypedefDcl->getLocation());
796 FileID FileIdOfEnumDcl =
797 PP.getSourceManager().getFileID(EnumDcl->getLocation());
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000798 if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
799 return false;
800 }
801 if (TypedefDcl->isDeprecated())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000802 return false;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000803
804 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000805 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
806 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000807
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000808 if (!IsNSIntegerType && !IsNSUIntegerType) {
809 // Also check for typedef enum {...} TD;
810 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
811 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000812 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000813 if (NSOptions) {
814 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000815 return false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000816 }
817 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000818 return false;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000819 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000820 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000821 Editor->commit(commit);
Fariborz Jahaniande79e812013-10-17 22:23:32 +0000822 return true;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000823 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000824 }
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000825 return false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000826 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000827
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000828 // We may still use NS_OPTIONS based on what we find in the enumertor list.
829 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000830 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000831 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000832 return false;
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000833 // NS_OPTIONS must be available.
834 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000835 return false;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000836 edit::Commit commit(*Editor);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000837 bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
838 commit, IsNSIntegerType, NSOptions);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000839 Editor->commit(commit);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000840 return Res;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000841}
842
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000843static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
844 ObjCMethodDecl *OM) {
845 SourceRange R;
846 std::string ClassString;
Alp Toker314cc812014-01-25 16:55:45 +0000847 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000848 TypeLoc TL = TSInfo->getTypeLoc();
849 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
850 ClassString = "instancetype";
851 }
852 else {
853 R = SourceRange(OM->getLocStart(), OM->getLocStart());
854 ClassString = OM->isInstanceMethod() ? '-' : '+';
855 ClassString += " (instancetype)";
856 }
857 edit::Commit commit(*ASTC.Editor);
858 commit.replace(R, ClassString);
859 ASTC.Editor->commit(commit);
860}
861
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000862static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
863 ObjCMethodDecl *OM) {
864 ObjCInterfaceDecl *IDecl = OM->getClassInterface();
865 SourceRange R;
866 std::string ClassString;
Alp Toker314cc812014-01-25 16:55:45 +0000867 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000868 TypeLoc TL = TSInfo->getTypeLoc();
869 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
870 ClassString = IDecl->getName();
871 ClassString += "*";
872 }
873 }
874 else {
875 R = SourceRange(OM->getLocStart(), OM->getLocStart());
876 ClassString = "+ (";
877 ClassString += IDecl->getName(); ClassString += "*)";
878 }
879 edit::Commit commit(*ASTC.Editor);
880 commit.replace(R, ClassString);
881 ASTC.Editor->commit(commit);
882}
883
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000884void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
885 ObjCContainerDecl *CDecl,
886 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +0000887 ObjCInstanceTypeFamily OIT_Family =
888 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000889
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000890 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000891 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000892 case OIT_None:
893 migrateFactoryMethod(Ctx, CDecl, OM);
894 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000895 case OIT_Array:
896 ClassName = "NSArray";
897 break;
898 case OIT_Dictionary:
899 ClassName = "NSDictionary";
900 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000901 case OIT_Singleton:
902 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000903 return;
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +0000904 case OIT_Init:
Alp Toker314cc812014-01-25 16:55:45 +0000905 if (OM->getReturnType()->isObjCIdType())
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +0000906 ReplaceWithInstancetype(*this, OM);
907 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000908 case OIT_ReturnsSelf:
909 migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
910 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000911 }
Alp Toker314cc812014-01-25 16:55:45 +0000912 if (!OM->getReturnType()->isObjCIdType())
Fariborz Jahanian71221352013-07-23 22:42:28 +0000913 return;
914
915 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
916 if (!IDecl) {
917 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
918 IDecl = CatDecl->getClassInterface();
919 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
920 IDecl = ImpDecl->getClassInterface();
921 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000922 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000923 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
924 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000925 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000926 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000927 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000928}
929
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000930static bool TypeIsInnerPointer(QualType T) {
931 if (!T->isAnyPointerType())
932 return false;
933 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
Fariborz Jahanian73466ca2013-09-26 21:43:47 +0000934 T->isBlockPointerType() || T->isFunctionPointerType() ||
935 ento::coreFoundation::isCFObjectRef(T))
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000936 return false;
Fariborz Jahanian9d5fffb2013-09-09 23:56:14 +0000937 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
938 // is not an innter pointer type.
939 QualType OrigT = T;
940 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
941 T = TD->getDecl()->getUnderlyingType();
942 if (OrigT == T || !T->isPointerType())
943 return true;
944 const PointerType* PT = T->getAs<PointerType>();
945 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
946 if (UPointeeT->isRecordType()) {
947 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
948 if (!RecordTy->getDecl()->isCompleteDefinition())
949 return false;
950 }
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000951 return true;
952}
953
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000954/// \brief Check whether the two versions match.
955static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) {
956 return (X == Y);
957}
958
959/// AvailabilityAttrsMatch - This routine checks that if comparing two
960/// availability attributes, all their components match. It returns
961/// true, if not dealing with availability or when all components of
962/// availability attributes match. This routine is only called when
963/// the attributes are of the same kind.
964static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) {
965 const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1);
966 if (!AA1)
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000967 return true;
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000968 const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2);
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000969
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000970 VersionTuple Introduced1 = AA1->getIntroduced();
971 VersionTuple Deprecated1 = AA1->getDeprecated();
972 VersionTuple Obsoleted1 = AA1->getObsoleted();
973 bool IsUnavailable1 = AA1->getUnavailable();
974 VersionTuple Introduced2 = AA2->getIntroduced();
975 VersionTuple Deprecated2 = AA2->getDeprecated();
976 VersionTuple Obsoleted2 = AA2->getObsoleted();
977 bool IsUnavailable2 = AA2->getUnavailable();
978 return (versionsMatch(Introduced1, Introduced2) &&
979 versionsMatch(Deprecated1, Deprecated2) &&
980 versionsMatch(Obsoleted1, Obsoleted2) &&
981 IsUnavailable1 == IsUnavailable2);
982
983}
984
985static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2,
986 bool &AvailabilityArgsMatch) {
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000987 // This list is very small, so this need not be optimized.
988 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
989 bool match = false;
990 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000991 // Matching attribute kind only. Except for Availabilty attributes,
992 // we are not getting into details of the attributes. For all practical purposes
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000993 // this is sufficient.
994 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000995 if (AvailabilityArgsMatch)
996 AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]);
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000997 match = true;
998 break;
999 }
1000 }
1001 if (!match)
1002 return false;
1003 }
1004 return true;
1005}
1006
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001007/// AttributesMatch - This routine checks list of attributes for two
1008/// decls. It returns false, if there is a mismatch in kind of
1009/// attributes seen in the decls. It returns true if the two decls
1010/// have list of same kind of attributes. Furthermore, when there
1011/// are availability attributes in the two decls, it sets the
1012/// AvailabilityArgsMatch to false if availability attributes have
1013/// different versions, etc.
1014static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2,
1015 bool &AvailabilityArgsMatch) {
1016 if (!Decl1->hasAttrs() || !Decl2->hasAttrs()) {
1017 AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs());
1018 return true;
1019 }
1020 AvailabilityArgsMatch = true;
1021 const AttrVec &Attrs1 = Decl1->getAttrs();
1022 const AttrVec &Attrs2 = Decl2->getAttrs();
1023 bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch);
1024 if (match && (Attrs2.size() > Attrs1.size()))
1025 return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch);
1026 return match;
1027}
1028
Fariborz Jahanian5d783df2013-09-27 22:55:54 +00001029static bool IsValidIdentifier(ASTContext &Ctx,
1030 const char *Name) {
1031 if (!isIdentifierHead(Name[0]))
1032 return false;
1033 std::string NameString = Name;
1034 NameString[0] = toLowercase(NameString[0]);
1035 IdentifierInfo *II = &Ctx.Idents.get(NameString);
1036 return II->getTokenID() == tok::identifier;
1037}
1038
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001039bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001040 ObjCContainerDecl *D,
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001041 ObjCMethodDecl *Method) {
1042 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
1043 Method->param_size() != 0)
1044 return false;
1045 // Is this method candidate to be a getter?
Alp Toker314cc812014-01-25 16:55:45 +00001046 QualType GRT = Method->getReturnType();
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001047 if (GRT->isVoidType())
1048 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001049
1050 Selector GetterSelector = Method->getSelector();
Fariborz Jahanian7391a7b5a2013-09-25 00:17:07 +00001051 ObjCInstanceTypeFamily OIT_Family =
1052 Selector::getInstTypeMethodFamily(GetterSelector);
1053
1054 if (OIT_Family != OIT_None)
1055 return false;
1056
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001057 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
1058 Selector SetterSelector =
1059 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1060 PP.getSelectorTable(),
1061 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001062 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanianca399602013-09-11 17:05:15 +00001063 unsigned LengthOfPrefix = 0;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001064 if (!SetterMethod) {
1065 // try a different naming convention for getter: isXxxxx
1066 StringRef getterNameString = getterName->getName();
Fariborz Jahanianca399602013-09-11 17:05:15 +00001067 bool IsPrefix = getterNameString.startswith("is");
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +00001068 // Note that we don't want to change an isXXX method of retainable object
1069 // type to property (readonly or otherwise).
1070 if (IsPrefix && GRT->isObjCRetainableType())
1071 return false;
1072 if (IsPrefix || getterNameString.startswith("get")) {
Fariborz Jahanianca399602013-09-11 17:05:15 +00001073 LengthOfPrefix = (IsPrefix ? 2 : 3);
1074 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
1075 // Make sure that first character after "is" or "get" prefix can
1076 // start an identifier.
Fariborz Jahanian5d783df2013-09-27 22:55:54 +00001077 if (!IsValidIdentifier(Ctx, CGetterName))
Fariborz Jahanianca399602013-09-11 17:05:15 +00001078 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001079 if (CGetterName[0] && isUppercase(CGetterName[0])) {
1080 getterName = &Ctx.Idents.get(CGetterName);
1081 SetterSelector =
1082 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1083 PP.getSelectorTable(),
1084 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001085 SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001086 }
1087 }
1088 }
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +00001089
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001090 if (SetterMethod) {
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001091 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
1092 return false;
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001093 bool AvailabilityArgsMatch;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001094 if (SetterMethod->isDeprecated() ||
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001095 !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch))
Fariborz Jahanianf6c65052013-09-17 22:41:25 +00001096 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001097
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001098 // Is this a valid setter, matching the target getter?
Alp Toker314cc812014-01-25 16:55:45 +00001099 QualType SRT = SetterMethod->getReturnType();
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001100 if (!SRT->isVoidType())
1101 return false;
1102 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
1103 QualType ArgType = argDecl->getType();
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001104 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001105 return false;
1106 edit::Commit commit(*Editor);
1107 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001108 LengthOfPrefix,
1109 (ASTMigrateActions &
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001110 FrontendOptions::ObjCMT_AtomicProperty) != 0,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001111 (ASTMigrateActions &
1112 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001113 AvailabilityArgsMatch);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001114 Editor->commit(commit);
1115 return true;
1116 }
Fariborz Jahanian182486c2013-10-02 17:08:12 +00001117 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001118 // Try a non-void method with no argument (and no setter or property of same name
1119 // as a 'readonly' property.
1120 edit::Commit commit(*Editor);
1121 rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001122 LengthOfPrefix,
1123 (ASTMigrateActions &
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001124 FrontendOptions::ObjCMT_AtomicProperty) != 0,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001125 (ASTMigrateActions &
1126 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001127 /*AvailabilityArgsMatch*/false);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001128 Editor->commit(commit);
1129 return true;
1130 }
1131 return false;
1132}
1133
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001134void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
1135 ObjCMethodDecl *OM) {
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001136 if (OM->isImplicit() ||
Fariborz Jahanian7c1a4452013-09-26 22:43:41 +00001137 !OM->isInstanceMethod() ||
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001138 OM->hasAttr<ObjCReturnsInnerPointerAttr>())
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001139 return;
Alp Toker314cc812014-01-25 16:55:45 +00001140
1141 QualType RT = OM->getReturnType();
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001142 if (!TypeIsInnerPointer(RT) ||
1143 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
1144 return;
1145
1146 edit::Commit commit(*Editor);
1147 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
1148 Editor->commit(commit);
1149}
1150
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001151void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
1152 ObjCPropertyDecl *P) {
1153 QualType T = P->getType();
1154
1155 if (!TypeIsInnerPointer(T) ||
1156 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
1157 return;
1158 edit::Commit commit(*Editor);
1159 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
1160 Editor->commit(commit);
1161}
1162
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001163void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
Fariborz Jahanian71221352013-07-23 22:42:28 +00001164 ObjCContainerDecl *CDecl) {
Fariborz Jahanian48a44d42013-11-19 18:17:31 +00001165 if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl))
Fariborz Jahaniane47a14a2013-09-18 15:43:52 +00001166 return;
1167
Fariborz Jahanian71221352013-07-23 22:42:28 +00001168 // migrate methods which can have instancetype as their result type.
1169 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1170 MEnd = CDecl->meth_end();
1171 M != MEnd; ++M) {
1172 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001173 if (Method->isDeprecated())
1174 continue;
Fariborz Jahanian71221352013-07-23 22:42:28 +00001175 migrateMethodInstanceType(Ctx, CDecl, Method);
1176 }
1177}
1178
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001179void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
1180 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001181 ObjCMethodDecl *OM,
1182 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +00001183 if (OM->isInstanceMethod() ||
Alp Toker314cc812014-01-25 16:55:45 +00001184 OM->getReturnType() == Ctx.getObjCInstanceType() ||
1185 !OM->getReturnType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001186 return;
1187
1188 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1189 // NSYYYNamE with matching names be at least 3 characters long.
1190 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1191 if (!IDecl) {
1192 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1193 IDecl = CatDecl->getClassInterface();
1194 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1195 IDecl = ImpDecl->getClassInterface();
1196 }
1197 if (!IDecl)
1198 return;
1199
1200 std::string StringClassName = IDecl->getName();
1201 StringRef LoweredClassName(StringClassName);
1202 std::string StringLoweredClassName = LoweredClassName.lower();
1203 LoweredClassName = StringLoweredClassName;
1204
1205 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001206 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1207 if (!MethodIdName)
1208 return;
1209
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001210 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001211 if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001212 StringRef STRefMethodName(MethodName);
1213 size_t len = 0;
1214 if (STRefMethodName.startswith("standard"))
1215 len = strlen("standard");
1216 else if (STRefMethodName.startswith("shared"))
1217 len = strlen("shared");
1218 else if (STRefMethodName.startswith("default"))
1219 len = strlen("default");
1220 else
1221 return;
1222 MethodName = STRefMethodName.substr(len);
1223 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001224 std::string MethodNameSubStr = MethodName.substr(0, 3);
1225 StringRef MethodNamePrefix(MethodNameSubStr);
1226 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1227 MethodNamePrefix = StringLoweredMethodNamePrefix;
1228 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1229 if (Ix == StringRef::npos)
1230 return;
1231 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1232 StringRef LoweredMethodName(MethodName);
1233 std::string StringLoweredMethodName = LoweredMethodName.lower();
1234 LoweredMethodName = StringLoweredMethodName;
1235 if (!LoweredMethodName.startswith(ClassNamePostfix))
1236 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001237 if (OIT_Family == OIT_ReturnsSelf)
1238 ReplaceWithClasstype(*this, OM);
1239 else
1240 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001241}
1242
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001243static bool IsVoidStarType(QualType Ty) {
1244 if (!Ty->isPointerType())
1245 return false;
1246
1247 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1248 Ty = TD->getDecl()->getUnderlyingType();
1249
1250 // Is the type void*?
1251 const PointerType* PT = Ty->getAs<PointerType>();
1252 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1253 return true;
1254 return IsVoidStarType(PT->getPointeeType());
1255}
1256
Fariborz Jahanian94279392013-08-20 18:54:39 +00001257/// AuditedType - This routine audits the type AT and returns false if it is one of known
1258/// CF object types or of the "void *" variety. It returns true if we don't care about the type
1259/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001260static bool AuditedType (QualType AT) {
1261 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001262 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001263 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +00001264 if (ento::coreFoundation::isCFObjectRef(AT) ||
1265 IsVoidStarType(AT) ||
1266 // If an ObjC object is type, assuming that it is not a CF function and
1267 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +00001268 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001269 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +00001270 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001271 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001272}
1273
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001274void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001275 if (CFFunctionIBCandidates.empty())
1276 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001277 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
1278 CFFunctionIBCandidates.clear();
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001279 FileId = FileID();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001280 return;
1281 }
1282 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001283 const Decl *FirstFD = CFFunctionIBCandidates[0];
1284 const Decl *LastFD =
1285 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001286 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1287 edit::Commit commit(*Editor);
1288 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
1289 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1290 SourceLocation EndLoc = LastFD->getLocEnd();
1291 // get location just past end of function location.
1292 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001293 if (isa<FunctionDecl>(LastFD)) {
1294 // For Methods, EndLoc points to the ending semcolon. So,
1295 // not of these extra work is needed.
1296 Token Tok;
1297 // get locaiton of token that comes after end of function.
1298 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1299 if (!Failed)
1300 EndLoc = Tok.getLocation();
1301 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001302 commit.insertAfterToken(EndLoc, PragmaString);
1303 Editor->commit(commit);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001304 FileId = FileID();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001305 CFFunctionIBCandidates.clear();
1306}
1307
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001308void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001309 if (Decl->isDeprecated())
1310 return;
1311
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001312 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001313 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001314 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001315 "provided CF_IMPLICIT_BRIDGING_ENABLE");
1316 return;
1317 }
1318
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001319 // Finction must be annotated first.
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001320 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1321 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1322 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001323 CFFunctionIBCandidates.push_back(Decl);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001324 if (FileId.isInvalid())
1325 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001326 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001327 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1328 if (!CFFunctionIBCandidates.empty()) {
1329 CFFunctionIBCandidates.push_back(Decl);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001330 if (FileId.isInvalid())
1331 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001332 }
1333 }
1334 else
1335 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001336 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001337 else {
1338 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001339 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001340 }
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001341}
1342
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001343void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1344 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001345 const FunctionDecl *FuncDecl,
1346 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001347 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001348 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001349 RetEffect Ret = CE.getReturnValue();
1350 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001351 if (Ret.getObjKind() == RetEffect::CF) {
1352 if (Ret.isOwned() &&
1353 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001354 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001355 else if (Ret.notOwned() &&
1356 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001357 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1358 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001359 else if (Ret.getObjKind() == RetEffect::ObjC) {
1360 if (Ret.isOwned() &&
1361 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1362 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001363 }
1364
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001365 if (AnnotationString) {
1366 edit::Commit commit(*Editor);
1367 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1368 Editor->commit(commit);
1369 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001370 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001371 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1372 unsigned i = 0;
1373 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1374 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +00001375 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001376 ArgEffect AE = AEArgs[i];
Aaron Ballman9ead1242013-12-19 02:39:40 +00001377 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001378 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1379 edit::Commit commit(*Editor);
1380 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1381 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +00001382 }
Aaron Ballman9ead1242013-12-19 02:39:40 +00001383 else if (AE == DecRefMsg && !pd->hasAttr<NSConsumedAttr>() &&
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001384 Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
1385 edit::Commit commit(*Editor);
1386 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1387 Editor->commit(commit);
1388 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001389 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001390}
1391
1392
1393ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1394 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1395 ASTContext &Ctx,
1396 const FunctionDecl *FuncDecl) {
1397 if (FuncDecl->hasBody())
1398 return CF_BRIDGING_NONE;
1399
1400 CallEffects CE = CallEffects::getEffect(FuncDecl);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001401 bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() ||
1402 FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1403 FuncDecl->hasAttr<NSReturnsRetainedAttr>() ||
1404 FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1405 FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001406
1407 // Trivial case of when funciton is annotated and has no argument.
1408 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1409 return CF_BRIDGING_NONE;
1410
1411 bool ReturnCFAudited = false;
1412 if (!FuncIsReturnAnnotated) {
1413 RetEffect Ret = CE.getReturnValue();
1414 if (Ret.getObjKind() == RetEffect::CF &&
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001415 (Ret.isOwned() || Ret.notOwned()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001416 ReturnCFAudited = true;
Alp Toker314cc812014-01-25 16:55:45 +00001417 else if (!AuditedType(FuncDecl->getReturnType()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001418 return CF_BRIDGING_NONE;
1419 }
1420
1421 // At this point result type is audited for potential inclusion.
1422 // Now, how about argument types.
1423 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1424 unsigned i = 0;
1425 bool ArgCFAudited = false;
1426 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1427 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1428 const ParmVarDecl *pd = *pi;
1429 ArgEffect AE = AEArgs[i];
1430 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
Aaron Ballman9ead1242013-12-19 02:39:40 +00001431 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>())
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001432 ArgCFAudited = true;
1433 else if (AE == IncRef)
1434 ArgCFAudited = true;
1435 }
1436 else {
1437 QualType AT = pd->getType();
1438 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001439 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001440 return CF_BRIDGING_NONE;
1441 }
1442 }
1443 }
1444 if (ReturnCFAudited || ArgCFAudited)
1445 return CF_BRIDGING_ENABLE;
1446
1447 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001448}
1449
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001450void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1451 ObjCContainerDecl *CDecl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001452 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001453 return;
1454
1455 // migrate methods which can have instancetype as their result type.
1456 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1457 MEnd = CDecl->meth_end();
1458 M != MEnd; ++M) {
1459 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001460 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001461 }
1462}
1463
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001464void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1465 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001466 const ObjCMethodDecl *MethodDecl,
1467 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001468 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001469 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001470 RetEffect Ret = CE.getReturnValue();
1471 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001472 if (Ret.getObjKind() == RetEffect::CF) {
1473 if (Ret.isOwned() &&
1474 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001475 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001476 else if (Ret.notOwned() &&
1477 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001478 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1479 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001480 else if (Ret.getObjKind() == RetEffect::ObjC) {
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001481 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1482 switch (OMF) {
1483 case clang::OMF_alloc:
1484 case clang::OMF_new:
1485 case clang::OMF_copy:
1486 case clang::OMF_init:
1487 case clang::OMF_mutableCopy:
1488 break;
1489
1490 default:
1491 if (Ret.isOwned() &&
1492 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1493 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001494 break;
1495 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001496 }
1497
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001498 if (AnnotationString) {
1499 edit::Commit commit(*Editor);
1500 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1501 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001502 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001503 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001504 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1505 unsigned i = 0;
1506 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1507 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1508 const ParmVarDecl *pd = *pi;
1509 ArgEffect AE = AEArgs[i];
Aaron Ballman9ead1242013-12-19 02:39:40 +00001510 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001511 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1512 edit::Commit commit(*Editor);
1513 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1514 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001515 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001516 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001517}
1518
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001519void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001520 ASTContext &Ctx,
1521 const ObjCMethodDecl *MethodDecl) {
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001522 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001523 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001524
1525 CallEffects CE = CallEffects::getEffect(MethodDecl);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001526 bool MethodIsReturnAnnotated = (MethodDecl->hasAttr<CFReturnsRetainedAttr>() ||
1527 MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1528 MethodDecl->hasAttr<NSReturnsRetainedAttr>() ||
1529 MethodDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1530 MethodDecl->hasAttr<NSReturnsAutoreleasedAttr>());
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001531
1532 if (CE.getReceiver() == DecRefMsg &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00001533 !MethodDecl->hasAttr<NSConsumesSelfAttr>() &&
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001534 MethodDecl->getMethodFamily() != OMF_init &&
1535 MethodDecl->getMethodFamily() != OMF_release &&
1536 Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
1537 edit::Commit commit(*Editor);
1538 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1539 Editor->commit(commit);
1540 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001541
1542 // Trivial case of when funciton is annotated and has no argument.
1543 if (MethodIsReturnAnnotated &&
1544 (MethodDecl->param_begin() == MethodDecl->param_end()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001545 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001546
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001547 if (!MethodIsReturnAnnotated) {
1548 RetEffect Ret = CE.getReturnValue();
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001549 if ((Ret.getObjKind() == RetEffect::CF ||
1550 Ret.getObjKind() == RetEffect::ObjC) &&
1551 (Ret.isOwned() || Ret.notOwned())) {
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001552 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1553 return;
Alp Toker314cc812014-01-25 16:55:45 +00001554 } else if (!AuditedType(MethodDecl->getReturnType()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001555 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001556 }
1557
1558 // At this point result type is either annotated or audited.
1559 // Now, how about argument types.
1560 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1561 unsigned i = 0;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001562 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1563 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1564 const ParmVarDecl *pd = *pi;
1565 ArgEffect AE = AEArgs[i];
Aaron Ballman9ead1242013-12-19 02:39:40 +00001566 if ((AE == DecRef && !pd->hasAttr<CFConsumedAttr>()) || AE == IncRef ||
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001567 !AuditedType(pd->getType())) {
1568 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1569 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001570 }
1571 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001572 return;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001573}
1574
Ted Kremenekf7639e12012-03-06 20:06:33 +00001575namespace {
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001576class SuperInitChecker : public RecursiveASTVisitor<SuperInitChecker> {
1577public:
1578 bool shouldVisitTemplateInstantiations() const { return false; }
1579 bool shouldWalkTypesOfTypeLocs() const { return false; }
1580
1581 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
1582 if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
1583 if (E->getMethodFamily() == OMF_init)
1584 return false;
1585 }
1586 return true;
1587 }
1588};
1589} // anonymous namespace
1590
1591static bool hasSuperInitCall(const ObjCMethodDecl *MD) {
1592 return !SuperInitChecker().TraverseStmt(MD->getBody());
1593}
1594
1595void ObjCMigrateASTConsumer::inferDesignatedInitializers(
1596 ASTContext &Ctx,
1597 const ObjCImplementationDecl *ImplD) {
1598
1599 const ObjCInterfaceDecl *IFace = ImplD->getClassInterface();
1600 if (!IFace || IFace->hasDesignatedInitializers())
1601 return;
1602 if (!Ctx.Idents.get("NS_DESIGNATED_INITIALIZER").hasMacroDefinition())
1603 return;
1604
1605 for (ObjCImplementationDecl::instmeth_iterator
1606 I = ImplD->instmeth_begin(), E = ImplD->instmeth_end(); I != E; ++I) {
1607 const ObjCMethodDecl *MD = *I;
1608 if (MD->isDeprecated() ||
1609 MD->getMethodFamily() != OMF_init ||
1610 MD->isDesignatedInitializerForTheInterface())
1611 continue;
1612 const ObjCMethodDecl *IFaceM = IFace->getMethod(MD->getSelector(),
1613 /*isInstance=*/true);
1614 if (!IFaceM)
1615 continue;
1616 if (hasSuperInitCall(MD)) {
1617 edit::Commit commit(*Editor);
1618 commit.insert(IFaceM->getLocEnd(), " NS_DESIGNATED_INITIALIZER");
1619 Editor->commit(commit);
1620 }
1621 }
1622}
1623
1624namespace {
Ted Kremenekf7639e12012-03-06 20:06:33 +00001625
1626class RewritesReceiver : public edit::EditsReceiver {
1627 Rewriter &Rewrite;
1628
1629public:
1630 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1631
1632 virtual void insert(SourceLocation loc, StringRef text) {
1633 Rewrite.InsertText(loc, text);
1634 }
1635 virtual void replace(CharSourceRange range, StringRef text) {
1636 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1637 }
1638};
1639
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001640class JSONEditWriter : public edit::EditsReceiver {
1641 SourceManager &SourceMgr;
1642 llvm::raw_ostream &OS;
1643
1644public:
1645 JSONEditWriter(SourceManager &SM, llvm::raw_ostream &OS)
1646 : SourceMgr(SM), OS(OS) {
1647 OS << "[\n";
1648 }
1649 ~JSONEditWriter() {
1650 OS << "]\n";
1651 }
1652
1653private:
1654 struct EntryWriter {
1655 SourceManager &SourceMgr;
1656 llvm::raw_ostream &OS;
1657
1658 EntryWriter(SourceManager &SM, llvm::raw_ostream &OS)
1659 : SourceMgr(SM), OS(OS) {
1660 OS << " {\n";
1661 }
1662 ~EntryWriter() {
1663 OS << " },\n";
1664 }
1665
1666 void writeLoc(SourceLocation Loc) {
1667 FileID FID;
1668 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001669 std::tie(FID, Offset) = SourceMgr.getDecomposedLoc(Loc);
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001670 assert(!FID.isInvalid());
1671 SmallString<200> Path =
1672 StringRef(SourceMgr.getFileEntryForID(FID)->getName());
1673 llvm::sys::fs::make_absolute(Path);
1674 OS << " \"file\": \"";
1675 OS.write_escaped(Path.str()) << "\",\n";
1676 OS << " \"offset\": " << Offset << ",\n";
1677 }
1678
1679 void writeRemove(CharSourceRange Range) {
1680 assert(Range.isCharRange());
1681 std::pair<FileID, unsigned> Begin =
1682 SourceMgr.getDecomposedLoc(Range.getBegin());
1683 std::pair<FileID, unsigned> End =
1684 SourceMgr.getDecomposedLoc(Range.getEnd());
1685 assert(Begin.first == End.first);
1686 assert(Begin.second <= End.second);
1687 unsigned Length = End.second - Begin.second;
1688
1689 OS << " \"remove\": " << Length << ",\n";
1690 }
1691
1692 void writeText(StringRef Text) {
1693 OS << " \"text\": \"";
1694 OS.write_escaped(Text) << "\",\n";
1695 }
1696 };
1697
1698 virtual void insert(SourceLocation Loc, StringRef Text) {
1699 EntryWriter Writer(SourceMgr, OS);
1700 Writer.writeLoc(Loc);
1701 Writer.writeText(Text);
1702 }
1703
1704 virtual void replace(CharSourceRange Range, StringRef Text) {
1705 EntryWriter Writer(SourceMgr, OS);
1706 Writer.writeLoc(Range.getBegin());
1707 Writer.writeRemove(Range);
1708 Writer.writeText(Text);
1709 }
1710
1711 virtual void remove(CharSourceRange Range) {
1712 EntryWriter Writer(SourceMgr, OS);
1713 Writer.writeLoc(Range.getBegin());
1714 Writer.writeRemove(Range);
1715 }
1716};
1717
Ted Kremenekf7639e12012-03-06 20:06:33 +00001718}
1719
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001720static bool
1721IsReallyASystemHeader(ASTContext &Ctx, const FileEntry *file, FileID FID) {
1722 bool Invalid = false;
1723 const SrcMgr::SLocEntry &SEntry =
1724 Ctx.getSourceManager().getSLocEntry(FID, &Invalid);
1725 if (!Invalid && SEntry.isFile()) {
1726 const SrcMgr::FileInfo &FI = SEntry.getFile();
1727 if (!FI.hasLineDirectives()) {
1728 if (FI.getFileCharacteristic() == SrcMgr::C_ExternCSystem)
1729 return true;
1730 if (FI.getFileCharacteristic() == SrcMgr::C_System) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00001731 // This file is in a system header directory. Continue committing
1732 // change only if it's a user-specified system directory because user
1733 // put a .system_framework file in the framework directory.
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001734 StringRef Directory(file->getDir()->getName());
1735 size_t Ix = Directory.rfind(".framework");
1736 if (Ix == StringRef::npos)
1737 return true;
1738 std::string PatchToSystemFramework = Directory.slice(0, Ix+sizeof(".framework"));
1739 PatchToSystemFramework += ".system_framework";
1740 if (!llvm::sys::fs::exists(PatchToSystemFramework.data()))
1741 return true;
1742 }
1743 }
1744 }
1745 return false;
1746}
1747
Ted Kremenekf7639e12012-03-06 20:06:33 +00001748void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001749
1750 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001751 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001752 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1753 D != DEnd; ++D) {
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001754 FileID FID = PP.getSourceManager().getFileID((*D)->getLocation());
1755 if (!FID.isInvalid())
1756 if (!FileId.isInvalid() && FileId != FID) {
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001757 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1758 AnnotateImplicitBridging(Ctx);
1759 }
1760
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001761 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001762 if (canModify(CDecl))
1763 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001764 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001765 if (canModify(CatDecl))
1766 migrateObjCInterfaceDecl(Ctx, CatDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001767 }
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001768 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
Fariborz Jahanian769c04e2013-12-17 01:01:33 +00001769 ObjCProtocolDecls.insert(PDecl->getCanonicalDecl());
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001770 else if (const ObjCImplementationDecl *ImpDecl =
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001771 dyn_cast<ObjCImplementationDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001772 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) &&
1773 canModify(ImpDecl))
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001774 migrateProtocolConformance(Ctx, ImpDecl);
1775 }
Fariborz Jahanian92463272013-07-18 20:11:45 +00001776 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001777 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1778 continue;
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001779 if (!canModify(ED))
1780 continue;
Fariborz Jahanian92463272013-07-18 20:11:45 +00001781 DeclContext::decl_iterator N = D;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001782 if (++N != DEnd) {
1783 const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
1784 if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
1785 D++;
1786 }
1787 else
1788 migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */0);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001789 }
1790 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001791 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1792 continue;
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001793 if (!canModify(TD))
1794 continue;
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001795 DeclContext::decl_iterator N = D;
1796 if (++N == DEnd)
1797 continue;
1798 if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001799 if (++N != DEnd)
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001800 if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) {
1801 // prefer typedef-follows-enum to enum-follows-typedef pattern.
1802 if (migrateNSEnumDecl(Ctx, ED, TDF)) {
1803 ++D; ++D;
1804 CacheObjCNSIntegerTypedefed(TD);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001805 continue;
1806 }
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001807 }
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001808 if (migrateNSEnumDecl(Ctx, ED, TD)) {
1809 ++D;
1810 continue;
1811 }
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001812 }
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001813 CacheObjCNSIntegerTypedefed(TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001814 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001815 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001816 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1817 canModify(FD))
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001818 migrateCFAnnotation(Ctx, FD);
1819 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001820
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001821 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001822 bool CanModify = canModify(CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001823 // migrate methods which can have instancetype as their result type.
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001824 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) &&
1825 CanModify)
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001826 migrateAllMethodInstaceType(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001827 // annotate methods with CF annotations.
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001828 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1829 CanModify)
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001830 migrateARCSafeAnnotation(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001831 }
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001832
1833 if (const ObjCImplementationDecl *
1834 ImplD = dyn_cast<ObjCImplementationDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001835 if ((ASTMigrateActions & FrontendOptions::ObjCMT_DesignatedInitializer) &&
1836 canModify(ImplD))
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001837 inferDesignatedInitializers(Ctx, ImplD);
1838 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001839 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001840 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1841 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001842 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001843
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001844 if (IsOutputFile) {
1845 std::string Error;
Rafael Espindola4fbd3732014-02-24 18:20:21 +00001846 llvm::raw_fd_ostream OS(MigrateDir.c_str(), Error, llvm::sys::fs::F_None);
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001847 if (!Error.empty()) {
Alp Toker29cb66b2014-01-26 06:17:37 +00001848 DiagnosticsEngine &Diags = Ctx.getDiagnostics();
1849 Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
1850 << Error;
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001851 return;
1852 }
1853
1854 JSONEditWriter Writer(Ctx.getSourceManager(), OS);
1855 Editor->applyRewrites(Writer);
1856 return;
1857 }
1858
David Blaikiebbafb8a2012-03-11 07:00:24 +00001859 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001860 RewritesReceiver Rec(rewriter);
1861 Editor->applyRewrites(Rec);
1862
1863 for (Rewriter::buffer_iterator
1864 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1865 FileID FID = I->first;
1866 RewriteBuffer &buf = I->second;
1867 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1868 assert(file);
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001869 if (IsReallyASystemHeader(Ctx, file, FID))
1870 continue;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001871 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001872 llvm::raw_svector_ostream vecOS(newText);
1873 buf.write(vecOS);
1874 vecOS.flush();
1875 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1876 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001877 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001878 FileMgr.FixupRelativePath(filePath);
1879 Remapper.remap(filePath.str(), memBuf);
1880 }
1881
1882 if (IsOutputFile) {
1883 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1884 } else {
1885 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1886 }
1887}
1888
1889bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001890 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001891 return true;
1892}
1893
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00001894static std::vector<std::string> getWhiteListFilenames(StringRef DirPath) {
1895 using namespace llvm::sys::fs;
1896 using namespace llvm::sys::path;
1897
1898 std::vector<std::string> Filenames;
1899 if (DirPath.empty() || !is_directory(DirPath))
1900 return Filenames;
1901
1902 llvm::error_code EC;
1903 directory_iterator DI = directory_iterator(DirPath, EC);
1904 directory_iterator DE;
1905 for (; !EC && DI != DE; DI = DI.increment(EC)) {
1906 if (is_regular_file(DI->path()))
1907 Filenames.push_back(filename(DI->path()));
1908 }
1909
1910 return Filenames;
1911}
1912
Ted Kremenekf7639e12012-03-06 20:06:33 +00001913ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1914 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001915 PPConditionalDirectiveRecord *
1916 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
Argyrios Kyrtzidisee02a8a2013-11-13 23:38:22 +00001917 unsigned ObjCMTAction = CI.getFrontendOpts().ObjCMTAction;
Argyrios Kyrtzidisc47c63b2013-11-14 16:33:20 +00001918 unsigned ObjCMTOpts = ObjCMTAction;
1919 // These are companion flags, they do not enable transformations.
1920 ObjCMTOpts &= ~(FrontendOptions::ObjCMT_AtomicProperty |
1921 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty);
1922 if (ObjCMTOpts == FrontendOptions::ObjCMT_None) {
Argyrios Kyrtzidisee02a8a2013-11-13 23:38:22 +00001923 // If no specific option was given, enable literals+subscripting transforms
1924 // by default.
Argyrios Kyrtzidisc47c63b2013-11-14 16:33:20 +00001925 ObjCMTAction |= FrontendOptions::ObjCMT_Literals |
1926 FrontendOptions::ObjCMT_Subscripting;
Argyrios Kyrtzidisee02a8a2013-11-13 23:38:22 +00001927 }
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001928 CI.getPreprocessor().addPPCallbacks(PPRec);
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00001929 std::vector<std::string> WhiteList =
1930 getWhiteListFilenames(CI.getFrontendOpts().ObjCMTWhiteListPath);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001931 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
Argyrios Kyrtzidisee02a8a2013-11-13 23:38:22 +00001932 ObjCMTAction,
Ted Kremenekf7639e12012-03-06 20:06:33 +00001933 Remapper,
1934 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001935 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001936 CI.getPreprocessor(),
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00001937 /*isOutputFile=*/true,
1938 WhiteList);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001939}
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001940
1941namespace {
1942struct EditEntry {
1943 const FileEntry *File;
1944 unsigned Offset;
1945 unsigned RemoveLen;
1946 std::string Text;
1947
1948 EditEntry() : File(), Offset(), RemoveLen() {}
1949};
1950}
1951
1952namespace llvm {
1953template<> struct DenseMapInfo<EditEntry> {
1954 static inline EditEntry getEmptyKey() {
1955 EditEntry Entry;
1956 Entry.Offset = unsigned(-1);
1957 return Entry;
1958 }
1959 static inline EditEntry getTombstoneKey() {
1960 EditEntry Entry;
1961 Entry.Offset = unsigned(-2);
1962 return Entry;
1963 }
1964 static unsigned getHashValue(const EditEntry& Val) {
1965 llvm::FoldingSetNodeID ID;
1966 ID.AddPointer(Val.File);
1967 ID.AddInteger(Val.Offset);
1968 ID.AddInteger(Val.RemoveLen);
1969 ID.AddString(Val.Text);
1970 return ID.ComputeHash();
1971 }
1972 static bool isEqual(const EditEntry &LHS, const EditEntry &RHS) {
1973 return LHS.File == RHS.File &&
1974 LHS.Offset == RHS.Offset &&
1975 LHS.RemoveLen == RHS.RemoveLen &&
1976 LHS.Text == RHS.Text;
1977 }
1978};
1979}
1980
1981namespace {
1982class RemapFileParser {
1983 FileManager &FileMgr;
1984
1985public:
1986 RemapFileParser(FileManager &FileMgr) : FileMgr(FileMgr) { }
1987
1988 bool parse(StringRef File, SmallVectorImpl<EditEntry> &Entries) {
1989 using namespace llvm::yaml;
1990
1991 OwningPtr<llvm::MemoryBuffer> FileBuf;
1992 if (llvm::MemoryBuffer::getFile(File, FileBuf))
1993 return true;
1994
1995 llvm::SourceMgr SM;
Ahmed Charles9a16beb2014-03-07 19:33:25 +00001996 Stream YAMLStream(FileBuf.release(), SM);
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001997 document_iterator I = YAMLStream.begin();
1998 if (I == YAMLStream.end())
1999 return true;
2000 Node *Root = I->getRoot();
2001 if (!Root)
2002 return true;
2003
2004 SequenceNode *SeqNode = dyn_cast<SequenceNode>(Root);
2005 if (!SeqNode)
2006 return true;
2007
2008 for (SequenceNode::iterator
2009 AI = SeqNode->begin(), AE = SeqNode->end(); AI != AE; ++AI) {
2010 MappingNode *MapNode = dyn_cast<MappingNode>(&*AI);
2011 if (!MapNode)
2012 continue;
2013 parseEdit(MapNode, Entries);
2014 }
2015
2016 return false;
2017 }
2018
2019private:
2020 void parseEdit(llvm::yaml::MappingNode *Node,
2021 SmallVectorImpl<EditEntry> &Entries) {
2022 using namespace llvm::yaml;
2023 EditEntry Entry;
2024 bool Ignore = false;
2025
2026 for (MappingNode::iterator
2027 KVI = Node->begin(), KVE = Node->end(); KVI != KVE; ++KVI) {
2028 ScalarNode *KeyString = dyn_cast<ScalarNode>((*KVI).getKey());
2029 if (!KeyString)
2030 continue;
2031 SmallString<10> KeyStorage;
2032 StringRef Key = KeyString->getValue(KeyStorage);
2033
2034 ScalarNode *ValueString = dyn_cast<ScalarNode>((*KVI).getValue());
2035 if (!ValueString)
2036 continue;
2037 SmallString<64> ValueStorage;
2038 StringRef Val = ValueString->getValue(ValueStorage);
2039
2040 if (Key == "file") {
2041 const FileEntry *FE = FileMgr.getFile(Val);
2042 if (!FE)
2043 Ignore = true;
2044 Entry.File = FE;
2045 } else if (Key == "offset") {
2046 if (Val.getAsInteger(10, Entry.Offset))
2047 Ignore = true;
2048 } else if (Key == "remove") {
2049 if (Val.getAsInteger(10, Entry.RemoveLen))
2050 Ignore = true;
2051 } else if (Key == "text") {
2052 Entry.Text = Val;
2053 }
2054 }
2055
2056 if (!Ignore)
2057 Entries.push_back(Entry);
2058 }
2059};
2060}
2061
2062static bool reportDiag(const Twine &Err, DiagnosticsEngine &Diag) {
Alp Toker29cb66b2014-01-26 06:17:37 +00002063 Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
2064 << Err.str();
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002065 return true;
2066}
2067
2068static std::string applyEditsToTemp(const FileEntry *FE,
2069 ArrayRef<EditEntry> Edits,
2070 FileManager &FileMgr,
2071 DiagnosticsEngine &Diag) {
2072 using namespace llvm::sys;
2073
2074 SourceManager SM(Diag, FileMgr);
2075 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
2076 LangOptions LangOpts;
2077 edit::EditedSource Editor(SM, LangOpts);
2078 for (ArrayRef<EditEntry>::iterator
2079 I = Edits.begin(), E = Edits.end(); I != E; ++I) {
2080 const EditEntry &Entry = *I;
2081 assert(Entry.File == FE);
2082 SourceLocation Loc =
2083 SM.getLocForStartOfFile(FID).getLocWithOffset(Entry.Offset);
2084 CharSourceRange Range;
2085 if (Entry.RemoveLen != 0) {
2086 Range = CharSourceRange::getCharRange(Loc,
2087 Loc.getLocWithOffset(Entry.RemoveLen));
2088 }
2089
2090 edit::Commit commit(Editor);
2091 if (Range.isInvalid()) {
2092 commit.insert(Loc, Entry.Text);
2093 } else if (Entry.Text.empty()) {
2094 commit.remove(Range);
2095 } else {
2096 commit.replace(Range, Entry.Text);
2097 }
2098 Editor.commit(commit);
2099 }
2100
2101 Rewriter rewriter(SM, LangOpts);
2102 RewritesReceiver Rec(rewriter);
2103 Editor.applyRewrites(Rec);
2104
2105 const RewriteBuffer *Buf = rewriter.getRewriteBufferFor(FID);
2106 SmallString<512> NewText;
2107 llvm::raw_svector_ostream OS(NewText);
2108 Buf->write(OS);
2109 OS.flush();
2110
2111 SmallString<64> TempPath;
2112 int FD;
2113 if (fs::createTemporaryFile(path::filename(FE->getName()),
2114 path::extension(FE->getName()), FD,
2115 TempPath)) {
2116 reportDiag("Could not create file: " + TempPath.str(), Diag);
2117 return std::string();
2118 }
2119
2120 llvm::raw_fd_ostream TmpOut(FD, /*shouldClose=*/true);
2121 TmpOut.write(NewText.data(), NewText.size());
2122 TmpOut.close();
2123
2124 return TempPath.str();
2125}
2126
2127bool arcmt::getFileRemappingsFromFileList(
2128 std::vector<std::pair<std::string,std::string> > &remap,
2129 ArrayRef<StringRef> remapFiles,
2130 DiagnosticConsumer *DiagClient) {
2131 bool hasErrorOccurred = false;
2132
2133 FileSystemOptions FSOpts;
2134 FileManager FileMgr(FSOpts);
2135 RemapFileParser Parser(FileMgr);
2136
2137 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
2138 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
2139 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
2140 DiagClient, /*ShouldOwnClient=*/false));
2141
2142 typedef llvm::DenseMap<const FileEntry *, std::vector<EditEntry> >
2143 FileEditEntriesTy;
2144 FileEditEntriesTy FileEditEntries;
2145
2146 llvm::DenseSet<EditEntry> EntriesSet;
2147
2148 for (ArrayRef<StringRef>::iterator
2149 I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
2150 SmallVector<EditEntry, 16> Entries;
2151 if (Parser.parse(*I, Entries))
2152 continue;
2153
2154 for (SmallVectorImpl<EditEntry>::iterator
2155 EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) {
2156 EditEntry &Entry = *EI;
2157 if (!Entry.File)
2158 continue;
2159 std::pair<llvm::DenseSet<EditEntry>::iterator, bool>
2160 Insert = EntriesSet.insert(Entry);
2161 if (!Insert.second)
2162 continue;
2163
2164 FileEditEntries[Entry.File].push_back(Entry);
2165 }
2166 }
2167
2168 for (FileEditEntriesTy::iterator
2169 I = FileEditEntries.begin(), E = FileEditEntries.end(); I != E; ++I) {
2170 std::string TempFile = applyEditsToTemp(I->first, I->second,
2171 FileMgr, *Diags);
2172 if (TempFile.empty()) {
2173 hasErrorOccurred = true;
2174 continue;
2175 }
2176
2177 remap.push_back(std::make_pair(I->first->getName(), TempFile));
2178 }
2179
2180 return hasErrorOccurred;
2181}