blob: 439b2d4fe4584d42e633e1f58b1c5cf584d43a90 [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 {
39 void migrateDecl(Decl *D);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000040 void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCInterfaceDecl *D);
Fariborz Jahanian1be01532013-07-12 22:32:19 +000041 void migrateProtocolConformance(ASTContext &Ctx,
42 const ObjCImplementationDecl *ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +000043 void migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
44 const TypedefDecl *TypedefDcl);
Fariborz Jahanian71221352013-07-23 22:42:28 +000045 void migrateInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000046 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
47 ObjCMethodDecl *OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000048 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000049 ObjCMethodDecl *OM,
50 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000051
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000052 void migrateCFFunctions(ASTContext &Ctx,
53 const FunctionDecl *FuncDecl);
54
55 bool migrateAddFunctionAnnotation(ASTContext &Ctx,
56 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000057
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +000058 void migrateObjCMethodDeclAnnotation(ASTContext &Ctx,
59 const ObjCMethodDecl *MethodDecl);
Ted Kremenekf7639e12012-03-06 20:06:33 +000060public:
61 std::string MigrateDir;
62 bool MigrateLiterals;
63 bool MigrateSubscripting;
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000064 bool MigrateProperty;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000065 OwningPtr<NSAPI> NSAPIObj;
66 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000067 FileRemapper &Remapper;
68 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000069 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000070 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000071 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000072 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000073 llvm::SmallVector<const FunctionDecl *, 8> CFFunctionIBCandidates;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000074
Ted Kremenekf7639e12012-03-06 20:06:33 +000075 ObjCMigrateASTConsumer(StringRef migrateDir,
76 bool migrateLiterals,
77 bool migrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000078 bool migrateProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +000079 FileRemapper &remapper,
80 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000081 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000082 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +000083 bool isOutputFile = false)
84 : MigrateDir(migrateDir),
85 MigrateLiterals(migrateLiterals),
86 MigrateSubscripting(migrateSubscripting),
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000087 MigrateProperty(migrateProperty),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000088 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +000089 IsOutputFile(isOutputFile) { }
90
91protected:
92 virtual void Initialize(ASTContext &Context) {
93 NSAPIObj.reset(new NSAPI(Context));
94 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +000095 Context.getLangOpts(),
Ted Kremenekf7639e12012-03-06 20:06:33 +000096 PPRec));
97 }
98
99 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
100 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
101 migrateDecl(*I);
102 return true;
103 }
104 virtual void HandleInterestingDecl(DeclGroupRef DG) {
105 // Ignore decls from the PCH.
106 }
107 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
108 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
109 }
110
111 virtual void HandleTranslationUnit(ASTContext &Ctx);
112};
113
114}
115
116ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
117 StringRef migrateDir,
118 bool migrateLiterals,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000119 bool migrateSubscripting,
120 bool migrateProperty)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000121 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
122 MigrateLiterals(migrateLiterals), MigrateSubscripting(migrateSubscripting),
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000123 MigrateProperty(migrateProperty),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000124 CompInst(0) {
125 if (MigrateDir.empty())
126 MigrateDir = "."; // user current directory if none is given.
127}
128
129ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
130 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000131 PPConditionalDirectiveRecord *
132 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
133 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000134 ASTConsumer *
135 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
136 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
137 MigrateLiterals,
138 MigrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000139 MigrateProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000140 Remapper,
141 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000142 PPRec,
143 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000144 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
145 return new MultiplexConsumer(Consumers);
146}
147
148bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
149 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
150 /*ignoreIfFilesChanges=*/true);
151 CompInst = &CI;
152 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000153 return true;
154}
155
156namespace {
157class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
158 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000159 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000160
161public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000162 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
163 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000164
165 bool shouldVisitTemplateInstantiations() const { return false; }
166 bool shouldWalkTypesOfTypeLocs() const { return false; }
167
168 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
169 if (Consumer.MigrateLiterals) {
170 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000171 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000172 Consumer.Editor->commit(commit);
173 }
174
175 if (Consumer.MigrateSubscripting) {
176 edit::Commit commit(*Consumer.Editor);
177 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
178 Consumer.Editor->commit(commit);
179 }
180
181 return true;
182 }
183
184 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
185 // Do depth first; we want to rewrite the subexpressions first so that if
186 // we have to move expressions we will move them already rewritten.
187 for (Stmt::child_range range = E->children(); range; ++range)
188 if (!TraverseStmt(*range))
189 return false;
190
191 return WalkUpFromObjCMessageExpr(E);
192 }
193};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000194
195class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
196 ObjCMigrateASTConsumer &Consumer;
197 OwningPtr<ParentMap> PMap;
198
199public:
200 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
201
202 bool shouldVisitTemplateInstantiations() const { return false; }
203 bool shouldWalkTypesOfTypeLocs() const { return false; }
204
205 bool TraverseStmt(Stmt *S) {
206 PMap.reset(new ParentMap(S));
207 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
208 return true;
209 }
210};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000211}
212
213void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
214 if (!D)
215 return;
216 if (isa<ObjCMethodDecl>(D))
217 return; // Wait for the ObjC container declaration.
218
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000219 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000220}
221
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000222static void append_attr(std::string &PropertyString, const char *attr,
223 bool GetterHasIsPrefix) {
224 PropertyString += (GetterHasIsPrefix ? ", " : "(");
225 PropertyString += attr;
226 PropertyString += ')';
227}
228
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000229static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
230 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000231 const NSAPI &NS, edit::Commit &commit,
232 bool GetterHasIsPrefix) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000233 ASTContext &Context = NS.getASTContext();
234 std::string PropertyString = "@property";
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000235 std::string PropertyNameString = Getter->getNameAsString();
236 StringRef PropertyName(PropertyNameString);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000237 if (GetterHasIsPrefix) {
238 PropertyString += "(getter=";
239 PropertyString += PropertyNameString;
240 }
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000241 // Short circuit properties that contain the name "delegate" or "dataSource",
242 // or have exact name "target" to have unsafe_unretained attribute.
243 if (PropertyName.equals("target") ||
244 (PropertyName.find("delegate") != StringRef::npos) ||
245 (PropertyName.find("dataSource") != StringRef::npos))
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000246 append_attr(PropertyString, "unsafe_unretained", GetterHasIsPrefix);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000247 else {
248 const ParmVarDecl *argDecl = *Setter->param_begin();
249 QualType ArgType = Context.getCanonicalType(argDecl->getType());
250 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
251 bool RetainableObject = ArgType->isObjCRetainableType();
252 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
253 if (const ObjCObjectPointerType *ObjPtrTy =
254 ArgType->getAs<ObjCObjectPointerType>()) {
255 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
256 if (IDecl &&
257 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000258 append_attr(PropertyString, "copy", GetterHasIsPrefix);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000259 else
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000260 append_attr(PropertyString, "retain", GetterHasIsPrefix);
261 } else if (GetterHasIsPrefix)
262 PropertyString += ')';
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000263 } else if (propertyLifetime == Qualifiers::OCL_Weak)
264 // TODO. More precise determination of 'weak' attribute requires
265 // looking into setter's implementation for backing weak ivar.
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000266 append_attr(PropertyString, "weak", GetterHasIsPrefix);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000267 else if (RetainableObject)
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000268 append_attr(PropertyString, "retain", GetterHasIsPrefix);
269 else if (GetterHasIsPrefix)
270 PropertyString += ')';
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000271 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000272
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000273 QualType RT = Getter->getResultType();
274 if (!isa<TypedefType>(RT)) {
275 // strip off any ARC lifetime qualifier.
276 QualType CanResultTy = Context.getCanonicalType(RT);
277 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
278 Qualifiers Qs = CanResultTy.getQualifiers();
279 Qs.removeObjCLifetime();
280 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
281 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000282 }
283 PropertyString += " ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000284 PropertyString += RT.getAsString(Context.getPrintingPolicy());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000285 PropertyString += " ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000286 if (GetterHasIsPrefix) {
287 // property name must strip off "is" and lower case the first character
288 // after that; e.g. isContinuous will become continuous.
289 StringRef PropertyNameStringRef(PropertyNameString);
290 PropertyNameStringRef = PropertyNameStringRef.drop_front(2);
291 PropertyNameString = PropertyNameStringRef;
292 std::string NewPropertyNameString = PropertyNameString;
Fariborz Jahaniandb8bf832013-08-08 21:51:06 +0000293 NewPropertyNameString[0] = toLowercase(NewPropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000294 PropertyString += NewPropertyNameString;
295 }
296 else
297 PropertyString += PropertyNameString;
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000298 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
299 Getter->getDeclaratorEndLoc()),
300 PropertyString);
301 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
302 // Get location past ';'
303 EndLoc = EndLoc.getLocWithOffset(1);
304 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
305 return true;
306}
307
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000308void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
309 ObjCInterfaceDecl *D) {
310 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
311 M != MEnd; ++M) {
312 ObjCMethodDecl *Method = (*M);
Fariborz Jahaniande661002013-07-03 23:44:11 +0000313 if (Method->isPropertyAccessor() || Method->param_size() != 0)
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000314 continue;
315 // Is this method candidate to be a getter?
Fariborz Jahaniande661002013-07-03 23:44:11 +0000316 QualType GRT = Method->getResultType();
317 if (GRT->isVoidType())
318 continue;
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000319 // FIXME. Don't know what todo with attributes, skip for now.
320 if (Method->hasAttrs())
321 continue;
322
Fariborz Jahaniande661002013-07-03 23:44:11 +0000323 Selector GetterSelector = Method->getSelector();
324 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
325 Selector SetterSelector =
326 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
327 PP.getSelectorTable(),
328 getterName);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000329 ObjCMethodDecl *SetterMethod = D->lookupMethod(SetterSelector, true);
330 bool GetterHasIsPrefix = false;
331 if (!SetterMethod) {
332 // try a different naming convention for getter: isXxxxx
333 StringRef getterNameString = getterName->getName();
Fariborz Jahanian261fdb72013-08-08 21:20:01 +0000334 if (getterNameString.startswith("is") && !GRT->isObjCRetainableType()) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000335 GetterHasIsPrefix = true;
336 const char *CGetterName = getterNameString.data() + 2;
Fariborz Jahanian261fdb72013-08-08 21:20:01 +0000337 if (CGetterName[0] && isUppercase(CGetterName[0])) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000338 getterName = &Ctx.Idents.get(CGetterName);
339 SetterSelector =
340 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
341 PP.getSelectorTable(),
342 getterName);
343 SetterMethod = D->lookupMethod(SetterSelector, true);
344 }
345 }
346 }
347 if (SetterMethod) {
Fariborz Jahaniande661002013-07-03 23:44:11 +0000348 // Is this a valid setter, matching the target getter?
349 QualType SRT = SetterMethod->getResultType();
350 if (!SRT->isVoidType())
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000351 continue;
Fariborz Jahaniande661002013-07-03 23:44:11 +0000352 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000353 QualType ArgType = argDecl->getType();
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000354 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT) ||
355 SetterMethod->hasAttrs())
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000356 continue;
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000357 edit::Commit commit(*Editor);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000358 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
359 GetterHasIsPrefix);
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000360 Editor->commit(commit);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000361 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000362 }
363}
364
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000365static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000366ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000367 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000368 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000369 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000370 // In auto-synthesis, protocol properties are not synthesized. So,
371 // a conforming protocol must have its required properties declared
372 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000373 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000374 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
375 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
376 E = PDecl->prop_end(); P != E; ++P) {
377 ObjCPropertyDecl *Property = *P;
378 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
379 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000380 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000381 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000382 if (R.size() == 0) {
383 // Relax the rule and look into class's implementation for a synthesize
384 // or dynamic declaration. Class is implementing a property coming from
385 // another protocol. This still makes the target protocol as conforming.
386 if (!ImpDecl->FindPropertyImplDecl(
387 Property->getDeclName().getAsIdentifierInfo()))
388 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000389 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000390 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
391 if ((ClassProperty->getPropertyAttributes()
392 != Property->getPropertyAttributes()) ||
393 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
394 return false;
395 }
396 else
397 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000398 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000399
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000400 // At this point, all required properties in this protocol conform to those
401 // declared in the class.
402 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000403 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000404 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
405 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000406 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000407 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
408 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
409 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000410 if (MD->isImplicit())
411 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000412 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
413 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000414 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000415 if (R.size() == 0)
416 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000417 bool match = false;
418 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000419 for (unsigned I = 0, N = R.size(); I != N; ++I)
420 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
421 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
422 match = true;
423 break;
424 }
425 if (!match)
426 return false;
427 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000428 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000429 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
430 return true;
431 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000432}
433
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000434static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
435 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
436 const NSAPI &NS, edit::Commit &commit) {
437 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
438 std::string ClassString;
439 SourceLocation EndLoc =
440 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
441
442 if (Protocols.empty()) {
443 ClassString = '<';
444 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
445 ClassString += ConformingProtocols[i]->getNameAsString();
446 if (i != (e-1))
447 ClassString += ", ";
448 }
449 ClassString += "> ";
450 }
451 else {
452 ClassString = ", ";
453 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
454 ClassString += ConformingProtocols[i]->getNameAsString();
455 if (i != (e-1))
456 ClassString += ", ";
457 }
458 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
459 EndLoc = *PL;
460 }
461
462 commit.insertAfterToken(EndLoc, ClassString);
463 return true;
464}
465
466static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
467 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000468 const NSAPI &NS, edit::Commit &commit,
469 bool IsNSIntegerType) {
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000470 std::string ClassString =
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000471 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, " : "typedef NS_OPTIONS(NSUInteger, ";
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000472 ClassString += TypedefDcl->getIdentifier()->getName();
473 ClassString += ')';
474 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
475 commit.replace(R, ClassString);
476 SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
477 EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext());
478 if (!EndOfTypedefLoc.isInvalid()) {
479 commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc));
480 return true;
481 }
482 return false;
483}
484
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000485static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000486 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000487 const NSAPI &NS, edit::Commit &commit,
488 bool IsNSIntegerType) {
489 std::string ClassString =
490 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000491 ClassString += TypedefDcl->getIdentifier()->getName();
492 ClassString += ')';
493 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
494 commit.replace(R, ClassString);
495 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
496 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
497 return true;
498}
499
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000500static bool UseNSOptionsMacro(ASTContext &Ctx,
501 const EnumDecl *EnumDcl) {
502 bool PowerOfTwo = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000503 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000504 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
505 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
506 EnumConstantDecl *Enumerator = (*EI);
507 const Expr *InitExpr = Enumerator->getInitExpr();
508 if (!InitExpr) {
509 PowerOfTwo = false;
510 continue;
511 }
512 InitExpr = InitExpr->IgnoreImpCasts();
513 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
514 if (BO->isShiftOp() || BO->isBitwiseOp())
515 return true;
516
517 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000518 if (PowerOfTwo && EnumVal) {
519 if (!llvm::isPowerOf2_64(EnumVal))
520 PowerOfTwo = false;
521 else if (EnumVal > MaxPowerOfTwoVal)
522 MaxPowerOfTwoVal = EnumVal;
523 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000524 }
Fariborz Jahanian0b48e7c2013-08-15 18:58:00 +0000525 return PowerOfTwo && (MaxPowerOfTwoVal > 2);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000526}
527
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000528void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000529 const ObjCImplementationDecl *ImpDecl) {
530 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
531 if (!IDecl || ObjCProtocolDecls.empty())
532 return;
533 // Find all implicit conforming protocols for this class
534 // and make them explicit.
535 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
536 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000537 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000538
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000539 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000540 ObjCProtocolDecls.begin(),
541 E = ObjCProtocolDecls.end(); I != E; ++I)
542 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000543 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000544
545 if (PotentialImplicitProtocols.empty())
546 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000547
548 // go through list of non-optional methods and properties in each protocol
549 // in the PotentialImplicitProtocols list. If class implements every one of the
550 // methods and properties, then this class conforms to this protocol.
551 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
552 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000553 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000554 PotentialImplicitProtocols[i]))
555 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000556
557 if (ConformingProtocols.empty())
558 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000559
560 // Further reduce number of conforming protocols. If protocol P1 is in the list
561 // protocol P2 (P2<P1>), No need to include P1.
562 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
563 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
564 bool DropIt = false;
565 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
566 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
567 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
568 if (PDecl == TargetPDecl)
569 continue;
570 if (PDecl->lookupProtocolNamed(
571 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
572 DropIt = true;
573 break;
574 }
575 }
576 if (!DropIt)
577 MinimalConformingProtocols.push_back(TargetPDecl);
578 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000579 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000580 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
581 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000582 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000583}
584
Fariborz Jahanian92463272013-07-18 20:11:45 +0000585void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
586 const EnumDecl *EnumDcl,
587 const TypedefDecl *TypedefDcl) {
588 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
589 !TypedefDcl->getIdentifier())
590 return;
591
592 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000593 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
594 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000595
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000596 if (!IsNSIntegerType && !IsNSUIntegerType) {
597 // Also check for typedef enum {...} TD;
598 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
599 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000600 bool NSOptions = UseNSOptionsMacro(Ctx, EnumDcl);
601 if (NSOptions) {
602 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
603 return;
604 }
605 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000606 return;
607 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000608 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000609 Editor->commit(commit);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000610 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000611 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000612 return;
613 }
614 if (IsNSIntegerType && UseNSOptionsMacro(Ctx, EnumDcl)) {
615 // We may still use NS_OPTIONS based on what we find in the enumertor list.
616 IsNSIntegerType = false;
617 IsNSUIntegerType = true;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000618 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000619
620 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000621 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
622 return;
623 // NS_OPTIONS must be available.
624 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000625 return;
626 edit::Commit commit(*Editor);
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000627 rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000628 Editor->commit(commit);
629}
630
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000631static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
632 ObjCMethodDecl *OM) {
633 SourceRange R;
634 std::string ClassString;
635 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
636 TypeLoc TL = TSInfo->getTypeLoc();
637 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
638 ClassString = "instancetype";
639 }
640 else {
641 R = SourceRange(OM->getLocStart(), OM->getLocStart());
642 ClassString = OM->isInstanceMethod() ? '-' : '+';
643 ClassString += " (instancetype)";
644 }
645 edit::Commit commit(*ASTC.Editor);
646 commit.replace(R, ClassString);
647 ASTC.Editor->commit(commit);
648}
649
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000650void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
651 ObjCContainerDecl *CDecl,
652 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +0000653 ObjCInstanceTypeFamily OIT_Family =
654 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000655
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000656 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000657 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000658 case OIT_None:
659 migrateFactoryMethod(Ctx, CDecl, OM);
660 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000661 case OIT_Array:
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000662 ClassName = "NSArray";
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000663 break;
664 case OIT_Dictionary:
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000665 ClassName = "NSDictionary";
666 break;
667 case OIT_MemManage:
668 ClassName = "NSObject";
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000669 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000670 case OIT_Singleton:
671 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000672 return;
673 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000674 if (!OM->getResultType()->isObjCIdType())
675 return;
676
677 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
678 if (!IDecl) {
679 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
680 IDecl = CatDecl->getClassInterface();
681 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
682 IDecl = ImpDecl->getClassInterface();
683 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000684 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000685 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
686 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000687 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000688 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000689 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000690}
691
692void ObjCMigrateASTConsumer::migrateInstanceType(ASTContext &Ctx,
693 ObjCContainerDecl *CDecl) {
694 // migrate methods which can have instancetype as their result type.
695 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
696 MEnd = CDecl->meth_end();
697 M != MEnd; ++M) {
698 ObjCMethodDecl *Method = (*M);
699 migrateMethodInstanceType(Ctx, CDecl, Method);
700 }
701}
702
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000703void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
704 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000705 ObjCMethodDecl *OM,
706 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +0000707 if (OM->isInstanceMethod() ||
708 OM->getResultType() == Ctx.getObjCInstanceType() ||
709 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000710 return;
711
712 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
713 // NSYYYNamE with matching names be at least 3 characters long.
714 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
715 if (!IDecl) {
716 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
717 IDecl = CatDecl->getClassInterface();
718 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
719 IDecl = ImpDecl->getClassInterface();
720 }
721 if (!IDecl)
722 return;
723
724 std::string StringClassName = IDecl->getName();
725 StringRef LoweredClassName(StringClassName);
726 std::string StringLoweredClassName = LoweredClassName.lower();
727 LoweredClassName = StringLoweredClassName;
728
729 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000730 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
731 if (!MethodIdName)
732 return;
733
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000734 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000735 if (OIT_Family == OIT_Singleton) {
736 StringRef STRefMethodName(MethodName);
737 size_t len = 0;
738 if (STRefMethodName.startswith("standard"))
739 len = strlen("standard");
740 else if (STRefMethodName.startswith("shared"))
741 len = strlen("shared");
742 else if (STRefMethodName.startswith("default"))
743 len = strlen("default");
744 else
745 return;
746 MethodName = STRefMethodName.substr(len);
747 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000748 std::string MethodNameSubStr = MethodName.substr(0, 3);
749 StringRef MethodNamePrefix(MethodNameSubStr);
750 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
751 MethodNamePrefix = StringLoweredMethodNamePrefix;
752 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
753 if (Ix == StringRef::npos)
754 return;
755 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
756 StringRef LoweredMethodName(MethodName);
757 std::string StringLoweredMethodName = LoweredMethodName.lower();
758 LoweredMethodName = StringLoweredMethodName;
759 if (!LoweredMethodName.startswith(ClassNamePostfix))
760 return;
761 ReplaceWithInstancetype(*this, OM);
762}
763
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000764static bool IsVoidStarType(QualType Ty) {
765 if (!Ty->isPointerType())
766 return false;
767
768 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
769 Ty = TD->getDecl()->getUnderlyingType();
770
771 // Is the type void*?
772 const PointerType* PT = Ty->getAs<PointerType>();
773 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
774 return true;
775 return IsVoidStarType(PT->getPointeeType());
776}
777
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000778static bool
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000779AuditedType (QualType AT) {
780 if (!AT->isPointerType())
781 return true;
782 if (IsVoidStarType(AT))
783 return false;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000784
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000785 // FIXME. There isn't much we can say about CF pointer type; or is there?
786 if (ento::coreFoundation::isCFObjectRef(AT))
787 return false;
788 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000789}
790
791void ObjCMigrateASTConsumer::migrateCFFunctions(
792 ASTContext &Ctx,
793 const FunctionDecl *FuncDecl) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000794 if (FuncDecl->hasAttr<CFAuditedTransferAttr>()) {
795 assert(CFFunctionIBCandidates.empty() &&
796 "Cannot have audited functions inside user "
797 "provided CF_IMPLICIT_BRIDGING_ENABLE");
798 return;
799 }
800
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000801 // Finction must be annotated first.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000802 bool Audited = migrateAddFunctionAnnotation(Ctx, FuncDecl);
803 if (Audited)
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000804 CFFunctionIBCandidates.push_back(FuncDecl);
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000805 else if (!CFFunctionIBCandidates.empty()) {
806 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
807 CFFunctionIBCandidates.clear();
808 return;
809 }
810 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
811 const FunctionDecl *FirstFD = CFFunctionIBCandidates[0];
812 const FunctionDecl *LastFD =
813 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
814 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n";
815 edit::Commit commit(*Editor);
816 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
817 PragmaString = "\nCF_IMPLICIT_BRIDGING_DISABLED\n";
Fariborz Jahaniand38ad472013-08-20 00:07:23 +0000818 SourceLocation EndLoc = LastFD->getLocEnd();
819 // get location just past end of function location.
820 EndLoc = PP.getLocForEndOfToken(EndLoc);
821 Token Tok;
822 // get locaiton of token that comes after end of function.
823 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
824 if (!Failed)
825 EndLoc = Tok.getLocation();
826 commit.insertAfterToken(EndLoc, PragmaString);
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000827 Editor->commit(commit);
828
829 CFFunctionIBCandidates.clear();
830 }
831 // FIXME. Also must insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
832 // when leaving current file.
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000833}
834
835bool ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +0000836 ASTContext &Ctx,
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000837 const FunctionDecl *FuncDecl) {
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000838 if (FuncDecl->hasBody())
839 return false;
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +0000840 CallEffects CE = CallEffects::getEffect(FuncDecl);
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000841 if (!FuncDecl->getAttr<CFReturnsRetainedAttr>() &&
842 !FuncDecl->getAttr<CFReturnsNotRetainedAttr>()) {
843 RetEffect Ret = CE.getReturnValue();
844 const char *AnnotationString = 0;
845 if (Ret.getObjKind() == RetEffect::CF && Ret.isOwned()) {
846 if (Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
847 AnnotationString = " CF_RETURNS_RETAINED";
848 }
849 else if (Ret.getObjKind() == RetEffect::CF && !Ret.isOwned()) {
850 if (Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
851 AnnotationString = " CF_RETURNS_NOT_RETAINED";
852 }
853 if (AnnotationString) {
854 edit::Commit commit(*Editor);
855 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
856 Editor->commit(commit);
857 }
858 else if (!AuditedType(FuncDecl->getResultType()))
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000859 return false;
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +0000860 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000861 // At this point result type is either annotated or audited.
862 // Now, how about argument types.
863 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
864 unsigned i = 0;
865 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
866 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
867 ArgEffect AE = AEArgs[i];
868 if (AE == DecRefMsg /*NSConsumed annotated*/ ||
869 AE == DecRef /*CFConsumed annotated*/)
870 continue;
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000871
872 if (AE != DoNothing && AE != MayEscape)
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000873 return false;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +0000874 const ParmVarDecl *pd = *pi;
875 QualType AT = pd->getType();
876 if (!AuditedType(AT))
877 return false;
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +0000878 }
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +0000879 return true;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +0000880}
881
882void ObjCMigrateASTConsumer::migrateObjCMethodDeclAnnotation(
883 ASTContext &Ctx,
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000884 const ObjCMethodDecl *MethodDecl) {
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +0000885 if (MethodDecl->hasAttr<CFAuditedTransferAttr>() ||
886 MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000887 MethodDecl->getAttr<CFReturnsNotRetainedAttr>() ||
888 MethodDecl->hasBody())
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +0000889 return;
890}
891
Ted Kremenekf7639e12012-03-06 20:06:33 +0000892namespace {
893
894class RewritesReceiver : public edit::EditsReceiver {
895 Rewriter &Rewrite;
896
897public:
898 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
899
900 virtual void insert(SourceLocation loc, StringRef text) {
901 Rewrite.InsertText(loc, text);
902 }
903 virtual void replace(CharSourceRange range, StringRef text) {
904 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
905 }
906};
907
908}
909
910void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000911
912 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000913 if (MigrateProperty)
914 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
915 D != DEnd; ++D) {
916 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
917 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000918 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
919 ObjCProtocolDecls.insert(PDecl);
920 else if (const ObjCImplementationDecl *ImpDecl =
921 dyn_cast<ObjCImplementationDecl>(*D))
922 migrateProtocolConformance(Ctx, ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000923 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
924 DeclContext::decl_iterator N = D;
925 ++N;
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000926 if (N != DEnd)
927 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N))
928 migrateNSEnumDecl(Ctx, ED, TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000929 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000930 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D))
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +0000931 migrateCFFunctions(Ctx, FD);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000932 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*D))
933 migrateObjCMethodDeclAnnotation(Ctx, MD);
934
Fariborz Jahanian71221352013-07-23 22:42:28 +0000935 // migrate methods which can have instancetype as their result type.
936 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D))
937 migrateInstanceType(Ctx, CDecl);
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000938 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000939
David Blaikiebbafb8a2012-03-11 07:00:24 +0000940 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000941 RewritesReceiver Rec(rewriter);
942 Editor->applyRewrites(Rec);
943
944 for (Rewriter::buffer_iterator
945 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
946 FileID FID = I->first;
947 RewriteBuffer &buf = I->second;
948 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
949 assert(file);
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000950 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000951 llvm::raw_svector_ostream vecOS(newText);
952 buf.write(vecOS);
953 vecOS.flush();
954 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
955 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000956 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000957 FileMgr.FixupRelativePath(filePath);
958 Remapper.remap(filePath.str(), memBuf);
959 }
960
961 if (IsOutputFile) {
962 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
963 } else {
964 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
965 }
966}
967
968bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +0000969 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000970 return true;
971}
972
973ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
974 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000975 PPConditionalDirectiveRecord *
976 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
977 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000978 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
979 /*MigrateLiterals=*/true,
980 /*MigrateSubscripting=*/true,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000981 /*MigrateProperty*/true,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000982 Remapper,
983 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000984 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000985 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000986 /*isOutputFile=*/true);
987}