blob: f6cc19a73788a99adffa63383a55d47af0920446 [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"
Ted Kremenekf7639e12012-03-06 20:06:33 +000011#include "clang/ARCMigrate/ARCMTActions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000012#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/NSAPI.h"
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +000015#include "clang/AST/ParentMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/RecursiveASTVisitor.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Edit/Commit.h"
19#include "clang/Edit/EditedSource.h"
20#include "clang/Edit/EditsReceiver.h"
21#include "clang/Edit/Rewriters.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000022#include "clang/Frontend/CompilerInstance.h"
23#include "clang/Frontend/MultiplexConsumer.h"
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000024#include "clang/Lex/PPConditionalDirectiveRecord.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Rewrite/Core/Rewriter.h"
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +000027#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000028#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000029#include "clang/AST/Attr.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000030#include "llvm/ADT/SmallString.h"
31
32using namespace clang;
33using namespace arcmt;
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000034using namespace ento::objc_retain;
Ted Kremenekf7639e12012-03-06 20:06:33 +000035
36namespace {
37
38class ObjCMigrateASTConsumer : public ASTConsumer {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000039 enum CF_BRIDGING_KIND {
40 CF_BRIDGING_NONE,
41 CF_BRIDGING_ENABLE,
42 CF_BRIDGING_MAY_INCLUDE
43 };
44
Ted Kremenekf7639e12012-03-06 20:06:33 +000045 void migrateDecl(Decl *D);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000046 void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCContainerDecl *D);
Fariborz Jahaniand41dbad2013-10-31 16:10:44 +000047 void migrateDeprecatedAnnotation(ASTContext &Ctx, ObjCCategoryDecl *CatDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +000048 void migrateProtocolConformance(ASTContext &Ctx,
49 const ObjCImplementationDecl *ImpDecl);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +000050 void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +000051 bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
Fariborz Jahanian92463272013-07-18 20:11:45 +000052 const TypedefDecl *TypedefDcl);
Fariborz Jahanian8c45e282013-10-02 22:49:59 +000053 void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000054 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
55 ObjCMethodDecl *OM);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000056 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +000057 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
Fariborz Jahanian10b74352013-09-24 20:20:52 +000058 void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000059 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000060 ObjCMethodDecl *OM,
61 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000062
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000063 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000064 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000065 const FunctionDecl *FuncDecl, bool ResultAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000066 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000067 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000068
Fariborz Jahanian301b5212013-08-20 22:42:13 +000069 void AnnotateImplicitBridging(ASTContext &Ctx);
70
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000071 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
72 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000073
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000074 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
75
Fariborz Jahanian89f6d102013-09-04 00:10:06 +000076 void migrateAddMethodAnnotation(ASTContext &Ctx,
77 const ObjCMethodDecl *MethodDecl);
Ted Kremenekf7639e12012-03-06 20:06:33 +000078public:
79 std::string MigrateDir;
Fariborz Jahanian182486c2013-10-02 17:08:12 +000080 unsigned ASTMigrateActions;
Fariborz Jahanianb8343522013-08-20 23:35:26 +000081 unsigned FileId;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +000082 const TypedefDecl *NSIntegerTypedefed;
83 const TypedefDecl *NSUIntegerTypedefed;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000084 OwningPtr<NSAPI> NSAPIObj;
85 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000086 FileRemapper &Remapper;
87 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000088 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000089 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000090 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000091 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000092 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000093
Ted Kremenekf7639e12012-03-06 20:06:33 +000094 ObjCMigrateASTConsumer(StringRef migrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +000095 unsigned astMigrateActions,
Ted Kremenekf7639e12012-03-06 20:06:33 +000096 FileRemapper &remapper,
97 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000098 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000099 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000100 bool isOutputFile = false)
101 : MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000102 ASTMigrateActions(astMigrateActions),
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000103 FileId(0), NSIntegerTypedefed(0), NSUIntegerTypedefed(0),
104 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000105 IsOutputFile(isOutputFile) { }
106
107protected:
108 virtual void Initialize(ASTContext &Context) {
109 NSAPIObj.reset(new NSAPI(Context));
110 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000111 Context.getLangOpts(),
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +0000112 PPRec, false));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000113 }
114
115 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
116 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
117 migrateDecl(*I);
118 return true;
119 }
120 virtual void HandleInterestingDecl(DeclGroupRef DG) {
121 // Ignore decls from the PCH.
122 }
123 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
124 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
125 }
126
127 virtual void HandleTranslationUnit(ASTContext &Ctx);
128};
129
130}
131
132ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000133 StringRef migrateDir,
134 unsigned migrateAction)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000135 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000136 ObjCMigAction(migrateAction),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000137 CompInst(0) {
138 if (MigrateDir.empty())
139 MigrateDir = "."; // user current directory if none is given.
140}
141
142ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
143 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000144 PPConditionalDirectiveRecord *
145 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
146 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000147 ASTConsumer *
148 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
149 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000150 ObjCMigAction,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000151 Remapper,
152 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000153 PPRec,
154 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000155 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
156 return new MultiplexConsumer(Consumers);
157}
158
159bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
160 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
161 /*ignoreIfFilesChanges=*/true);
162 CompInst = &CI;
163 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000164 return true;
165}
166
167namespace {
168class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
169 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000170 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000171
172public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000173 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
174 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000175
176 bool shouldVisitTemplateInstantiations() const { return false; }
177 bool shouldWalkTypesOfTypeLocs() const { return false; }
178
179 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000180 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000181 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000182 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000183 Consumer.Editor->commit(commit);
184 }
185
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000186 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000187 edit::Commit commit(*Consumer.Editor);
188 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
189 Consumer.Editor->commit(commit);
190 }
191
192 return true;
193 }
194
195 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
196 // Do depth first; we want to rewrite the subexpressions first so that if
197 // we have to move expressions we will move them already rewritten.
198 for (Stmt::child_range range = E->children(); range; ++range)
199 if (!TraverseStmt(*range))
200 return false;
201
202 return WalkUpFromObjCMessageExpr(E);
203 }
204};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000205
206class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
207 ObjCMigrateASTConsumer &Consumer;
208 OwningPtr<ParentMap> PMap;
209
210public:
211 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
212
213 bool shouldVisitTemplateInstantiations() const { return false; }
214 bool shouldWalkTypesOfTypeLocs() const { return false; }
215
216 bool TraverseStmt(Stmt *S) {
217 PMap.reset(new ParentMap(S));
218 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
219 return true;
220 }
221};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000222}
223
224void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
225 if (!D)
226 return;
227 if (isa<ObjCMethodDecl>(D))
228 return; // Wait for the ObjC container declaration.
229
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000230 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000231}
232
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000233static void append_attr(std::string &PropertyString, const char *attr,
234 bool &LParenAdded) {
235 if (!LParenAdded) {
236 PropertyString += "(";
237 LParenAdded = true;
238 }
239 else
240 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000241 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000242}
243
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000244static
245void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
246 const std::string& TypeString,
247 const char *name) {
248 const char *argPtr = TypeString.c_str();
249 int paren = 0;
250 while (*argPtr) {
251 switch (*argPtr) {
252 case '(':
253 PropertyString += *argPtr;
254 paren++;
255 break;
256 case ')':
257 PropertyString += *argPtr;
258 paren--;
259 break;
260 case '^':
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000261 case '*':
262 PropertyString += (*argPtr);
263 if (paren == 1) {
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000264 PropertyString += name;
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000265 name = "";
266 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000267 break;
268 default:
269 PropertyString += *argPtr;
270 break;
271 }
272 argPtr++;
273 }
274}
275
276
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000277static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000278 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000279 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000280 unsigned LengthOfPrefix,
281 bool Atomic) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000282 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000283 bool LParenAdded = false;
284 std::string PropertyString = "@property ";
285 if (!Atomic) {
286 PropertyString += "(nonatomic";
287 LParenAdded = true;
288 }
289
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000290 std::string PropertyNameString = Getter->getNameAsString();
291 StringRef PropertyName(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000292 if (LengthOfPrefix > 0) {
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000293 if (!LParenAdded) {
294 PropertyString += "(getter=";
295 LParenAdded = true;
296 }
297 else
298 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000299 PropertyString += PropertyNameString;
300 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000301 // Property with no setter may be suggested as a 'readonly' property.
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000302 if (!Setter) {
303 if (!LParenAdded) {
304 PropertyString += "(readonly";
305 LParenAdded = true;
306 }
307 else
308 append_attr(PropertyString, "readonly", LParenAdded);
309 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000310
Fariborz Jahanian33304e302013-10-16 18:52:17 +0000311 // Short circuit 'delegate' properties that contain the name "delegate" or
312 // "dataSource", or have exact name "target" to have 'assign' attribute.
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000313 if (PropertyName.equals("target") ||
314 (PropertyName.find("delegate") != StringRef::npos) ||
Fariborz Jahanian78bff052013-10-16 20:44:26 +0000315 (PropertyName.find("dataSource") != StringRef::npos)) {
316 QualType QT = Getter->getResultType();
317 if (!QT->isRealType())
318 append_attr(PropertyString, "assign", LParenAdded);
319 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000320 else if (Setter) {
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000321 const ParmVarDecl *argDecl = *Setter->param_begin();
322 QualType ArgType = Context.getCanonicalType(argDecl->getType());
323 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
324 bool RetainableObject = ArgType->isObjCRetainableType();
325 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
326 if (const ObjCObjectPointerType *ObjPtrTy =
327 ArgType->getAs<ObjCObjectPointerType>()) {
328 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
329 if (IDecl &&
330 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000331 append_attr(PropertyString, "copy", LParenAdded);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000332 else
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000333 append_attr(PropertyString, "retain", LParenAdded);
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000334 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000335 else if (ArgType->isBlockPointerType())
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000336 append_attr(PropertyString, "copy", LParenAdded);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000337 } else if (propertyLifetime == Qualifiers::OCL_Weak)
338 // TODO. More precise determination of 'weak' attribute requires
339 // looking into setter's implementation for backing weak ivar.
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000340 append_attr(PropertyString, "weak", LParenAdded);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000341 else if (RetainableObject)
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000342 append_attr(PropertyString,
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000343 ArgType->isBlockPointerType() ? "copy" : "retain", LParenAdded);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000344 }
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000345 if (LParenAdded)
346 PropertyString += ')';
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000347 QualType RT = Getter->getResultType();
348 if (!isa<TypedefType>(RT)) {
349 // strip off any ARC lifetime qualifier.
350 QualType CanResultTy = Context.getCanonicalType(RT);
351 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
352 Qualifiers Qs = CanResultTy.getQualifiers();
353 Qs.removeObjCLifetime();
354 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
355 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000356 }
357 PropertyString += " ";
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000358 PrintingPolicy SubPolicy(Context.getPrintingPolicy());
359 SubPolicy.SuppressStrongLifetime = true;
Fariborz Jahaniande557f82013-10-09 17:37:28 +0000360 SubPolicy.SuppressLifetimeQualifiers = true;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000361 std::string TypeString = RT.getAsString(SubPolicy);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000362 if (LengthOfPrefix > 0) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000363 // property name must strip off "is" and lower case the first character
364 // after that; e.g. isContinuous will become continuous.
365 StringRef PropertyNameStringRef(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000366 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000367 PropertyNameString = PropertyNameStringRef;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000368 bool NoLowering = (isUppercase(PropertyNameString[0]) &&
369 PropertyNameString.size() > 1 &&
370 isUppercase(PropertyNameString[1]));
Fariborz Jahanian34fea362013-09-11 18:27:16 +0000371 if (!NoLowering)
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000372 PropertyNameString[0] = toLowercase(PropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000373 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000374 if (RT->isBlockPointerType() || RT->isFunctionPointerType())
375 MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
376 TypeString,
377 PropertyNameString.c_str());
378 else {
379 char LastChar = TypeString[TypeString.size()-1];
380 PropertyString += TypeString;
381 if (LastChar != '*')
382 PropertyString += ' ';
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000383 PropertyString += PropertyNameString;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000384 }
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000385 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
386 Selector GetterSelector = Getter->getSelector();
387
388 SourceLocation EndGetterSelectorLoc =
389 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000390 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000391 EndGetterSelectorLoc),
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000392 PropertyString);
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000393 if (Setter) {
394 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
395 // Get location past ';'
396 EndLoc = EndLoc.getLocWithOffset(1);
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000397 SourceLocation BeginOfSetterDclLoc = Setter->getLocStart();
398 // FIXME. This assumes that setter decl; is immediately preceeded by eoln.
399 // It is trying to remove the setter method decl. line entirely.
400 BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
401 commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000402 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000403}
404
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000405void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000406 ObjCContainerDecl *D) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000407 if (D->isDeprecated())
408 return;
409
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000410 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
411 M != MEnd; ++M) {
412 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000413 if (Method->isDeprecated())
414 continue;
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000415 migrateProperty(Ctx, D, Method);
Fariborz Jahanian8c45e282013-10-02 22:49:59 +0000416 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
417 migrateNsReturnsInnerPointer(Ctx, Method);
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000418 }
419 for (ObjCContainerDecl::prop_iterator P = D->prop_begin(),
420 E = D->prop_end(); P != E; ++P) {
421 ObjCPropertyDecl *Prop = *P;
Fariborz Jahanian8c45e282013-10-02 22:49:59 +0000422 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000423 !Prop->isDeprecated())
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000424 migratePropertyNsReturnsInnerPointer(Ctx, Prop);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000425 }
426}
427
Fariborz Jahaniand41dbad2013-10-31 16:10:44 +0000428void ObjCMigrateASTConsumer::migrateDeprecatedAnnotation(ASTContext &Ctx,
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000429 ObjCCategoryDecl *CatDecl) {
430 StringRef Name = CatDecl->getName();
Fariborz Jahaniand41dbad2013-10-31 16:10:44 +0000431 if (!Name.endswith("Deprecated"))
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000432 return;
433
434 if (!Ctx.Idents.get("DEPRECATED").hasMacroDefinition())
435 return;
436
437 ObjCContainerDecl *D = cast<ObjCContainerDecl>(CatDecl);
438
439 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
440 M != MEnd; ++M) {
441 ObjCMethodDecl *Method = (*M);
442 if (Method->isDeprecated() || Method->isImplicit())
443 continue;
444 // Annotate with DEPRECATED
445 edit::Commit commit(*Editor);
446 commit.insertBefore(Method->getLocEnd(), " DEPRECATED");
447 Editor->commit(commit);
448 }
449 for (ObjCContainerDecl::prop_iterator P = D->prop_begin(),
450 E = D->prop_end(); P != E; ++P) {
451 ObjCPropertyDecl *Prop = *P;
452 if (Prop->isDeprecated())
453 continue;
454 // Annotate with DEPRECATED
455 edit::Commit commit(*Editor);
456 commit.insertAfterToken(Prop->getLocEnd(), " DEPRECATED");
457 Editor->commit(commit);
458 }
459}
460
461static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000462ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000463 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000464 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000465 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000466 // In auto-synthesis, protocol properties are not synthesized. So,
467 // a conforming protocol must have its required properties declared
468 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000469 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000470 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
471 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
472 E = PDecl->prop_end(); P != E; ++P) {
473 ObjCPropertyDecl *Property = *P;
474 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
475 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000476 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000477 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000478 if (R.size() == 0) {
479 // Relax the rule and look into class's implementation for a synthesize
480 // or dynamic declaration. Class is implementing a property coming from
481 // another protocol. This still makes the target protocol as conforming.
482 if (!ImpDecl->FindPropertyImplDecl(
483 Property->getDeclName().getAsIdentifierInfo()))
484 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000485 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000486 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
487 if ((ClassProperty->getPropertyAttributes()
488 != Property->getPropertyAttributes()) ||
489 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
490 return false;
491 }
492 else
493 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000494 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000495
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000496 // At this point, all required properties in this protocol conform to those
497 // declared in the class.
498 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000499 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000500 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
501 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000502 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000503 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
504 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
505 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000506 if (MD->isImplicit())
507 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000508 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
509 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000510 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000511 if (R.size() == 0)
512 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000513 bool match = false;
514 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000515 for (unsigned I = 0, N = R.size(); I != N; ++I)
516 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
517 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
518 match = true;
519 break;
520 }
521 if (!match)
522 return false;
523 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000524 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000525 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
526 return true;
527 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000528}
529
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000530static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
531 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
532 const NSAPI &NS, edit::Commit &commit) {
533 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
534 std::string ClassString;
535 SourceLocation EndLoc =
536 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
537
538 if (Protocols.empty()) {
539 ClassString = '<';
540 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
541 ClassString += ConformingProtocols[i]->getNameAsString();
542 if (i != (e-1))
543 ClassString += ", ";
544 }
545 ClassString += "> ";
546 }
547 else {
548 ClassString = ", ";
549 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
550 ClassString += ConformingProtocols[i]->getNameAsString();
551 if (i != (e-1))
552 ClassString += ", ";
553 }
554 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
555 EndLoc = *PL;
556 }
557
558 commit.insertAfterToken(EndLoc, ClassString);
559 return true;
560}
561
562static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
563 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000564 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000565 bool IsNSIntegerType,
566 bool NSOptions) {
567 std::string ClassString;
568 if (NSOptions)
569 ClassString = "typedef NS_OPTIONS(NSUInteger, ";
570 else
571 ClassString =
572 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, "
573 : "typedef NS_ENUM(NSUInteger, ";
574
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000575 ClassString += TypedefDcl->getIdentifier()->getName();
576 ClassString += ')';
577 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
578 commit.replace(R, ClassString);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000579 SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
580 EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
581 NS.getASTContext(), /*IsDecl*/true);
582 if (!EndOfEnumDclLoc.isInvalid()) {
583 SourceRange EnumDclRange(EnumDcl->getLocStart(), EndOfEnumDclLoc);
584 commit.insertFromRange(TypedefDcl->getLocStart(), EnumDclRange);
585 }
586 else
587 return false;
588
589 SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
590 EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
591 NS.getASTContext(), /*IsDecl*/true);
592 if (!EndTypedefDclLoc.isInvalid()) {
593 SourceRange TDRange(TypedefDcl->getLocStart(), EndTypedefDclLoc);
594 commit.remove(TDRange);
595 }
596 else
597 return false;
598
599 EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
Fariborz Jahanian1d27ffd2013-10-11 17:35:22 +0000600 /*IsDecl*/true);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000601 if (!EndOfEnumDclLoc.isInvalid()) {
602 SourceLocation BeginOfEnumDclLoc = EnumDcl->getLocStart();
603 // FIXME. This assumes that enum decl; is immediately preceeded by eoln.
604 // It is trying to remove the enum decl. lines entirely.
605 BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
606 commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000607 return true;
608 }
609 return false;
610}
611
Fariborz Jahanian403425b2013-10-17 23:13:13 +0000612static void rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000613 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000614 const NSAPI &NS, edit::Commit &commit,
615 bool IsNSIntegerType) {
616 std::string ClassString =
617 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000618 ClassString += TypedefDcl->getIdentifier()->getName();
619 ClassString += ')';
620 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
621 commit.replace(R, ClassString);
622 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
623 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000624}
625
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000626static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000627 const EnumDecl *EnumDcl) {
628 bool PowerOfTwo = true;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000629 bool AllHexdecimalEnumerator = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000630 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000631 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
632 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
633 EnumConstantDecl *Enumerator = (*EI);
634 const Expr *InitExpr = Enumerator->getInitExpr();
635 if (!InitExpr) {
636 PowerOfTwo = false;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000637 AllHexdecimalEnumerator = false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000638 continue;
639 }
Fariborz Jahanian6e1798e2013-09-17 23:32:51 +0000640 InitExpr = InitExpr->IgnoreParenCasts();
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000641 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
642 if (BO->isShiftOp() || BO->isBitwiseOp())
643 return true;
644
645 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000646 if (PowerOfTwo && EnumVal) {
647 if (!llvm::isPowerOf2_64(EnumVal))
648 PowerOfTwo = false;
649 else if (EnumVal > MaxPowerOfTwoVal)
650 MaxPowerOfTwoVal = EnumVal;
651 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000652 if (AllHexdecimalEnumerator && EnumVal) {
653 bool FoundHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000654 SourceLocation EndLoc = Enumerator->getLocEnd();
655 Token Tok;
656 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
657 if (Tok.isLiteral() && Tok.getLength() > 2) {
658 if (const char *StringLit = Tok.getLiteralData())
659 FoundHexdecimalEnumerator =
660 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
661 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000662 if (!FoundHexdecimalEnumerator)
663 AllHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000664 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000665 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000666 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000667}
668
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000669void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000670 const ObjCImplementationDecl *ImpDecl) {
671 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000672 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000673 return;
674 // Find all implicit conforming protocols for this class
675 // and make them explicit.
676 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
677 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000678 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000679
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000680 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000681 ObjCProtocolDecls.begin(),
682 E = ObjCProtocolDecls.end(); I != E; ++I)
683 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000684 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000685
686 if (PotentialImplicitProtocols.empty())
687 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000688
689 // go through list of non-optional methods and properties in each protocol
690 // in the PotentialImplicitProtocols list. If class implements every one of the
691 // methods and properties, then this class conforms to this protocol.
692 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
693 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000694 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000695 PotentialImplicitProtocols[i]))
696 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000697
698 if (ConformingProtocols.empty())
699 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000700
701 // Further reduce number of conforming protocols. If protocol P1 is in the list
702 // protocol P2 (P2<P1>), No need to include P1.
703 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
704 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
705 bool DropIt = false;
706 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
707 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
708 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
709 if (PDecl == TargetPDecl)
710 continue;
711 if (PDecl->lookupProtocolNamed(
712 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
713 DropIt = true;
714 break;
715 }
716 }
717 if (!DropIt)
718 MinimalConformingProtocols.push_back(TargetPDecl);
719 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000720 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000721 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
722 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000723 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000724}
725
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000726void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
727 const TypedefDecl *TypedefDcl) {
728
729 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
730 if (NSAPIObj->isObjCNSIntegerType(qt))
731 NSIntegerTypedefed = TypedefDcl;
732 else if (NSAPIObj->isObjCNSUIntegerType(qt))
733 NSUIntegerTypedefed = TypedefDcl;
734}
735
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000736bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
Fariborz Jahanian92463272013-07-18 20:11:45 +0000737 const EnumDecl *EnumDcl,
738 const TypedefDecl *TypedefDcl) {
739 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000740 EnumDcl->isDeprecated())
741 return false;
742 if (!TypedefDcl) {
743 if (NSIntegerTypedefed) {
744 TypedefDcl = NSIntegerTypedefed;
745 NSIntegerTypedefed = 0;
746 }
747 else if (NSUIntegerTypedefed) {
748 TypedefDcl = NSUIntegerTypedefed;
749 NSUIntegerTypedefed = 0;
750 }
751 else
752 return false;
753 unsigned FileIdOfTypedefDcl =
754 PP.getSourceManager().getFileID(TypedefDcl->getLocation()).getHashValue();
755 unsigned FileIdOfEnumDcl =
756 PP.getSourceManager().getFileID(EnumDcl->getLocation()).getHashValue();
757 if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
758 return false;
759 }
760 if (TypedefDcl->isDeprecated())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000761 return false;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000762
763 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000764 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
765 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000766
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000767 if (!IsNSIntegerType && !IsNSUIntegerType) {
768 // Also check for typedef enum {...} TD;
769 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
770 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000771 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000772 if (NSOptions) {
773 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000774 return false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000775 }
776 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000777 return false;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000778 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000779 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000780 Editor->commit(commit);
Fariborz Jahaniande79e812013-10-17 22:23:32 +0000781 return true;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000782 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000783 }
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000784 return false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000785 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000786
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000787 // We may still use NS_OPTIONS based on what we find in the enumertor list.
788 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000789 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000790 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000791 return false;
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000792 // NS_OPTIONS must be available.
793 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000794 return false;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000795 edit::Commit commit(*Editor);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000796 bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
797 commit, IsNSIntegerType, NSOptions);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000798 Editor->commit(commit);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000799 return Res;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000800}
801
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000802static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
803 ObjCMethodDecl *OM) {
804 SourceRange R;
805 std::string ClassString;
806 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
807 TypeLoc TL = TSInfo->getTypeLoc();
808 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
809 ClassString = "instancetype";
810 }
811 else {
812 R = SourceRange(OM->getLocStart(), OM->getLocStart());
813 ClassString = OM->isInstanceMethod() ? '-' : '+';
814 ClassString += " (instancetype)";
815 }
816 edit::Commit commit(*ASTC.Editor);
817 commit.replace(R, ClassString);
818 ASTC.Editor->commit(commit);
819}
820
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000821static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
822 ObjCMethodDecl *OM) {
823 ObjCInterfaceDecl *IDecl = OM->getClassInterface();
824 SourceRange R;
825 std::string ClassString;
826 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
827 TypeLoc TL = TSInfo->getTypeLoc();
828 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
829 ClassString = IDecl->getName();
830 ClassString += "*";
831 }
832 }
833 else {
834 R = SourceRange(OM->getLocStart(), OM->getLocStart());
835 ClassString = "+ (";
836 ClassString += IDecl->getName(); ClassString += "*)";
837 }
838 edit::Commit commit(*ASTC.Editor);
839 commit.replace(R, ClassString);
840 ASTC.Editor->commit(commit);
841}
842
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000843void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
844 ObjCContainerDecl *CDecl,
845 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +0000846 ObjCInstanceTypeFamily OIT_Family =
847 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000848
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000849 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000850 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000851 case OIT_None:
852 migrateFactoryMethod(Ctx, CDecl, OM);
853 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000854 case OIT_Array:
855 ClassName = "NSArray";
856 break;
857 case OIT_Dictionary:
858 ClassName = "NSDictionary";
859 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000860 case OIT_Singleton:
861 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000862 return;
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +0000863 case OIT_Init:
864 if (OM->getResultType()->isObjCIdType())
865 ReplaceWithInstancetype(*this, OM);
866 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000867 case OIT_ReturnsSelf:
868 migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
869 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000870 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000871 if (!OM->getResultType()->isObjCIdType())
872 return;
873
874 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
875 if (!IDecl) {
876 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
877 IDecl = CatDecl->getClassInterface();
878 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
879 IDecl = ImpDecl->getClassInterface();
880 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000881 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000882 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
883 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000884 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000885 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000886 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000887}
888
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000889static bool TypeIsInnerPointer(QualType T) {
890 if (!T->isAnyPointerType())
891 return false;
892 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
Fariborz Jahanian73466ca2013-09-26 21:43:47 +0000893 T->isBlockPointerType() || T->isFunctionPointerType() ||
894 ento::coreFoundation::isCFObjectRef(T))
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000895 return false;
Fariborz Jahanian9d5fffb2013-09-09 23:56:14 +0000896 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
897 // is not an innter pointer type.
898 QualType OrigT = T;
899 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
900 T = TD->getDecl()->getUnderlyingType();
901 if (OrigT == T || !T->isPointerType())
902 return true;
903 const PointerType* PT = T->getAs<PointerType>();
904 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
905 if (UPointeeT->isRecordType()) {
906 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
907 if (!RecordTy->getDecl()->isCompleteDefinition())
908 return false;
909 }
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000910 return true;
911}
912
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000913static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2) {
914 if (Decl1->hasAttrs() != Decl2->hasAttrs())
915 return false;
916
917 if (!Decl1->hasAttrs())
918 return true;
919
920 const AttrVec &Attrs1 = Decl1->getAttrs();
921 const AttrVec &Attrs2 = Decl2->getAttrs();
922 // This list is very small, so this need not be optimized.
923 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
924 bool match = false;
925 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
926 // Matching attribute kind only. We are not getting into
927 // details of the attributes. For all practical purposes
928 // this is sufficient.
929 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
930 match = true;
931 break;
932 }
933 }
934 if (!match)
935 return false;
936 }
937 return true;
938}
939
Fariborz Jahanian5d783df2013-09-27 22:55:54 +0000940static bool IsValidIdentifier(ASTContext &Ctx,
941 const char *Name) {
942 if (!isIdentifierHead(Name[0]))
943 return false;
944 std::string NameString = Name;
945 NameString[0] = toLowercase(NameString[0]);
946 IdentifierInfo *II = &Ctx.Idents.get(NameString);
947 return II->getTokenID() == tok::identifier;
948}
949
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000950bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000951 ObjCContainerDecl *D,
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000952 ObjCMethodDecl *Method) {
953 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
954 Method->param_size() != 0)
955 return false;
956 // Is this method candidate to be a getter?
957 QualType GRT = Method->getResultType();
958 if (GRT->isVoidType())
959 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000960
961 Selector GetterSelector = Method->getSelector();
Fariborz Jahanian7391a7b5a2013-09-25 00:17:07 +0000962 ObjCInstanceTypeFamily OIT_Family =
963 Selector::getInstTypeMethodFamily(GetterSelector);
964
965 if (OIT_Family != OIT_None)
966 return false;
967
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000968 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
969 Selector SetterSelector =
970 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
971 PP.getSelectorTable(),
972 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000973 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000974 unsigned LengthOfPrefix = 0;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000975 if (!SetterMethod) {
976 // try a different naming convention for getter: isXxxxx
977 StringRef getterNameString = getterName->getName();
Fariborz Jahanianca399602013-09-11 17:05:15 +0000978 bool IsPrefix = getterNameString.startswith("is");
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +0000979 // Note that we don't want to change an isXXX method of retainable object
980 // type to property (readonly or otherwise).
981 if (IsPrefix && GRT->isObjCRetainableType())
982 return false;
983 if (IsPrefix || getterNameString.startswith("get")) {
Fariborz Jahanianca399602013-09-11 17:05:15 +0000984 LengthOfPrefix = (IsPrefix ? 2 : 3);
985 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
986 // Make sure that first character after "is" or "get" prefix can
987 // start an identifier.
Fariborz Jahanian5d783df2013-09-27 22:55:54 +0000988 if (!IsValidIdentifier(Ctx, CGetterName))
Fariborz Jahanianca399602013-09-11 17:05:15 +0000989 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000990 if (CGetterName[0] && isUppercase(CGetterName[0])) {
991 getterName = &Ctx.Idents.get(CGetterName);
992 SetterSelector =
993 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
994 PP.getSelectorTable(),
995 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000996 SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000997 }
998 }
999 }
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +00001000
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001001 if (SetterMethod) {
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001002 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
1003 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001004 if (SetterMethod->isDeprecated() ||
1005 !AttributesMatch(Method, SetterMethod))
Fariborz Jahanianf6c65052013-09-17 22:41:25 +00001006 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001007
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001008 // Is this a valid setter, matching the target getter?
1009 QualType SRT = SetterMethod->getResultType();
1010 if (!SRT->isVoidType())
1011 return false;
1012 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
1013 QualType ArgType = argDecl->getType();
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001014 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001015 return false;
1016 edit::Commit commit(*Editor);
1017 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001018 LengthOfPrefix,
1019 (ASTMigrateActions &
1020 FrontendOptions::ObjCMT_AtomicProperty) != 0);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001021 Editor->commit(commit);
1022 return true;
1023 }
Fariborz Jahanian182486c2013-10-02 17:08:12 +00001024 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001025 // Try a non-void method with no argument (and no setter or property of same name
1026 // as a 'readonly' property.
1027 edit::Commit commit(*Editor);
1028 rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001029 LengthOfPrefix,
1030 (ASTMigrateActions &
1031 FrontendOptions::ObjCMT_AtomicProperty) != 0);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001032 Editor->commit(commit);
1033 return true;
1034 }
1035 return false;
1036}
1037
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001038void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
1039 ObjCMethodDecl *OM) {
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001040 if (OM->isImplicit() ||
Fariborz Jahanian7c1a4452013-09-26 22:43:41 +00001041 !OM->isInstanceMethod() ||
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001042 OM->hasAttr<ObjCReturnsInnerPointerAttr>())
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001043 return;
1044
1045 QualType RT = OM->getResultType();
1046 if (!TypeIsInnerPointer(RT) ||
1047 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
1048 return;
1049
1050 edit::Commit commit(*Editor);
1051 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
1052 Editor->commit(commit);
1053}
1054
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001055void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
1056 ObjCPropertyDecl *P) {
1057 QualType T = P->getType();
1058
1059 if (!TypeIsInnerPointer(T) ||
1060 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
1061 return;
1062 edit::Commit commit(*Editor);
1063 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
1064 Editor->commit(commit);
1065}
1066
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001067void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
Fariborz Jahanian71221352013-07-23 22:42:28 +00001068 ObjCContainerDecl *CDecl) {
Fariborz Jahaniane47a14a2013-09-18 15:43:52 +00001069 if (CDecl->isDeprecated())
1070 return;
1071
Fariborz Jahanian71221352013-07-23 22:42:28 +00001072 // migrate methods which can have instancetype as their result type.
1073 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1074 MEnd = CDecl->meth_end();
1075 M != MEnd; ++M) {
1076 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001077 if (Method->isDeprecated())
1078 continue;
Fariborz Jahanian71221352013-07-23 22:42:28 +00001079 migrateMethodInstanceType(Ctx, CDecl, Method);
1080 }
1081}
1082
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001083void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
1084 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001085 ObjCMethodDecl *OM,
1086 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +00001087 if (OM->isInstanceMethod() ||
1088 OM->getResultType() == Ctx.getObjCInstanceType() ||
1089 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001090 return;
1091
1092 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1093 // NSYYYNamE with matching names be at least 3 characters long.
1094 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1095 if (!IDecl) {
1096 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1097 IDecl = CatDecl->getClassInterface();
1098 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1099 IDecl = ImpDecl->getClassInterface();
1100 }
1101 if (!IDecl)
1102 return;
1103
1104 std::string StringClassName = IDecl->getName();
1105 StringRef LoweredClassName(StringClassName);
1106 std::string StringLoweredClassName = LoweredClassName.lower();
1107 LoweredClassName = StringLoweredClassName;
1108
1109 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001110 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1111 if (!MethodIdName)
1112 return;
1113
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001114 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001115 if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001116 StringRef STRefMethodName(MethodName);
1117 size_t len = 0;
1118 if (STRefMethodName.startswith("standard"))
1119 len = strlen("standard");
1120 else if (STRefMethodName.startswith("shared"))
1121 len = strlen("shared");
1122 else if (STRefMethodName.startswith("default"))
1123 len = strlen("default");
1124 else
1125 return;
1126 MethodName = STRefMethodName.substr(len);
1127 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001128 std::string MethodNameSubStr = MethodName.substr(0, 3);
1129 StringRef MethodNamePrefix(MethodNameSubStr);
1130 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1131 MethodNamePrefix = StringLoweredMethodNamePrefix;
1132 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1133 if (Ix == StringRef::npos)
1134 return;
1135 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1136 StringRef LoweredMethodName(MethodName);
1137 std::string StringLoweredMethodName = LoweredMethodName.lower();
1138 LoweredMethodName = StringLoweredMethodName;
1139 if (!LoweredMethodName.startswith(ClassNamePostfix))
1140 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001141 if (OIT_Family == OIT_ReturnsSelf)
1142 ReplaceWithClasstype(*this, OM);
1143 else
1144 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001145}
1146
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001147static bool IsVoidStarType(QualType Ty) {
1148 if (!Ty->isPointerType())
1149 return false;
1150
1151 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1152 Ty = TD->getDecl()->getUnderlyingType();
1153
1154 // Is the type void*?
1155 const PointerType* PT = Ty->getAs<PointerType>();
1156 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1157 return true;
1158 return IsVoidStarType(PT->getPointeeType());
1159}
1160
Fariborz Jahanian94279392013-08-20 18:54:39 +00001161/// AuditedType - This routine audits the type AT and returns false if it is one of known
1162/// CF object types or of the "void *" variety. It returns true if we don't care about the type
1163/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001164static bool AuditedType (QualType AT) {
1165 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001166 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001167 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +00001168 if (ento::coreFoundation::isCFObjectRef(AT) ||
1169 IsVoidStarType(AT) ||
1170 // If an ObjC object is type, assuming that it is not a CF function and
1171 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +00001172 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001173 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +00001174 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001175 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001176}
1177
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001178void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001179 if (CFFunctionIBCandidates.empty())
1180 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001181 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
1182 CFFunctionIBCandidates.clear();
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001183 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001184 return;
1185 }
1186 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001187 const Decl *FirstFD = CFFunctionIBCandidates[0];
1188 const Decl *LastFD =
1189 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001190 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1191 edit::Commit commit(*Editor);
1192 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
1193 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1194 SourceLocation EndLoc = LastFD->getLocEnd();
1195 // get location just past end of function location.
1196 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001197 if (isa<FunctionDecl>(LastFD)) {
1198 // For Methods, EndLoc points to the ending semcolon. So,
1199 // not of these extra work is needed.
1200 Token Tok;
1201 // get locaiton of token that comes after end of function.
1202 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1203 if (!Failed)
1204 EndLoc = Tok.getLocation();
1205 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001206 commit.insertAfterToken(EndLoc, PragmaString);
1207 Editor->commit(commit);
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001208 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001209 CFFunctionIBCandidates.clear();
1210}
1211
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001212void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001213 if (Decl->isDeprecated())
1214 return;
1215
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001216 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001217 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001218 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001219 "provided CF_IMPLICIT_BRIDGING_ENABLE");
1220 return;
1221 }
1222
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001223 // Finction must be annotated first.
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001224 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1225 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1226 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001227 CFFunctionIBCandidates.push_back(Decl);
1228 if (!FileId)
1229 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1230 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001231 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1232 if (!CFFunctionIBCandidates.empty()) {
1233 CFFunctionIBCandidates.push_back(Decl);
1234 if (!FileId)
1235 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1236 }
1237 }
1238 else
1239 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001240 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001241 else {
1242 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001243 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001244 }
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001245}
1246
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001247void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1248 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001249 const FunctionDecl *FuncDecl,
1250 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001251 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001252 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001253 RetEffect Ret = CE.getReturnValue();
1254 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001255 if (Ret.getObjKind() == RetEffect::CF) {
1256 if (Ret.isOwned() &&
1257 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001258 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001259 else if (Ret.notOwned() &&
1260 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001261 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1262 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001263 else if (Ret.getObjKind() == RetEffect::ObjC) {
1264 if (Ret.isOwned() &&
1265 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1266 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001267 }
1268
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001269 if (AnnotationString) {
1270 edit::Commit commit(*Editor);
1271 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1272 Editor->commit(commit);
1273 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001274 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001275 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1276 unsigned i = 0;
1277 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1278 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +00001279 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001280 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001281 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1282 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1283 edit::Commit commit(*Editor);
1284 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1285 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +00001286 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001287 else if (AE == DecRefMsg && !pd->getAttr<NSConsumedAttr>() &&
1288 Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
1289 edit::Commit commit(*Editor);
1290 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1291 Editor->commit(commit);
1292 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001293 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001294}
1295
1296
1297ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1298 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1299 ASTContext &Ctx,
1300 const FunctionDecl *FuncDecl) {
1301 if (FuncDecl->hasBody())
1302 return CF_BRIDGING_NONE;
1303
1304 CallEffects CE = CallEffects::getEffect(FuncDecl);
1305 bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001306 FuncDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1307 FuncDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001308 FuncDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1309 FuncDecl->getAttr<NSReturnsAutoreleasedAttr>());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001310
1311 // Trivial case of when funciton is annotated and has no argument.
1312 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1313 return CF_BRIDGING_NONE;
1314
1315 bool ReturnCFAudited = false;
1316 if (!FuncIsReturnAnnotated) {
1317 RetEffect Ret = CE.getReturnValue();
1318 if (Ret.getObjKind() == RetEffect::CF &&
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001319 (Ret.isOwned() || Ret.notOwned()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001320 ReturnCFAudited = true;
1321 else if (!AuditedType(FuncDecl->getResultType()))
1322 return CF_BRIDGING_NONE;
1323 }
1324
1325 // At this point result type is audited for potential inclusion.
1326 // Now, how about argument types.
1327 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1328 unsigned i = 0;
1329 bool ArgCFAudited = false;
1330 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1331 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1332 const ParmVarDecl *pd = *pi;
1333 ArgEffect AE = AEArgs[i];
1334 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1335 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
1336 ArgCFAudited = true;
1337 else if (AE == IncRef)
1338 ArgCFAudited = true;
1339 }
1340 else {
1341 QualType AT = pd->getType();
1342 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001343 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001344 return CF_BRIDGING_NONE;
1345 }
1346 }
1347 }
1348 if (ReturnCFAudited || ArgCFAudited)
1349 return CF_BRIDGING_ENABLE;
1350
1351 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001352}
1353
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001354void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1355 ObjCContainerDecl *CDecl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001356 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001357 return;
1358
1359 // migrate methods which can have instancetype as their result type.
1360 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1361 MEnd = CDecl->meth_end();
1362 M != MEnd; ++M) {
1363 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001364 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001365 }
1366}
1367
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001368void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1369 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001370 const ObjCMethodDecl *MethodDecl,
1371 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001372 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001373 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001374 RetEffect Ret = CE.getReturnValue();
1375 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001376 if (Ret.getObjKind() == RetEffect::CF) {
1377 if (Ret.isOwned() &&
1378 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001379 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001380 else if (Ret.notOwned() &&
1381 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001382 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1383 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001384 else if (Ret.getObjKind() == RetEffect::ObjC) {
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001385 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1386 switch (OMF) {
1387 case clang::OMF_alloc:
1388 case clang::OMF_new:
1389 case clang::OMF_copy:
1390 case clang::OMF_init:
1391 case clang::OMF_mutableCopy:
1392 break;
1393
1394 default:
1395 if (Ret.isOwned() &&
1396 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1397 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001398 break;
1399 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001400 }
1401
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001402 if (AnnotationString) {
1403 edit::Commit commit(*Editor);
1404 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1405 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001406 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001407 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001408 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1409 unsigned i = 0;
1410 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1411 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1412 const ParmVarDecl *pd = *pi;
1413 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001414 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1415 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1416 edit::Commit commit(*Editor);
1417 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1418 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001419 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001420 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001421}
1422
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001423void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001424 ASTContext &Ctx,
1425 const ObjCMethodDecl *MethodDecl) {
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001426 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001427 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001428
1429 CallEffects CE = CallEffects::getEffect(MethodDecl);
1430 bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001431 MethodDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1432 MethodDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001433 MethodDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1434 MethodDecl->getAttr<NSReturnsAutoreleasedAttr>());
1435
1436 if (CE.getReceiver() == DecRefMsg &&
1437 !MethodDecl->getAttr<NSConsumesSelfAttr>() &&
1438 MethodDecl->getMethodFamily() != OMF_init &&
1439 MethodDecl->getMethodFamily() != OMF_release &&
1440 Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
1441 edit::Commit commit(*Editor);
1442 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1443 Editor->commit(commit);
1444 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001445
1446 // Trivial case of when funciton is annotated and has no argument.
1447 if (MethodIsReturnAnnotated &&
1448 (MethodDecl->param_begin() == MethodDecl->param_end()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001449 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001450
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001451 if (!MethodIsReturnAnnotated) {
1452 RetEffect Ret = CE.getReturnValue();
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001453 if ((Ret.getObjKind() == RetEffect::CF ||
1454 Ret.getObjKind() == RetEffect::ObjC) &&
1455 (Ret.isOwned() || Ret.notOwned())) {
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001456 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1457 return;
1458 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001459 else if (!AuditedType(MethodDecl->getResultType()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001460 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001461 }
1462
1463 // At this point result type is either annotated or audited.
1464 // Now, how about argument types.
1465 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1466 unsigned i = 0;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001467 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1468 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1469 const ParmVarDecl *pd = *pi;
1470 ArgEffect AE = AEArgs[i];
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001471 if ((AE == DecRef && !pd->getAttr<CFConsumedAttr>()) || AE == IncRef ||
1472 !AuditedType(pd->getType())) {
1473 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1474 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001475 }
1476 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001477 return;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001478}
1479
Ted Kremenekf7639e12012-03-06 20:06:33 +00001480namespace {
1481
1482class RewritesReceiver : public edit::EditsReceiver {
1483 Rewriter &Rewrite;
1484
1485public:
1486 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1487
1488 virtual void insert(SourceLocation loc, StringRef text) {
1489 Rewrite.InsertText(loc, text);
1490 }
1491 virtual void replace(CharSourceRange range, StringRef text) {
1492 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1493 }
1494};
1495
1496}
1497
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001498static bool
1499IsReallyASystemHeader(ASTContext &Ctx, const FileEntry *file, FileID FID) {
1500 bool Invalid = false;
1501 const SrcMgr::SLocEntry &SEntry =
1502 Ctx.getSourceManager().getSLocEntry(FID, &Invalid);
1503 if (!Invalid && SEntry.isFile()) {
1504 const SrcMgr::FileInfo &FI = SEntry.getFile();
1505 if (!FI.hasLineDirectives()) {
1506 if (FI.getFileCharacteristic() == SrcMgr::C_ExternCSystem)
1507 return true;
1508 if (FI.getFileCharacteristic() == SrcMgr::C_System) {
1509 // This file is in a system header directory. Continue with commiting change
1510 // only if it is a user specified system directory because user put a
1511 // .system_framework file in the framework directory.
1512 StringRef Directory(file->getDir()->getName());
1513 size_t Ix = Directory.rfind(".framework");
1514 if (Ix == StringRef::npos)
1515 return true;
1516 std::string PatchToSystemFramework = Directory.slice(0, Ix+sizeof(".framework"));
1517 PatchToSystemFramework += ".system_framework";
1518 if (!llvm::sys::fs::exists(PatchToSystemFramework.data()))
1519 return true;
1520 }
1521 }
1522 }
1523 return false;
1524}
1525
Ted Kremenekf7639e12012-03-06 20:06:33 +00001526void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001527
1528 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001529 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001530 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1531 D != DEnd; ++D) {
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001532 if (unsigned FID =
1533 PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue())
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001534 if (FileId && FileId != FID) {
1535 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1536 AnnotateImplicitBridging(Ctx);
1537 }
1538
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001539 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1540 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001541 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) {
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001542 migrateObjCInterfaceDecl(Ctx, CatDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001543 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
Fariborz Jahaniand41dbad2013-10-31 16:10:44 +00001544 migrateDeprecatedAnnotation(Ctx, CatDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001545 }
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001546 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1547 ObjCProtocolDecls.insert(PDecl);
1548 else if (const ObjCImplementationDecl *ImpDecl =
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001549 dyn_cast<ObjCImplementationDecl>(*D)) {
1550 if (ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance)
1551 migrateProtocolConformance(Ctx, ImpDecl);
1552 }
Fariborz Jahanian92463272013-07-18 20:11:45 +00001553 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001554 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1555 continue;
Fariborz Jahanian92463272013-07-18 20:11:45 +00001556 DeclContext::decl_iterator N = D;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001557 if (++N != DEnd) {
1558 const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
1559 if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
1560 D++;
1561 }
1562 else
1563 migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */0);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001564 }
1565 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001566 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1567 continue;
1568 DeclContext::decl_iterator N = D;
1569 if (++N == DEnd)
1570 continue;
1571 if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001572 if (++N != DEnd)
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001573 if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) {
1574 // prefer typedef-follows-enum to enum-follows-typedef pattern.
1575 if (migrateNSEnumDecl(Ctx, ED, TDF)) {
1576 ++D; ++D;
1577 CacheObjCNSIntegerTypedefed(TD);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001578 continue;
1579 }
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001580 }
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001581 if (migrateNSEnumDecl(Ctx, ED, TD)) {
1582 ++D;
1583 continue;
1584 }
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001585 }
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001586 CacheObjCNSIntegerTypedefed(TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001587 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001588 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
1589 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1590 migrateCFAnnotation(Ctx, FD);
1591 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001592
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001593 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1594 // migrate methods which can have instancetype as their result type.
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001595 if (ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype)
1596 migrateAllMethodInstaceType(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001597 // annotate methods with CF annotations.
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001598 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1599 migrateARCSafeAnnotation(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001600 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001601 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001602 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1603 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001604 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001605
David Blaikiebbafb8a2012-03-11 07:00:24 +00001606 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001607 RewritesReceiver Rec(rewriter);
1608 Editor->applyRewrites(Rec);
1609
1610 for (Rewriter::buffer_iterator
1611 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1612 FileID FID = I->first;
1613 RewriteBuffer &buf = I->second;
1614 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1615 assert(file);
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001616 if (IsReallyASystemHeader(Ctx, file, FID))
1617 continue;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001618 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001619 llvm::raw_svector_ostream vecOS(newText);
1620 buf.write(vecOS);
1621 vecOS.flush();
1622 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1623 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001624 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001625 FileMgr.FixupRelativePath(filePath);
1626 Remapper.remap(filePath.str(), memBuf);
1627 }
1628
1629 if (IsOutputFile) {
1630 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1631 } else {
1632 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1633 }
1634}
1635
1636bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001637 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001638 return true;
1639}
1640
1641ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1642 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001643 PPConditionalDirectiveRecord *
1644 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1645 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001646 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001647 FrontendOptions::ObjCMT_MigrateAll,
Ted Kremenekf7639e12012-03-06 20:06:33 +00001648 Remapper,
1649 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001650 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001651 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +00001652 /*isOutputFile=*/true);
1653}