blob: 0aca657ffdb7728591da626cea4ab85614738b10 [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 Jahanian55d6e6c2013-08-28 23:22:46 +000078 bool MigrateReadonlyProperty;
Fariborz Jahanianb8343522013-08-20 23:35:26 +000079 unsigned FileId;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000080 OwningPtr<NSAPI> NSAPIObj;
81 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000082 FileRemapper &Remapper;
83 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000084 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000085 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000086 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000087 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000088 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000089
Ted Kremenekf7639e12012-03-06 20:06:33 +000090 ObjCMigrateASTConsumer(StringRef migrateDir,
91 bool migrateLiterals,
92 bool migrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000093 bool migrateProperty,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +000094 bool migrateReadonlyProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +000095 FileRemapper &remapper,
96 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000097 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000098 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +000099 bool isOutputFile = false)
100 : MigrateDir(migrateDir),
101 MigrateLiterals(migrateLiterals),
102 MigrateSubscripting(migrateSubscripting),
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000103 MigrateProperty(migrateProperty),
104 MigrateReadonlyProperty(migrateReadonlyProperty),
105 FileId(0), Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000106 IsOutputFile(isOutputFile) { }
107
108protected:
109 virtual void Initialize(ASTContext &Context) {
110 NSAPIObj.reset(new NSAPI(Context));
111 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000112 Context.getLangOpts(),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000113 PPRec));
114 }
115
116 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
117 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
118 migrateDecl(*I);
119 return true;
120 }
121 virtual void HandleInterestingDecl(DeclGroupRef DG) {
122 // Ignore decls from the PCH.
123 }
124 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
125 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
126 }
127
128 virtual void HandleTranslationUnit(ASTContext &Ctx);
129};
130
131}
132
133ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
134 StringRef migrateDir,
135 bool migrateLiterals,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000136 bool migrateSubscripting,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000137 bool migrateProperty,
138 bool migrateReadonlyProperty)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000139 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
140 MigrateLiterals(migrateLiterals), MigrateSubscripting(migrateSubscripting),
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000141 MigrateProperty(migrateProperty),
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000142 MigrateReadonlyProperty(migrateReadonlyProperty),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000143 CompInst(0) {
144 if (MigrateDir.empty())
145 MigrateDir = "."; // user current directory if none is given.
146}
147
148ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
149 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000150 PPConditionalDirectiveRecord *
151 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
152 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000153 ASTConsumer *
154 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
155 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
156 MigrateLiterals,
157 MigrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000158 MigrateProperty,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000159 MigrateReadonlyProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000160 Remapper,
161 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000162 PPRec,
163 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000164 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
165 return new MultiplexConsumer(Consumers);
166}
167
168bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
169 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
170 /*ignoreIfFilesChanges=*/true);
171 CompInst = &CI;
172 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000173 return true;
174}
175
176namespace {
177class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
178 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000179 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000180
181public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000182 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
183 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000184
185 bool shouldVisitTemplateInstantiations() const { return false; }
186 bool shouldWalkTypesOfTypeLocs() const { return false; }
187
188 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
189 if (Consumer.MigrateLiterals) {
190 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000191 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000192 Consumer.Editor->commit(commit);
193 }
194
195 if (Consumer.MigrateSubscripting) {
196 edit::Commit commit(*Consumer.Editor);
197 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
198 Consumer.Editor->commit(commit);
199 }
200
201 return true;
202 }
203
204 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
205 // Do depth first; we want to rewrite the subexpressions first so that if
206 // we have to move expressions we will move them already rewritten.
207 for (Stmt::child_range range = E->children(); range; ++range)
208 if (!TraverseStmt(*range))
209 return false;
210
211 return WalkUpFromObjCMessageExpr(E);
212 }
213};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000214
215class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
216 ObjCMigrateASTConsumer &Consumer;
217 OwningPtr<ParentMap> PMap;
218
219public:
220 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
221
222 bool shouldVisitTemplateInstantiations() const { return false; }
223 bool shouldWalkTypesOfTypeLocs() const { return false; }
224
225 bool TraverseStmt(Stmt *S) {
226 PMap.reset(new ParentMap(S));
227 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
228 return true;
229 }
230};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000231}
232
233void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
234 if (!D)
235 return;
236 if (isa<ObjCMethodDecl>(D))
237 return; // Wait for the ObjC container declaration.
238
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000239 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000240}
241
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000242static void append_attr(std::string &PropertyString, const char *attr) {
243 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000244 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000245}
246
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000247static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
248 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000249 const NSAPI &NS, edit::Commit &commit,
250 bool GetterHasIsPrefix) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000251 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000252 std::string PropertyString = "@property(nonatomic";
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000253 std::string PropertyNameString = Getter->getNameAsString();
254 StringRef PropertyName(PropertyNameString);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000255 if (GetterHasIsPrefix) {
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000256 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000257 PropertyString += PropertyNameString;
258 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000259 // Property with no setter may be suggested as a 'readonly' property.
260 if (!Setter)
261 append_attr(PropertyString, "readonly");
262
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000263 // Short circuit properties that contain the name "delegate" or "dataSource",
264 // or have exact name "target" to have unsafe_unretained attribute.
265 if (PropertyName.equals("target") ||
266 (PropertyName.find("delegate") != StringRef::npos) ||
267 (PropertyName.find("dataSource") != StringRef::npos))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000268 append_attr(PropertyString, "unsafe_unretained");
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000269 else if (Setter) {
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000270 const ParmVarDecl *argDecl = *Setter->param_begin();
271 QualType ArgType = Context.getCanonicalType(argDecl->getType());
272 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
273 bool RetainableObject = ArgType->isObjCRetainableType();
274 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
275 if (const ObjCObjectPointerType *ObjPtrTy =
276 ArgType->getAs<ObjCObjectPointerType>()) {
277 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
278 if (IDecl &&
279 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000280 append_attr(PropertyString, "copy");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000281 else
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000282 append_attr(PropertyString, "retain");
283 }
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000284 } else if (propertyLifetime == Qualifiers::OCL_Weak)
285 // TODO. More precise determination of 'weak' attribute requires
286 // looking into setter's implementation for backing weak ivar.
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000287 append_attr(PropertyString, "weak");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000288 else if (RetainableObject)
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000289 append_attr(PropertyString, "retain");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000290 }
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000291 PropertyString += ')';
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000292
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000293 QualType RT = Getter->getResultType();
294 if (!isa<TypedefType>(RT)) {
295 // strip off any ARC lifetime qualifier.
296 QualType CanResultTy = Context.getCanonicalType(RT);
297 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
298 Qualifiers Qs = CanResultTy.getQualifiers();
299 Qs.removeObjCLifetime();
300 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
301 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000302 }
303 PropertyString += " ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000304 PropertyString += RT.getAsString(Context.getPrintingPolicy());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000305 PropertyString += " ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000306 if (GetterHasIsPrefix) {
307 // property name must strip off "is" and lower case the first character
308 // after that; e.g. isContinuous will become continuous.
309 StringRef PropertyNameStringRef(PropertyNameString);
310 PropertyNameStringRef = PropertyNameStringRef.drop_front(2);
311 PropertyNameString = PropertyNameStringRef;
312 std::string NewPropertyNameString = PropertyNameString;
Fariborz Jahaniandb8bf832013-08-08 21:51:06 +0000313 NewPropertyNameString[0] = toLowercase(NewPropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000314 PropertyString += NewPropertyNameString;
315 }
316 else
317 PropertyString += PropertyNameString;
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000318 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
319 Getter->getDeclaratorEndLoc()),
320 PropertyString);
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000321 if (Setter) {
322 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
323 // Get location past ';'
324 EndLoc = EndLoc.getLocWithOffset(1);
325 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
326 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000327 return true;
328}
329
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000330void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
331 ObjCInterfaceDecl *D) {
332 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
333 M != MEnd; ++M) {
334 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000335 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
336 Method->param_size() != 0)
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000337 continue;
338 // Is this method candidate to be a getter?
Fariborz Jahaniande661002013-07-03 23:44:11 +0000339 QualType GRT = Method->getResultType();
340 if (GRT->isVoidType())
341 continue;
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000342 // FIXME. Don't know what todo with attributes, skip for now.
343 if (Method->hasAttrs())
344 continue;
345
Fariborz Jahaniande661002013-07-03 23:44:11 +0000346 Selector GetterSelector = Method->getSelector();
347 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
348 Selector SetterSelector =
349 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
350 PP.getSelectorTable(),
351 getterName);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000352 ObjCMethodDecl *SetterMethod = D->lookupMethod(SetterSelector, true);
353 bool GetterHasIsPrefix = false;
354 if (!SetterMethod) {
355 // try a different naming convention for getter: isXxxxx
356 StringRef getterNameString = getterName->getName();
Fariborz Jahanian261fdb72013-08-08 21:20:01 +0000357 if (getterNameString.startswith("is") && !GRT->isObjCRetainableType()) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000358 GetterHasIsPrefix = true;
359 const char *CGetterName = getterNameString.data() + 2;
Fariborz Jahanian261fdb72013-08-08 21:20:01 +0000360 if (CGetterName[0] && isUppercase(CGetterName[0])) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000361 getterName = &Ctx.Idents.get(CGetterName);
362 SetterSelector =
363 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
364 PP.getSelectorTable(),
365 getterName);
366 SetterMethod = D->lookupMethod(SetterSelector, true);
367 }
368 }
369 }
370 if (SetterMethod) {
Fariborz Jahaniande661002013-07-03 23:44:11 +0000371 // Is this a valid setter, matching the target getter?
372 QualType SRT = SetterMethod->getResultType();
373 if (!SRT->isVoidType())
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000374 continue;
Fariborz Jahaniande661002013-07-03 23:44:11 +0000375 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000376 QualType ArgType = argDecl->getType();
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000377 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT) ||
378 SetterMethod->hasAttrs())
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000379 continue;
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000380 edit::Commit commit(*Editor);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000381 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
382 GetterHasIsPrefix);
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000383 Editor->commit(commit);
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000384 }
385 else if (MigrateReadonlyProperty) {
386 // Try a non-void method with no argument (and no setter or property of same name
387 // as a 'readonly' property.
388 edit::Commit commit(*Editor);
389 rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
390 false /*GetterHasIsPrefix*/);
391 Editor->commit(commit);
392 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000393 }
394}
395
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000396static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000397ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000398 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000399 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000400 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000401 // In auto-synthesis, protocol properties are not synthesized. So,
402 // a conforming protocol must have its required properties declared
403 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000404 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000405 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
406 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
407 E = PDecl->prop_end(); P != E; ++P) {
408 ObjCPropertyDecl *Property = *P;
409 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
410 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000411 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000412 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000413 if (R.size() == 0) {
414 // Relax the rule and look into class's implementation for a synthesize
415 // or dynamic declaration. Class is implementing a property coming from
416 // another protocol. This still makes the target protocol as conforming.
417 if (!ImpDecl->FindPropertyImplDecl(
418 Property->getDeclName().getAsIdentifierInfo()))
419 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000420 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000421 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
422 if ((ClassProperty->getPropertyAttributes()
423 != Property->getPropertyAttributes()) ||
424 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
425 return false;
426 }
427 else
428 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000429 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000430
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000431 // At this point, all required properties in this protocol conform to those
432 // declared in the class.
433 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000434 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000435 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
436 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000437 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000438 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
439 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
440 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000441 if (MD->isImplicit())
442 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000443 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
444 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000445 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000446 if (R.size() == 0)
447 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000448 bool match = false;
449 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000450 for (unsigned I = 0, N = R.size(); I != N; ++I)
451 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
452 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
453 match = true;
454 break;
455 }
456 if (!match)
457 return false;
458 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000459 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000460 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
461 return true;
462 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000463}
464
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000465static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
466 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
467 const NSAPI &NS, edit::Commit &commit) {
468 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
469 std::string ClassString;
470 SourceLocation EndLoc =
471 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
472
473 if (Protocols.empty()) {
474 ClassString = '<';
475 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
476 ClassString += ConformingProtocols[i]->getNameAsString();
477 if (i != (e-1))
478 ClassString += ", ";
479 }
480 ClassString += "> ";
481 }
482 else {
483 ClassString = ", ";
484 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
485 ClassString += ConformingProtocols[i]->getNameAsString();
486 if (i != (e-1))
487 ClassString += ", ";
488 }
489 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
490 EndLoc = *PL;
491 }
492
493 commit.insertAfterToken(EndLoc, ClassString);
494 return true;
495}
496
497static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
498 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000499 const NSAPI &NS, edit::Commit &commit,
500 bool IsNSIntegerType) {
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000501 std::string ClassString =
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000502 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, " : "typedef NS_OPTIONS(NSUInteger, ";
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000503 ClassString += TypedefDcl->getIdentifier()->getName();
504 ClassString += ')';
505 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
506 commit.replace(R, ClassString);
507 SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
508 EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext());
509 if (!EndOfTypedefLoc.isInvalid()) {
510 commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc));
511 return true;
512 }
513 return false;
514}
515
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000516static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000517 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000518 const NSAPI &NS, edit::Commit &commit,
519 bool IsNSIntegerType) {
520 std::string ClassString =
521 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000522 ClassString += TypedefDcl->getIdentifier()->getName();
523 ClassString += ')';
524 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
525 commit.replace(R, ClassString);
526 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
527 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
528 return true;
529}
530
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000531static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000532 const EnumDecl *EnumDcl) {
533 bool PowerOfTwo = true;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000534 bool FoundHexdecimalEnumerator = false;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000535 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000536 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
537 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
538 EnumConstantDecl *Enumerator = (*EI);
539 const Expr *InitExpr = Enumerator->getInitExpr();
540 if (!InitExpr) {
541 PowerOfTwo = false;
542 continue;
543 }
544 InitExpr = InitExpr->IgnoreImpCasts();
545 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
546 if (BO->isShiftOp() || BO->isBitwiseOp())
547 return true;
548
549 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000550 if (PowerOfTwo && EnumVal) {
551 if (!llvm::isPowerOf2_64(EnumVal))
552 PowerOfTwo = false;
553 else if (EnumVal > MaxPowerOfTwoVal)
554 MaxPowerOfTwoVal = EnumVal;
555 }
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000556 if (!FoundHexdecimalEnumerator) {
557 SourceLocation EndLoc = Enumerator->getLocEnd();
558 Token Tok;
559 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
560 if (Tok.isLiteral() && Tok.getLength() > 2) {
561 if (const char *StringLit = Tok.getLiteralData())
562 FoundHexdecimalEnumerator =
563 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
564 }
565 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000566 }
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000567 return FoundHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000568}
569
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000570void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000571 const ObjCImplementationDecl *ImpDecl) {
572 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
573 if (!IDecl || ObjCProtocolDecls.empty())
574 return;
575 // Find all implicit conforming protocols for this class
576 // and make them explicit.
577 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
578 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000579 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000580
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000581 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000582 ObjCProtocolDecls.begin(),
583 E = ObjCProtocolDecls.end(); I != E; ++I)
584 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000585 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000586
587 if (PotentialImplicitProtocols.empty())
588 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000589
590 // go through list of non-optional methods and properties in each protocol
591 // in the PotentialImplicitProtocols list. If class implements every one of the
592 // methods and properties, then this class conforms to this protocol.
593 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
594 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000595 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000596 PotentialImplicitProtocols[i]))
597 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000598
599 if (ConformingProtocols.empty())
600 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000601
602 // Further reduce number of conforming protocols. If protocol P1 is in the list
603 // protocol P2 (P2<P1>), No need to include P1.
604 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
605 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
606 bool DropIt = false;
607 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
608 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
609 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
610 if (PDecl == TargetPDecl)
611 continue;
612 if (PDecl->lookupProtocolNamed(
613 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
614 DropIt = true;
615 break;
616 }
617 }
618 if (!DropIt)
619 MinimalConformingProtocols.push_back(TargetPDecl);
620 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000621 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000622 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
623 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000624 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000625}
626
Fariborz Jahanian92463272013-07-18 20:11:45 +0000627void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
628 const EnumDecl *EnumDcl,
629 const TypedefDecl *TypedefDcl) {
630 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
631 !TypedefDcl->getIdentifier())
632 return;
633
634 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000635 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
636 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000637
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000638 if (!IsNSIntegerType && !IsNSUIntegerType) {
639 // Also check for typedef enum {...} TD;
640 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
641 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000642 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000643 if (NSOptions) {
644 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
645 return;
646 }
647 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000648 return;
649 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000650 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000651 Editor->commit(commit);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000652 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000653 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000654 return;
655 }
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000656 if (IsNSIntegerType && UseNSOptionsMacro(PP, Ctx, EnumDcl)) {
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000657 // We may still use NS_OPTIONS based on what we find in the enumertor list.
658 IsNSIntegerType = false;
659 IsNSUIntegerType = true;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000660 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000661
662 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000663 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
664 return;
665 // NS_OPTIONS must be available.
666 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000667 return;
668 edit::Commit commit(*Editor);
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000669 rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000670 Editor->commit(commit);
671}
672
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000673static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
674 ObjCMethodDecl *OM) {
675 SourceRange R;
676 std::string ClassString;
677 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
678 TypeLoc TL = TSInfo->getTypeLoc();
679 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
680 ClassString = "instancetype";
681 }
682 else {
683 R = SourceRange(OM->getLocStart(), OM->getLocStart());
684 ClassString = OM->isInstanceMethod() ? '-' : '+';
685 ClassString += " (instancetype)";
686 }
687 edit::Commit commit(*ASTC.Editor);
688 commit.replace(R, ClassString);
689 ASTC.Editor->commit(commit);
690}
691
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000692void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
693 ObjCContainerDecl *CDecl,
694 ObjCMethodDecl *OM) {
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000695 // bail out early and do not suggest 'instancetype' when the method already
696 // has a related result type,
697 if (OM->hasRelatedResultType())
698 return;
699
Fariborz Jahanian71221352013-07-23 22:42:28 +0000700 ObjCInstanceTypeFamily OIT_Family =
701 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000702
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000703 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000704 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000705 case OIT_None:
706 migrateFactoryMethod(Ctx, CDecl, OM);
707 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000708 case OIT_Array:
709 ClassName = "NSArray";
710 break;
711 case OIT_Dictionary:
712 ClassName = "NSDictionary";
713 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000714 case OIT_Singleton:
715 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000716 return;
717 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000718 if (!OM->getResultType()->isObjCIdType())
719 return;
720
721 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
722 if (!IDecl) {
723 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
724 IDecl = CatDecl->getClassInterface();
725 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
726 IDecl = ImpDecl->getClassInterface();
727 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000728 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000729 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
730 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000731 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000732 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000733 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000734}
735
736void ObjCMigrateASTConsumer::migrateInstanceType(ASTContext &Ctx,
737 ObjCContainerDecl *CDecl) {
738 // migrate methods which can have instancetype as their result type.
739 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
740 MEnd = CDecl->meth_end();
741 M != MEnd; ++M) {
742 ObjCMethodDecl *Method = (*M);
743 migrateMethodInstanceType(Ctx, CDecl, Method);
744 }
745}
746
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000747void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
748 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000749 ObjCMethodDecl *OM,
750 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +0000751 if (OM->isInstanceMethod() ||
752 OM->getResultType() == Ctx.getObjCInstanceType() ||
753 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000754 return;
755
756 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
757 // NSYYYNamE with matching names be at least 3 characters long.
758 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
759 if (!IDecl) {
760 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
761 IDecl = CatDecl->getClassInterface();
762 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
763 IDecl = ImpDecl->getClassInterface();
764 }
765 if (!IDecl)
766 return;
767
768 std::string StringClassName = IDecl->getName();
769 StringRef LoweredClassName(StringClassName);
770 std::string StringLoweredClassName = LoweredClassName.lower();
771 LoweredClassName = StringLoweredClassName;
772
773 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000774 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
775 if (!MethodIdName)
776 return;
777
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000778 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000779 if (OIT_Family == OIT_Singleton) {
780 StringRef STRefMethodName(MethodName);
781 size_t len = 0;
782 if (STRefMethodName.startswith("standard"))
783 len = strlen("standard");
784 else if (STRefMethodName.startswith("shared"))
785 len = strlen("shared");
786 else if (STRefMethodName.startswith("default"))
787 len = strlen("default");
788 else
789 return;
790 MethodName = STRefMethodName.substr(len);
791 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000792 std::string MethodNameSubStr = MethodName.substr(0, 3);
793 StringRef MethodNamePrefix(MethodNameSubStr);
794 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
795 MethodNamePrefix = StringLoweredMethodNamePrefix;
796 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
797 if (Ix == StringRef::npos)
798 return;
799 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
800 StringRef LoweredMethodName(MethodName);
801 std::string StringLoweredMethodName = LoweredMethodName.lower();
802 LoweredMethodName = StringLoweredMethodName;
803 if (!LoweredMethodName.startswith(ClassNamePostfix))
804 return;
805 ReplaceWithInstancetype(*this, OM);
806}
807
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000808static bool IsVoidStarType(QualType Ty) {
809 if (!Ty->isPointerType())
810 return false;
811
812 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
813 Ty = TD->getDecl()->getUnderlyingType();
814
815 // Is the type void*?
816 const PointerType* PT = Ty->getAs<PointerType>();
817 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
818 return true;
819 return IsVoidStarType(PT->getPointeeType());
820}
821
Fariborz Jahanian94279392013-08-20 18:54:39 +0000822/// AuditedType - This routine audits the type AT and returns false if it is one of known
823/// CF object types or of the "void *" variety. It returns true if we don't care about the type
824/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000825static bool AuditedType (QualType AT) {
826 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000827 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000828 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +0000829 if (ento::coreFoundation::isCFObjectRef(AT) ||
830 IsVoidStarType(AT) ||
831 // If an ObjC object is type, assuming that it is not a CF function and
832 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +0000833 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000834 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +0000835 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000836 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000837}
838
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000839void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000840 if (CFFunctionIBCandidates.empty())
841 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000842 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
843 CFFunctionIBCandidates.clear();
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000844 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000845 return;
846 }
847 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000848 const Decl *FirstFD = CFFunctionIBCandidates[0];
849 const Decl *LastFD =
850 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000851 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
852 edit::Commit commit(*Editor);
853 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
854 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
855 SourceLocation EndLoc = LastFD->getLocEnd();
856 // get location just past end of function location.
857 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000858 if (isa<FunctionDecl>(LastFD)) {
859 // For Methods, EndLoc points to the ending semcolon. So,
860 // not of these extra work is needed.
861 Token Tok;
862 // get locaiton of token that comes after end of function.
863 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
864 if (!Failed)
865 EndLoc = Tok.getLocation();
866 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000867 commit.insertAfterToken(EndLoc, PragmaString);
868 Editor->commit(commit);
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000869 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000870 CFFunctionIBCandidates.clear();
871}
872
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000873void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
874 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000875 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000876 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000877 "provided CF_IMPLICIT_BRIDGING_ENABLE");
878 return;
879 }
880
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000881 // Finction must be annotated first.
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000882 CF_BRIDGING_KIND AuditKind;
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000883 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000884 AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000885 else
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000886 AuditKind = migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
887 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000888 CFFunctionIBCandidates.push_back(Decl);
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000889 if (!FileId)
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +0000890 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
Fariborz Jahanianb8343522013-08-20 23:35:26 +0000891 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000892 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
893 if (!CFFunctionIBCandidates.empty()) {
894 CFFunctionIBCandidates.push_back(Decl);
895 if (!FileId)
896 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
897 }
898 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000899 else
Fariborz Jahanian301b5212013-08-20 22:42:13 +0000900 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000901}
902
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000903void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
904 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +0000905 const FunctionDecl *FuncDecl,
906 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000907 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +0000908 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000909 RetEffect Ret = CE.getReturnValue();
910 const char *AnnotationString = 0;
911 if (Ret.getObjKind() == RetEffect::CF && Ret.isOwned()) {
912 if (Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
913 AnnotationString = " CF_RETURNS_RETAINED";
914 }
915 else if (Ret.getObjKind() == RetEffect::CF && !Ret.isOwned()) {
916 if (Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
917 AnnotationString = " CF_RETURNS_NOT_RETAINED";
918 }
919 if (AnnotationString) {
920 edit::Commit commit(*Editor);
921 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
922 Editor->commit(commit);
923 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +0000924 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000925 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
926 unsigned i = 0;
927 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
928 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +0000929 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000930 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000931 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
932 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
933 edit::Commit commit(*Editor);
934 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
935 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +0000936 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +0000937 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000938}
939
940
941ObjCMigrateASTConsumer::CF_BRIDGING_KIND
942 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
943 ASTContext &Ctx,
944 const FunctionDecl *FuncDecl) {
945 if (FuncDecl->hasBody())
946 return CF_BRIDGING_NONE;
947
948 CallEffects CE = CallEffects::getEffect(FuncDecl);
949 bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
950 FuncDecl->getAttr<CFReturnsNotRetainedAttr>());
951
952 // Trivial case of when funciton is annotated and has no argument.
953 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
954 return CF_BRIDGING_NONE;
955
956 bool ReturnCFAudited = false;
957 if (!FuncIsReturnAnnotated) {
958 RetEffect Ret = CE.getReturnValue();
959 if (Ret.getObjKind() == RetEffect::CF &&
960 (Ret.isOwned() || !Ret.isOwned()))
961 ReturnCFAudited = true;
962 else if (!AuditedType(FuncDecl->getResultType()))
963 return CF_BRIDGING_NONE;
964 }
965
966 // At this point result type is audited for potential inclusion.
967 // Now, how about argument types.
968 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
969 unsigned i = 0;
970 bool ArgCFAudited = false;
971 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
972 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
973 const ParmVarDecl *pd = *pi;
974 ArgEffect AE = AEArgs[i];
975 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
976 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
977 ArgCFAudited = true;
978 else if (AE == IncRef)
979 ArgCFAudited = true;
980 }
981 else {
982 QualType AT = pd->getType();
983 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +0000984 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +0000985 return CF_BRIDGING_NONE;
986 }
987 }
988 }
989 if (ReturnCFAudited || ArgCFAudited)
990 return CF_BRIDGING_ENABLE;
991
992 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +0000993}
994
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000995void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
996 ObjCContainerDecl *CDecl) {
997 if (!isa<ObjCInterfaceDecl>(CDecl))
998 return;
999
1000 // migrate methods which can have instancetype as their result type.
1001 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1002 MEnd = CDecl->meth_end();
1003 M != MEnd; ++M) {
1004 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001005 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001006 }
1007}
1008
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001009void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1010 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001011 const ObjCMethodDecl *MethodDecl,
1012 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001013 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001014 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001015 RetEffect Ret = CE.getReturnValue();
1016 const char *AnnotationString = 0;
1017 if (Ret.getObjKind() == RetEffect::CF && Ret.isOwned()) {
1018 if (Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
1019 AnnotationString = " CF_RETURNS_RETAINED";
1020 }
1021 else if (Ret.getObjKind() == RetEffect::CF && !Ret.isOwned()) {
1022 if (Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
1023 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1024 }
1025 if (AnnotationString) {
1026 edit::Commit commit(*Editor);
1027 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1028 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001029 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001030 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001031 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1032 unsigned i = 0;
1033 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1034 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1035 const ParmVarDecl *pd = *pi;
1036 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001037 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1038 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1039 edit::Commit commit(*Editor);
1040 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1041 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001042 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001043 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001044}
1045
1046ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1047 ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
1048 ASTContext &Ctx,
1049 const ObjCMethodDecl *MethodDecl) {
1050 if (MethodDecl->hasBody())
1051 return CF_BRIDGING_NONE;
1052
1053 CallEffects CE = CallEffects::getEffect(MethodDecl);
1054 bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
1055 MethodDecl->getAttr<CFReturnsNotRetainedAttr>());
1056
1057 // Trivial case of when funciton is annotated and has no argument.
1058 if (MethodIsReturnAnnotated &&
1059 (MethodDecl->param_begin() == MethodDecl->param_end()))
1060 return CF_BRIDGING_NONE;
1061
1062 bool ReturnCFAudited = false;
1063 if (!MethodIsReturnAnnotated) {
1064 RetEffect Ret = CE.getReturnValue();
1065 if (Ret.getObjKind() == RetEffect::CF && (Ret.isOwned() || !Ret.isOwned()))
1066 ReturnCFAudited = true;
1067 else if (!AuditedType(MethodDecl->getResultType()))
1068 return CF_BRIDGING_NONE;
1069 }
1070
1071 // At this point result type is either annotated or audited.
1072 // Now, how about argument types.
1073 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1074 unsigned i = 0;
1075 bool ArgCFAudited = false;
1076 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1077 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1078 const ParmVarDecl *pd = *pi;
1079 ArgEffect AE = AEArgs[i];
1080 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1081 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
1082 ArgCFAudited = true;
1083 else if (AE == IncRef)
1084 ArgCFAudited = true;
1085 }
1086 else {
1087 QualType AT = pd->getType();
1088 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001089 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001090 return CF_BRIDGING_NONE;
1091 }
1092 }
1093 }
1094 if (ReturnCFAudited || ArgCFAudited)
1095 return CF_BRIDGING_ENABLE;
1096
1097 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001098}
1099
Ted Kremenekf7639e12012-03-06 20:06:33 +00001100namespace {
1101
1102class RewritesReceiver : public edit::EditsReceiver {
1103 Rewriter &Rewrite;
1104
1105public:
1106 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1107
1108 virtual void insert(SourceLocation loc, StringRef text) {
1109 Rewrite.InsertText(loc, text);
1110 }
1111 virtual void replace(CharSourceRange range, StringRef text) {
1112 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1113 }
1114};
1115
1116}
1117
1118void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001119
1120 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001121 if (MigrateProperty) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001122 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1123 D != DEnd; ++D) {
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001124 if (unsigned FID =
1125 PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue())
1126 if (FileId && FileId != FID) {
1127 assert(!CFFunctionIBCandidates.empty());
1128 AnnotateImplicitBridging(Ctx);
1129 }
1130
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001131 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1132 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001133 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1134 ObjCProtocolDecls.insert(PDecl);
1135 else if (const ObjCImplementationDecl *ImpDecl =
1136 dyn_cast<ObjCImplementationDecl>(*D))
1137 migrateProtocolConformance(Ctx, ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001138 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1139 DeclContext::decl_iterator N = D;
1140 ++N;
Fariborz Jahanian008ef722013-07-19 17:44:32 +00001141 if (N != DEnd)
1142 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N))
1143 migrateNSEnumDecl(Ctx, ED, TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001144 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001145 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D))
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001146 migrateCFAnnotation(Ctx, FD);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001147
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001148 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1149 // migrate methods which can have instancetype as their result type.
Fariborz Jahanian71221352013-07-23 22:42:28 +00001150 migrateInstanceType(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001151 // annotate methods with CF annotations.
1152 migrateARCSafeAnnotation(Ctx, CDecl);
1153 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001154 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001155 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001156 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001157
David Blaikiebbafb8a2012-03-11 07:00:24 +00001158 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001159 RewritesReceiver Rec(rewriter);
1160 Editor->applyRewrites(Rec);
1161
1162 for (Rewriter::buffer_iterator
1163 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1164 FileID FID = I->first;
1165 RewriteBuffer &buf = I->second;
1166 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1167 assert(file);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001168 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001169 llvm::raw_svector_ostream vecOS(newText);
1170 buf.write(vecOS);
1171 vecOS.flush();
1172 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1173 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001174 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001175 FileMgr.FixupRelativePath(filePath);
1176 Remapper.remap(filePath.str(), memBuf);
1177 }
1178
1179 if (IsOutputFile) {
1180 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1181 } else {
1182 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1183 }
1184}
1185
1186bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001187 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001188 return true;
1189}
1190
1191ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1192 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001193 PPConditionalDirectiveRecord *
1194 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1195 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001196 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
1197 /*MigrateLiterals=*/true,
1198 /*MigrateSubscripting=*/true,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001199 /*MigrateProperty*/true,
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +00001200 /*MigrateReadonlyProperty*/true,
Ted Kremenekf7639e12012-03-06 20:06:33 +00001201 Remapper,
1202 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001203 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001204 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +00001205 /*isOutputFile=*/true);
1206}