blob: 9b9d6aa10dbd668cefd7d5ed894466348fec86e9 [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 Jahaniana7437f02013-07-03 23:05:00 +000046 void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCInterfaceDecl *D);
Fariborz Jahanian1be01532013-07-12 22:32:19 +000047 void migrateProtocolConformance(ASTContext &Ctx,
48 const ObjCImplementationDecl *ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +000049 void migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
50 const TypedefDecl *TypedefDcl);
Fariborz Jahanian71221352013-07-23 22:42:28 +000051 void migrateInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000052 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
53 ObjCMethodDecl *OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000054 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000055 ObjCMethodDecl *OM,
56 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000057
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000058 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000059 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000060 const FunctionDecl *FuncDecl, bool ResultAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000061 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000062 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000063
Fariborz Jahanian301b5212013-08-20 22:42:13 +000064 void AnnotateImplicitBridging(ASTContext &Ctx);
65
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000066 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
67 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000068
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000069 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
70
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000071 CF_BRIDGING_KIND migrateAddMethodAnnotation(ASTContext &Ctx,
72 const ObjCMethodDecl *MethodDecl);
Ted Kremenekf7639e12012-03-06 20:06:33 +000073public:
74 std::string MigrateDir;
75 bool MigrateLiterals;
76 bool MigrateSubscripting;
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000077 bool MigrateProperty;
Fariborz Jahanianb8343522013-08-20 23:35:26 +000078 unsigned FileId;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000079 OwningPtr<NSAPI> NSAPIObj;
80 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000081 FileRemapper &Remapper;
82 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000083 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000084 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000085 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000086 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000087 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000088
Ted Kremenekf7639e12012-03-06 20:06:33 +000089 ObjCMigrateASTConsumer(StringRef migrateDir,
90 bool migrateLiterals,
91 bool migrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000092 bool migrateProperty,
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 = false)
98 : MigrateDir(migrateDir),
99 MigrateLiterals(migrateLiterals),
100 MigrateSubscripting(migrateSubscripting),
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000101 MigrateProperty(migrateProperty), FileId(0),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000102 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000103 IsOutputFile(isOutputFile) { }
104
105protected:
106 virtual void Initialize(ASTContext &Context) {
107 NSAPIObj.reset(new NSAPI(Context));
108 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000109 Context.getLangOpts(),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000110 PPRec));
111 }
112
113 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
114 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
115 migrateDecl(*I);
116 return true;
117 }
118 virtual void HandleInterestingDecl(DeclGroupRef DG) {
119 // Ignore decls from the PCH.
120 }
121 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
122 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
123 }
124
125 virtual void HandleTranslationUnit(ASTContext &Ctx);
126};
127
128}
129
130ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
131 StringRef migrateDir,
132 bool migrateLiterals,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000133 bool migrateSubscripting,
134 bool migrateProperty)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000135 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
136 MigrateLiterals(migrateLiterals), MigrateSubscripting(migrateSubscripting),
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000137 MigrateProperty(migrateProperty),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000138 CompInst(0) {
139 if (MigrateDir.empty())
140 MigrateDir = "."; // user current directory if none is given.
141}
142
143ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
144 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000145 PPConditionalDirectiveRecord *
146 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
147 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000148 ASTConsumer *
149 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
150 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
151 MigrateLiterals,
152 MigrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000153 MigrateProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000154 Remapper,
155 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000156 PPRec,
157 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000158 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
159 return new MultiplexConsumer(Consumers);
160}
161
162bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
163 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
164 /*ignoreIfFilesChanges=*/true);
165 CompInst = &CI;
166 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000167 return true;
168}
169
170namespace {
171class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
172 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000173 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000174
175public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000176 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
177 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000178
179 bool shouldVisitTemplateInstantiations() const { return false; }
180 bool shouldWalkTypesOfTypeLocs() const { return false; }
181
182 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
183 if (Consumer.MigrateLiterals) {
184 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000185 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000186 Consumer.Editor->commit(commit);
187 }
188
189 if (Consumer.MigrateSubscripting) {
190 edit::Commit commit(*Consumer.Editor);
191 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
192 Consumer.Editor->commit(commit);
193 }
194
195 return true;
196 }
197
198 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
199 // Do depth first; we want to rewrite the subexpressions first so that if
200 // we have to move expressions we will move them already rewritten.
201 for (Stmt::child_range range = E->children(); range; ++range)
202 if (!TraverseStmt(*range))
203 return false;
204
205 return WalkUpFromObjCMessageExpr(E);
206 }
207};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000208
209class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
210 ObjCMigrateASTConsumer &Consumer;
211 OwningPtr<ParentMap> PMap;
212
213public:
214 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
215
216 bool shouldVisitTemplateInstantiations() const { return false; }
217 bool shouldWalkTypesOfTypeLocs() const { return false; }
218
219 bool TraverseStmt(Stmt *S) {
220 PMap.reset(new ParentMap(S));
221 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
222 return true;
223 }
224};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000225}
226
227void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
228 if (!D)
229 return;
230 if (isa<ObjCMethodDecl>(D))
231 return; // Wait for the ObjC container declaration.
232
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000233 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000234}
235
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000236static void append_attr(std::string &PropertyString, const char *attr) {
237 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000238 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000239}
240
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000241static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
242 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000243 const NSAPI &NS, edit::Commit &commit,
244 bool GetterHasIsPrefix) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000245 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000246 std::string PropertyString = "@property(nonatomic";
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000247 std::string PropertyNameString = Getter->getNameAsString();
248 StringRef PropertyName(PropertyNameString);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000249 if (GetterHasIsPrefix) {
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000250 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000251 PropertyString += PropertyNameString;
252 }
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000253 // Short circuit properties that contain the name "delegate" or "dataSource",
254 // or have exact name "target" to have unsafe_unretained attribute.
255 if (PropertyName.equals("target") ||
256 (PropertyName.find("delegate") != StringRef::npos) ||
257 (PropertyName.find("dataSource") != StringRef::npos))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000258 append_attr(PropertyString, "unsafe_unretained");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000259 else {
260 const ParmVarDecl *argDecl = *Setter->param_begin();
261 QualType ArgType = Context.getCanonicalType(argDecl->getType());
262 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
263 bool RetainableObject = ArgType->isObjCRetainableType();
264 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
265 if (const ObjCObjectPointerType *ObjPtrTy =
266 ArgType->getAs<ObjCObjectPointerType>()) {
267 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
268 if (IDecl &&
269 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000270 append_attr(PropertyString, "copy");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000271 else
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000272 append_attr(PropertyString, "retain");
273 }
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000274 } else if (propertyLifetime == Qualifiers::OCL_Weak)
275 // TODO. More precise determination of 'weak' attribute requires
276 // looking into setter's implementation for backing weak ivar.
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000277 append_attr(PropertyString, "weak");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000278 else if (RetainableObject)
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000279 append_attr(PropertyString, "retain");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000280 }
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000281 PropertyString += ')';
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000282
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000283 QualType RT = Getter->getResultType();
284 if (!isa<TypedefType>(RT)) {
285 // strip off any ARC lifetime qualifier.
286 QualType CanResultTy = Context.getCanonicalType(RT);
287 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
288 Qualifiers Qs = CanResultTy.getQualifiers();
289 Qs.removeObjCLifetime();
290 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
291 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000292 }
293 PropertyString += " ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000294 PropertyString += RT.getAsString(Context.getPrintingPolicy());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000295 PropertyString += " ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000296 if (GetterHasIsPrefix) {
297 // property name must strip off "is" and lower case the first character
298 // after that; e.g. isContinuous will become continuous.
299 StringRef PropertyNameStringRef(PropertyNameString);
300 PropertyNameStringRef = PropertyNameStringRef.drop_front(2);
301 PropertyNameString = PropertyNameStringRef;
302 std::string NewPropertyNameString = PropertyNameString;
Fariborz Jahaniandb8bf832013-08-08 21:51:06 +0000303 NewPropertyNameString[0] = toLowercase(NewPropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000304 PropertyString += NewPropertyNameString;
305 }
306 else
307 PropertyString += PropertyNameString;
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000308 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
309 Getter->getDeclaratorEndLoc()),
310 PropertyString);
311 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
312 // Get location past ';'
313 EndLoc = EndLoc.getLocWithOffset(1);
314 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
315 return true;
316}
317
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000318void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
319 ObjCInterfaceDecl *D) {
320 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
321 M != MEnd; ++M) {
322 ObjCMethodDecl *Method = (*M);
Fariborz Jahaniande661002013-07-03 23:44:11 +0000323 if (Method->isPropertyAccessor() || Method->param_size() != 0)
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000324 continue;
325 // Is this method candidate to be a getter?
Fariborz Jahaniande661002013-07-03 23:44:11 +0000326 QualType GRT = Method->getResultType();
327 if (GRT->isVoidType())
328 continue;
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000329 // FIXME. Don't know what todo with attributes, skip for now.
330 if (Method->hasAttrs())
331 continue;
332
Fariborz Jahaniande661002013-07-03 23:44:11 +0000333 Selector GetterSelector = Method->getSelector();
334 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
335 Selector SetterSelector =
336 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
337 PP.getSelectorTable(),
338 getterName);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000339 ObjCMethodDecl *SetterMethod = D->lookupMethod(SetterSelector, true);
340 bool GetterHasIsPrefix = false;
341 if (!SetterMethod) {
342 // try a different naming convention for getter: isXxxxx
343 StringRef getterNameString = getterName->getName();
Fariborz Jahanian261fdb72013-08-08 21:20:01 +0000344 if (getterNameString.startswith("is") && !GRT->isObjCRetainableType()) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000345 GetterHasIsPrefix = true;
346 const char *CGetterName = getterNameString.data() + 2;
Fariborz Jahanian261fdb72013-08-08 21:20:01 +0000347 if (CGetterName[0] && isUppercase(CGetterName[0])) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000348 getterName = &Ctx.Idents.get(CGetterName);
349 SetterSelector =
350 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
351 PP.getSelectorTable(),
352 getterName);
353 SetterMethod = D->lookupMethod(SetterSelector, true);
354 }
355 }
356 }
357 if (SetterMethod) {
Fariborz Jahaniande661002013-07-03 23:44:11 +0000358 // Is this a valid setter, matching the target getter?
359 QualType SRT = SetterMethod->getResultType();
360 if (!SRT->isVoidType())
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000361 continue;
Fariborz Jahaniande661002013-07-03 23:44:11 +0000362 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000363 QualType ArgType = argDecl->getType();
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000364 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT) ||
365 SetterMethod->hasAttrs())
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000366 continue;
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000367 edit::Commit commit(*Editor);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000368 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
369 GetterHasIsPrefix);
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000370 Editor->commit(commit);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000371 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000372 }
373}
374
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000375static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000376ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000377 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000378 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000379 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000380 // In auto-synthesis, protocol properties are not synthesized. So,
381 // a conforming protocol must have its required properties declared
382 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000383 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000384 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
385 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
386 E = PDecl->prop_end(); P != E; ++P) {
387 ObjCPropertyDecl *Property = *P;
388 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
389 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000390 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000391 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000392 if (R.size() == 0) {
393 // Relax the rule and look into class's implementation for a synthesize
394 // or dynamic declaration. Class is implementing a property coming from
395 // another protocol. This still makes the target protocol as conforming.
396 if (!ImpDecl->FindPropertyImplDecl(
397 Property->getDeclName().getAsIdentifierInfo()))
398 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000399 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000400 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
401 if ((ClassProperty->getPropertyAttributes()
402 != Property->getPropertyAttributes()) ||
403 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
404 return false;
405 }
406 else
407 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000408 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000409
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000410 // At this point, all required properties in this protocol conform to those
411 // declared in the class.
412 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000413 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000414 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
415 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000416 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000417 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
418 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
419 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000420 if (MD->isImplicit())
421 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000422 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
423 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000424 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000425 if (R.size() == 0)
426 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000427 bool match = false;
428 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000429 for (unsigned I = 0, N = R.size(); I != N; ++I)
430 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
431 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
432 match = true;
433 break;
434 }
435 if (!match)
436 return false;
437 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000438 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000439 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
440 return true;
441 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000442}
443
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000444static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
445 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
446 const NSAPI &NS, edit::Commit &commit) {
447 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
448 std::string ClassString;
449 SourceLocation EndLoc =
450 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
451
452 if (Protocols.empty()) {
453 ClassString = '<';
454 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
455 ClassString += ConformingProtocols[i]->getNameAsString();
456 if (i != (e-1))
457 ClassString += ", ";
458 }
459 ClassString += "> ";
460 }
461 else {
462 ClassString = ", ";
463 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
464 ClassString += ConformingProtocols[i]->getNameAsString();
465 if (i != (e-1))
466 ClassString += ", ";
467 }
468 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
469 EndLoc = *PL;
470 }
471
472 commit.insertAfterToken(EndLoc, ClassString);
473 return true;
474}
475
476static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
477 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000478 const NSAPI &NS, edit::Commit &commit,
479 bool IsNSIntegerType) {
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000480 std::string ClassString =
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000481 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, " : "typedef NS_OPTIONS(NSUInteger, ";
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000482 ClassString += TypedefDcl->getIdentifier()->getName();
483 ClassString += ')';
484 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
485 commit.replace(R, ClassString);
486 SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
487 EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext());
488 if (!EndOfTypedefLoc.isInvalid()) {
489 commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc));
490 return true;
491 }
492 return false;
493}
494
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000495static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000496 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000497 const NSAPI &NS, edit::Commit &commit,
498 bool IsNSIntegerType) {
499 std::string ClassString =
500 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000501 ClassString += TypedefDcl->getIdentifier()->getName();
502 ClassString += ')';
503 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
504 commit.replace(R, ClassString);
505 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
506 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
507 return true;
508}
509
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000510static bool UseNSOptionsMacro(ASTContext &Ctx,
511 const EnumDecl *EnumDcl) {
512 bool PowerOfTwo = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000513 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000514 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
515 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
516 EnumConstantDecl *Enumerator = (*EI);
517 const Expr *InitExpr = Enumerator->getInitExpr();
518 if (!InitExpr) {
519 PowerOfTwo = false;
520 continue;
521 }
522 InitExpr = InitExpr->IgnoreImpCasts();
523 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
524 if (BO->isShiftOp() || BO->isBitwiseOp())
525 return true;
526
527 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000528 if (PowerOfTwo && EnumVal) {
529 if (!llvm::isPowerOf2_64(EnumVal))
530 PowerOfTwo = false;
531 else if (EnumVal > MaxPowerOfTwoVal)
532 MaxPowerOfTwoVal = EnumVal;
533 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000534 }
Fariborz Jahanian0b48e7c2013-08-15 18:58:00 +0000535 return PowerOfTwo && (MaxPowerOfTwoVal > 2);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000536}
537
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000538void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000539 const ObjCImplementationDecl *ImpDecl) {
540 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
541 if (!IDecl || ObjCProtocolDecls.empty())
542 return;
543 // Find all implicit conforming protocols for this class
544 // and make them explicit.
545 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
546 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000547 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000548
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000549 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000550 ObjCProtocolDecls.begin(),
551 E = ObjCProtocolDecls.end(); I != E; ++I)
552 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000553 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000554
555 if (PotentialImplicitProtocols.empty())
556 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000557
558 // go through list of non-optional methods and properties in each protocol
559 // in the PotentialImplicitProtocols list. If class implements every one of the
560 // methods and properties, then this class conforms to this protocol.
561 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
562 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000563 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000564 PotentialImplicitProtocols[i]))
565 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000566
567 if (ConformingProtocols.empty())
568 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000569
570 // Further reduce number of conforming protocols. If protocol P1 is in the list
571 // protocol P2 (P2<P1>), No need to include P1.
572 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
573 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
574 bool DropIt = false;
575 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
576 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
577 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
578 if (PDecl == TargetPDecl)
579 continue;
580 if (PDecl->lookupProtocolNamed(
581 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
582 DropIt = true;
583 break;
584 }
585 }
586 if (!DropIt)
587 MinimalConformingProtocols.push_back(TargetPDecl);
588 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000589 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000590 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
591 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000592 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000593}
594
Fariborz Jahanian92463272013-07-18 20:11:45 +0000595void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
596 const EnumDecl *EnumDcl,
597 const TypedefDecl *TypedefDcl) {
598 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
599 !TypedefDcl->getIdentifier())
600 return;
601
602 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000603 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
604 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000605
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000606 if (!IsNSIntegerType && !IsNSUIntegerType) {
607 // Also check for typedef enum {...} TD;
608 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
609 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000610 bool NSOptions = UseNSOptionsMacro(Ctx, EnumDcl);
611 if (NSOptions) {
612 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
613 return;
614 }
615 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000616 return;
617 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000618 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000619 Editor->commit(commit);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000620 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000621 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000622 return;
623 }
624 if (IsNSIntegerType && UseNSOptionsMacro(Ctx, EnumDcl)) {
625 // We may still use NS_OPTIONS based on what we find in the enumertor list.
626 IsNSIntegerType = false;
627 IsNSUIntegerType = true;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000628 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000629
630 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000631 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
632 return;
633 // NS_OPTIONS must be available.
634 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000635 return;
636 edit::Commit commit(*Editor);
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000637 rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000638 Editor->commit(commit);
639}
640
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000641static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
642 ObjCMethodDecl *OM) {
643 SourceRange R;
644 std::string ClassString;
645 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
646 TypeLoc TL = TSInfo->getTypeLoc();
647 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
648 ClassString = "instancetype";
649 }
650 else {
651 R = SourceRange(OM->getLocStart(), OM->getLocStart());
652 ClassString = OM->isInstanceMethod() ? '-' : '+';
653 ClassString += " (instancetype)";
654 }
655 edit::Commit commit(*ASTC.Editor);
656 commit.replace(R, ClassString);
657 ASTC.Editor->commit(commit);
658}
659
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000660void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
661 ObjCContainerDecl *CDecl,
662 ObjCMethodDecl *OM) {
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000663 // bail out early and do not suggest 'instancetype' when the method already
664 // has a related result type,
665 if (OM->hasRelatedResultType())
666 return;
667
Fariborz Jahanian71221352013-07-23 22:42:28 +0000668 ObjCInstanceTypeFamily OIT_Family =
669 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000670
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000671 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000672 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000673 case OIT_None:
674 migrateFactoryMethod(Ctx, CDecl, OM);
675 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000676 case OIT_Array:
677 ClassName = "NSArray";
678 break;
679 case OIT_Dictionary:
680 ClassName = "NSDictionary";
681 break;
Fariborz Jahanian1a26c202013-08-28 20:49:58 +0000682 // For methods where Clang automatically infers instancetype from the selector
683 // (e.g., all -init* methods), we should not suggest "instancetype" because it
684 // is redundant,
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000685 case OIT_MemManage:
Fariborz Jahanian1a26c202013-08-28 20:49:58 +0000686 return;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000687 case OIT_Singleton:
688 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000689 return;
690 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000691 if (!OM->getResultType()->isObjCIdType())
692 return;
693
694 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
695 if (!IDecl) {
696 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
697 IDecl = CatDecl->getClassInterface();
698 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
699 IDecl = ImpDecl->getClassInterface();
700 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000701 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000702 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
703 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000704 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000705 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000706 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000707}
708
709void ObjCMigrateASTConsumer::migrateInstanceType(ASTContext &Ctx,
710 ObjCContainerDecl *CDecl) {
711 // migrate methods which can have instancetype as their result type.
712 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
713 MEnd = CDecl->meth_end();
714 M != MEnd; ++M) {
715 ObjCMethodDecl *Method = (*M);
716 migrateMethodInstanceType(Ctx, CDecl, Method);
717 }
718}
719
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000720void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
721 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000722 ObjCMethodDecl *OM,
723 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +0000724 if (OM->isInstanceMethod() ||
725 OM->getResultType() == Ctx.getObjCInstanceType() ||
726 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000727 return;
728
729 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
730 // NSYYYNamE with matching names be at least 3 characters long.
731 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
732 if (!IDecl) {
733 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
734 IDecl = CatDecl->getClassInterface();
735 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
736 IDecl = ImpDecl->getClassInterface();
737 }
738 if (!IDecl)
739 return;
740
741 std::string StringClassName = IDecl->getName();
742 StringRef LoweredClassName(StringClassName);
743 std::string StringLoweredClassName = LoweredClassName.lower();
744 LoweredClassName = StringLoweredClassName;
745
746 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000747 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
748 if (!MethodIdName)
749 return;
750
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000751 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000752 if (OIT_Family == OIT_Singleton) {
753 StringRef STRefMethodName(MethodName);
754 size_t len = 0;
755 if (STRefMethodName.startswith("standard"))
756 len = strlen("standard");
757 else if (STRefMethodName.startswith("shared"))
758 len = strlen("shared");
759 else if (STRefMethodName.startswith("default"))
760 len = strlen("default");
761 else
762 return;
763 MethodName = STRefMethodName.substr(len);
764 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000765 std::string MethodNameSubStr = MethodName.substr(0, 3);
766 StringRef MethodNamePrefix(MethodNameSubStr);
767 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
768 MethodNamePrefix = StringLoweredMethodNamePrefix;
769 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
770 if (Ix == StringRef::npos)
771 return;
772 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
773 StringRef LoweredMethodName(MethodName);
774 std::string StringLoweredMethodName = LoweredMethodName.lower();
775 LoweredMethodName = StringLoweredMethodName;
776 if (!LoweredMethodName.startswith(ClassNamePostfix))
777 return;
778 ReplaceWithInstancetype(*this, OM);
779}
780
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000781static bool IsVoidStarType(QualType Ty) {
782 if (!Ty->isPointerType())
783 return false;
784
785 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
786 Ty = TD->getDecl()->getUnderlyingType();
787
788 // Is the type void*?
789 const PointerType* PT = Ty->getAs<PointerType>();
790 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
791 return true;
792 return IsVoidStarType(PT->getPointeeType());
793}
794
Fariborz Jahanian94279392013-08-20 18:54:39 +0000795/// AuditedType - This routine audits the type AT and returns false if it is one of known
796/// CF object types or of the "void *" variety. It returns true if we don't care about the type
797/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000798static bool AuditedType (QualType AT) {
799 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000800 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000801 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +0000802 if (ento::coreFoundation::isCFObjectRef(AT) ||
803 IsVoidStarType(AT) ||
804 // If an ObjC object is type, assuming that it is not a CF function and
805 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +0000806 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000807 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +0000808 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000809 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000810}
811
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000812void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000813 if (CFFunctionIBCandidates.empty())
814 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000815 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
816 CFFunctionIBCandidates.clear();
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000817 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000818 return;
819 }
820 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000821 const Decl *FirstFD = CFFunctionIBCandidates[0];
822 const Decl *LastFD =
823 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000824 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
825 edit::Commit commit(*Editor);
826 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
827 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
828 SourceLocation EndLoc = LastFD->getLocEnd();
829 // get location just past end of function location.
830 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000831 if (isa<FunctionDecl>(LastFD)) {
832 // For Methods, EndLoc points to the ending semcolon. So,
833 // not of these extra work is needed.
834 Token Tok;
835 // get locaiton of token that comes after end of function.
836 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
837 if (!Failed)
838 EndLoc = Tok.getLocation();
839 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000840 commit.insertAfterToken(EndLoc, PragmaString);
841 Editor->commit(commit);
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000842 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000843 CFFunctionIBCandidates.clear();
844}
845
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000846void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
847 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000848 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000849 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000850 "provided CF_IMPLICIT_BRIDGING_ENABLE");
851 return;
852 }
853
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000854 // Finction must be annotated first.
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000855 CF_BRIDGING_KIND AuditKind;
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000856 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000857 AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000858 else
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000859 AuditKind = migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
860 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000861 CFFunctionIBCandidates.push_back(Decl);
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000862 if (!FileId)
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000863 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000864 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000865 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
866 if (!CFFunctionIBCandidates.empty()) {
867 CFFunctionIBCandidates.push_back(Decl);
868 if (!FileId)
869 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
870 }
871 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000872 else
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000873 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000874}
875
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000876void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
877 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +0000878 const FunctionDecl *FuncDecl,
879 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000880 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +0000881 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000882 RetEffect Ret = CE.getReturnValue();
883 const char *AnnotationString = 0;
884 if (Ret.getObjKind() == RetEffect::CF && Ret.isOwned()) {
885 if (Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
886 AnnotationString = " CF_RETURNS_RETAINED";
887 }
888 else if (Ret.getObjKind() == RetEffect::CF && !Ret.isOwned()) {
889 if (Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
890 AnnotationString = " CF_RETURNS_NOT_RETAINED";
891 }
892 if (AnnotationString) {
893 edit::Commit commit(*Editor);
894 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
895 Editor->commit(commit);
896 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +0000897 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000898 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
899 unsigned i = 0;
900 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
901 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +0000902 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000903 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000904 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
905 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
906 edit::Commit commit(*Editor);
907 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
908 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +0000909 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +0000910 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000911}
912
913
914ObjCMigrateASTConsumer::CF_BRIDGING_KIND
915 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
916 ASTContext &Ctx,
917 const FunctionDecl *FuncDecl) {
918 if (FuncDecl->hasBody())
919 return CF_BRIDGING_NONE;
920
921 CallEffects CE = CallEffects::getEffect(FuncDecl);
922 bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
923 FuncDecl->getAttr<CFReturnsNotRetainedAttr>());
924
925 // Trivial case of when funciton is annotated and has no argument.
926 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
927 return CF_BRIDGING_NONE;
928
929 bool ReturnCFAudited = false;
930 if (!FuncIsReturnAnnotated) {
931 RetEffect Ret = CE.getReturnValue();
932 if (Ret.getObjKind() == RetEffect::CF &&
933 (Ret.isOwned() || !Ret.isOwned()))
934 ReturnCFAudited = true;
935 else if (!AuditedType(FuncDecl->getResultType()))
936 return CF_BRIDGING_NONE;
937 }
938
939 // At this point result type is audited for potential inclusion.
940 // Now, how about argument types.
941 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
942 unsigned i = 0;
943 bool ArgCFAudited = false;
944 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
945 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
946 const ParmVarDecl *pd = *pi;
947 ArgEffect AE = AEArgs[i];
948 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
949 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
950 ArgCFAudited = true;
951 else if (AE == IncRef)
952 ArgCFAudited = true;
953 }
954 else {
955 QualType AT = pd->getType();
956 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +0000957 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000958 return CF_BRIDGING_NONE;
959 }
960 }
961 }
962 if (ReturnCFAudited || ArgCFAudited)
963 return CF_BRIDGING_ENABLE;
964
965 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +0000966}
967
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000968void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
969 ObjCContainerDecl *CDecl) {
970 if (!isa<ObjCInterfaceDecl>(CDecl))
971 return;
972
973 // migrate methods which can have instancetype as their result type.
974 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
975 MEnd = CDecl->meth_end();
976 M != MEnd; ++M) {
977 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000978 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000979 }
980}
981
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000982void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
983 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +0000984 const ObjCMethodDecl *MethodDecl,
985 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000986 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +0000987 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000988 RetEffect Ret = CE.getReturnValue();
989 const char *AnnotationString = 0;
990 if (Ret.getObjKind() == RetEffect::CF && Ret.isOwned()) {
991 if (Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
992 AnnotationString = " CF_RETURNS_RETAINED";
993 }
994 else if (Ret.getObjKind() == RetEffect::CF && !Ret.isOwned()) {
995 if (Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
996 AnnotationString = " CF_RETURNS_NOT_RETAINED";
997 }
998 if (AnnotationString) {
999 edit::Commit commit(*Editor);
1000 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1001 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001002 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001003 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001004 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1005 unsigned i = 0;
1006 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1007 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1008 const ParmVarDecl *pd = *pi;
1009 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001010 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1011 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1012 edit::Commit commit(*Editor);
1013 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1014 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001015 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001016 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001017}
1018
1019ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1020 ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
1021 ASTContext &Ctx,
1022 const ObjCMethodDecl *MethodDecl) {
1023 if (MethodDecl->hasBody())
1024 return CF_BRIDGING_NONE;
1025
1026 CallEffects CE = CallEffects::getEffect(MethodDecl);
1027 bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
1028 MethodDecl->getAttr<CFReturnsNotRetainedAttr>());
1029
1030 // Trivial case of when funciton is annotated and has no argument.
1031 if (MethodIsReturnAnnotated &&
1032 (MethodDecl->param_begin() == MethodDecl->param_end()))
1033 return CF_BRIDGING_NONE;
1034
1035 bool ReturnCFAudited = false;
1036 if (!MethodIsReturnAnnotated) {
1037 RetEffect Ret = CE.getReturnValue();
1038 if (Ret.getObjKind() == RetEffect::CF && (Ret.isOwned() || !Ret.isOwned()))
1039 ReturnCFAudited = true;
1040 else if (!AuditedType(MethodDecl->getResultType()))
1041 return CF_BRIDGING_NONE;
1042 }
1043
1044 // At this point result type is either annotated or audited.
1045 // Now, how about argument types.
1046 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1047 unsigned i = 0;
1048 bool ArgCFAudited = false;
1049 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1050 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1051 const ParmVarDecl *pd = *pi;
1052 ArgEffect AE = AEArgs[i];
1053 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1054 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
1055 ArgCFAudited = true;
1056 else if (AE == IncRef)
1057 ArgCFAudited = true;
1058 }
1059 else {
1060 QualType AT = pd->getType();
1061 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001062 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001063 return CF_BRIDGING_NONE;
1064 }
1065 }
1066 }
1067 if (ReturnCFAudited || ArgCFAudited)
1068 return CF_BRIDGING_ENABLE;
1069
1070 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001071}
1072
Ted Kremenekf7639e12012-03-06 20:06:33 +00001073namespace {
1074
1075class RewritesReceiver : public edit::EditsReceiver {
1076 Rewriter &Rewrite;
1077
1078public:
1079 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1080
1081 virtual void insert(SourceLocation loc, StringRef text) {
1082 Rewrite.InsertText(loc, text);
1083 }
1084 virtual void replace(CharSourceRange range, StringRef text) {
1085 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1086 }
1087};
1088
1089}
1090
1091void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001092
1093 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001094 if (MigrateProperty) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001095 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1096 D != DEnd; ++D) {
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001097 if (unsigned FID =
1098 PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue())
1099 if (FileId && FileId != FID) {
1100 assert(!CFFunctionIBCandidates.empty());
1101 AnnotateImplicitBridging(Ctx);
1102 }
1103
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001104 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1105 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001106 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1107 ObjCProtocolDecls.insert(PDecl);
1108 else if (const ObjCImplementationDecl *ImpDecl =
1109 dyn_cast<ObjCImplementationDecl>(*D))
1110 migrateProtocolConformance(Ctx, ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001111 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1112 DeclContext::decl_iterator N = D;
1113 ++N;
Fariborz Jahanian008ef722013-07-19 17:44:32 +00001114 if (N != DEnd)
1115 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N))
1116 migrateNSEnumDecl(Ctx, ED, TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001117 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001118 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D))
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001119 migrateCFAnnotation(Ctx, FD);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001120
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001121 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1122 // migrate methods which can have instancetype as their result type.
Fariborz Jahanian71221352013-07-23 22:42:28 +00001123 migrateInstanceType(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001124 // annotate methods with CF annotations.
1125 migrateARCSafeAnnotation(Ctx, CDecl);
1126 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001127 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001128 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001129 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001130
David Blaikiebbafb8a2012-03-11 07:00:24 +00001131 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001132 RewritesReceiver Rec(rewriter);
1133 Editor->applyRewrites(Rec);
1134
1135 for (Rewriter::buffer_iterator
1136 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1137 FileID FID = I->first;
1138 RewriteBuffer &buf = I->second;
1139 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1140 assert(file);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001141 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001142 llvm::raw_svector_ostream vecOS(newText);
1143 buf.write(vecOS);
1144 vecOS.flush();
1145 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1146 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001147 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001148 FileMgr.FixupRelativePath(filePath);
1149 Remapper.remap(filePath.str(), memBuf);
1150 }
1151
1152 if (IsOutputFile) {
1153 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1154 } else {
1155 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1156 }
1157}
1158
1159bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001160 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001161 return true;
1162}
1163
1164ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1165 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001166 PPConditionalDirectiveRecord *
1167 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1168 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001169 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
1170 /*MigrateLiterals=*/true,
1171 /*MigrateSubscripting=*/true,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001172 /*MigrateProperty*/true,
Ted Kremenekf7639e12012-03-06 20:06:33 +00001173 Remapper,
1174 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001175 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001176 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +00001177 /*isOutputFile=*/true);
1178}