blob: c8fc312e6a2b67dc7fe05bb14af6350bce0bf39b [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"
Ted Kremenekf7639e12012-03-06 20:06:33 +000027#include "llvm/ADT/SmallString.h"
28
29using namespace clang;
30using namespace arcmt;
31
32namespace {
33
34class ObjCMigrateASTConsumer : public ASTConsumer {
35 void migrateDecl(Decl *D);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000036 void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCInterfaceDecl *D);
Fariborz Jahanian1be01532013-07-12 22:32:19 +000037 void migrateProtocolConformance(ASTContext &Ctx,
38 const ObjCImplementationDecl *ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +000039 void migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
40 const TypedefDecl *TypedefDcl);
Fariborz Jahanian71221352013-07-23 22:42:28 +000041 void migrateInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000042 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
43 ObjCMethodDecl *OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000044 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000045 ObjCMethodDecl *OM,
46 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Ted Kremenekf7639e12012-03-06 20:06:33 +000047
48public:
49 std::string MigrateDir;
50 bool MigrateLiterals;
51 bool MigrateSubscripting;
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000052 bool MigrateProperty;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000053 OwningPtr<NSAPI> NSAPIObj;
54 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000055 FileRemapper &Remapper;
56 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000057 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000058 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000059 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000060 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
61
Ted Kremenekf7639e12012-03-06 20:06:33 +000062 ObjCMigrateASTConsumer(StringRef migrateDir,
63 bool migrateLiterals,
64 bool migrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000065 bool migrateProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +000066 FileRemapper &remapper,
67 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000068 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000069 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +000070 bool isOutputFile = false)
71 : MigrateDir(migrateDir),
72 MigrateLiterals(migrateLiterals),
73 MigrateSubscripting(migrateSubscripting),
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000074 MigrateProperty(migrateProperty),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000075 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +000076 IsOutputFile(isOutputFile) { }
77
78protected:
79 virtual void Initialize(ASTContext &Context) {
80 NSAPIObj.reset(new NSAPI(Context));
81 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +000082 Context.getLangOpts(),
Ted Kremenekf7639e12012-03-06 20:06:33 +000083 PPRec));
84 }
85
86 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
87 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
88 migrateDecl(*I);
89 return true;
90 }
91 virtual void HandleInterestingDecl(DeclGroupRef DG) {
92 // Ignore decls from the PCH.
93 }
94 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
95 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
96 }
97
98 virtual void HandleTranslationUnit(ASTContext &Ctx);
99};
100
101}
102
103ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
104 StringRef migrateDir,
105 bool migrateLiterals,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000106 bool migrateSubscripting,
107 bool migrateProperty)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000108 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
109 MigrateLiterals(migrateLiterals), MigrateSubscripting(migrateSubscripting),
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000110 MigrateProperty(migrateProperty),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000111 CompInst(0) {
112 if (MigrateDir.empty())
113 MigrateDir = "."; // user current directory if none is given.
114}
115
116ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
117 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000118 PPConditionalDirectiveRecord *
119 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
120 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000121 ASTConsumer *
122 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
123 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
124 MigrateLiterals,
125 MigrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000126 MigrateProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000127 Remapper,
128 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000129 PPRec,
130 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000131 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
132 return new MultiplexConsumer(Consumers);
133}
134
135bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
136 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
137 /*ignoreIfFilesChanges=*/true);
138 CompInst = &CI;
139 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000140 return true;
141}
142
143namespace {
144class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
145 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000146 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000147
148public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000149 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
150 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000151
152 bool shouldVisitTemplateInstantiations() const { return false; }
153 bool shouldWalkTypesOfTypeLocs() const { return false; }
154
155 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
156 if (Consumer.MigrateLiterals) {
157 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000158 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000159 Consumer.Editor->commit(commit);
160 }
161
162 if (Consumer.MigrateSubscripting) {
163 edit::Commit commit(*Consumer.Editor);
164 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
165 Consumer.Editor->commit(commit);
166 }
167
168 return true;
169 }
170
171 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
172 // Do depth first; we want to rewrite the subexpressions first so that if
173 // we have to move expressions we will move them already rewritten.
174 for (Stmt::child_range range = E->children(); range; ++range)
175 if (!TraverseStmt(*range))
176 return false;
177
178 return WalkUpFromObjCMessageExpr(E);
179 }
180};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000181
182class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
183 ObjCMigrateASTConsumer &Consumer;
184 OwningPtr<ParentMap> PMap;
185
186public:
187 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
188
189 bool shouldVisitTemplateInstantiations() const { return false; }
190 bool shouldWalkTypesOfTypeLocs() const { return false; }
191
192 bool TraverseStmt(Stmt *S) {
193 PMap.reset(new ParentMap(S));
194 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
195 return true;
196 }
197};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000198}
199
200void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
201 if (!D)
202 return;
203 if (isa<ObjCMethodDecl>(D))
204 return; // Wait for the ObjC container declaration.
205
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000206 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000207}
208
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000209static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
210 const ObjCMethodDecl *Setter,
211 const NSAPI &NS, edit::Commit &commit) {
212 ASTContext &Context = NS.getASTContext();
213 std::string PropertyString = "@property";
214 const ParmVarDecl *argDecl = *Setter->param_begin();
215 QualType ArgType = Context.getCanonicalType(argDecl->getType());
216 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
217
218 if (ArgType->isObjCRetainableType() &&
219 propertyLifetime == Qualifiers::OCL_Strong) {
220 if (const ObjCObjectPointerType *ObjPtrTy =
221 ArgType->getAs<ObjCObjectPointerType>()) {
222 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
223 if (IDecl &&
224 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
225 PropertyString += "(copy)";
226 }
227 }
228 else if (propertyLifetime == Qualifiers::OCL_Weak)
229 // TODO. More precise determination of 'weak' attribute requires
230 // looking into setter's implementation for backing weak ivar.
231 PropertyString += "(weak)";
232 else
233 PropertyString += "(unsafe_unretained)";
234
235 // strip off any ARC lifetime qualifier.
236 QualType CanResultTy = Context.getCanonicalType(Getter->getResultType());
237 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
238 Qualifiers Qs = CanResultTy.getQualifiers();
239 Qs.removeObjCLifetime();
240 CanResultTy = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
241 }
242 PropertyString += " ";
243 PropertyString += CanResultTy.getAsString(Context.getPrintingPolicy());
244 PropertyString += " ";
245 PropertyString += Getter->getNameAsString();
246 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
247 Getter->getDeclaratorEndLoc()),
248 PropertyString);
249 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
250 // Get location past ';'
251 EndLoc = EndLoc.getLocWithOffset(1);
252 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
253 return true;
254}
255
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000256void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
257 ObjCInterfaceDecl *D) {
258 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
259 M != MEnd; ++M) {
260 ObjCMethodDecl *Method = (*M);
Fariborz Jahaniande661002013-07-03 23:44:11 +0000261 if (Method->isPropertyAccessor() || Method->param_size() != 0)
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000262 continue;
263 // Is this method candidate to be a getter?
Fariborz Jahaniande661002013-07-03 23:44:11 +0000264 QualType GRT = Method->getResultType();
265 if (GRT->isVoidType())
266 continue;
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000267 // FIXME. Don't know what todo with attributes, skip for now.
268 if (Method->hasAttrs())
269 continue;
270
Fariborz Jahaniande661002013-07-03 23:44:11 +0000271 Selector GetterSelector = Method->getSelector();
272 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
273 Selector SetterSelector =
274 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
275 PP.getSelectorTable(),
276 getterName);
277 if (ObjCMethodDecl *SetterMethod = D->lookupMethod(SetterSelector, true)) {
278 // Is this a valid setter, matching the target getter?
279 QualType SRT = SetterMethod->getResultType();
280 if (!SRT->isVoidType())
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000281 continue;
Fariborz Jahaniande661002013-07-03 23:44:11 +0000282 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000283 QualType ArgType = argDecl->getType();
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000284 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT) ||
285 SetterMethod->hasAttrs())
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000286 continue;
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000287 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000288 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit);
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000289 Editor->commit(commit);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000290 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000291 }
292}
293
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000294static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000295ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000296 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000297 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000298 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000299 // In auto-synthesis, protocol properties are not synthesized. So,
300 // a conforming protocol must have its required properties declared
301 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000302 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000303 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
304 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
305 E = PDecl->prop_end(); P != E; ++P) {
306 ObjCPropertyDecl *Property = *P;
307 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
308 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000309 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000310 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000311 if (R.size() == 0) {
312 // Relax the rule and look into class's implementation for a synthesize
313 // or dynamic declaration. Class is implementing a property coming from
314 // another protocol. This still makes the target protocol as conforming.
315 if (!ImpDecl->FindPropertyImplDecl(
316 Property->getDeclName().getAsIdentifierInfo()))
317 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000318 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000319 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
320 if ((ClassProperty->getPropertyAttributes()
321 != Property->getPropertyAttributes()) ||
322 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
323 return false;
324 }
325 else
326 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000327 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000328
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000329 // At this point, all required properties in this protocol conform to those
330 // declared in the class.
331 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000332 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000333 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
334 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000335 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000336 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
337 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
338 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000339 if (MD->isImplicit())
340 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000341 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
342 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000343 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000344 if (R.size() == 0)
345 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000346 bool match = false;
347 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000348 for (unsigned I = 0, N = R.size(); I != N; ++I)
349 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
350 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
351 match = true;
352 break;
353 }
354 if (!match)
355 return false;
356 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000357 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000358 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
359 return true;
360 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000361}
362
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000363static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
364 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
365 const NSAPI &NS, edit::Commit &commit) {
366 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
367 std::string ClassString;
368 SourceLocation EndLoc =
369 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
370
371 if (Protocols.empty()) {
372 ClassString = '<';
373 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
374 ClassString += ConformingProtocols[i]->getNameAsString();
375 if (i != (e-1))
376 ClassString += ", ";
377 }
378 ClassString += "> ";
379 }
380 else {
381 ClassString = ", ";
382 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
383 ClassString += ConformingProtocols[i]->getNameAsString();
384 if (i != (e-1))
385 ClassString += ", ";
386 }
387 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
388 EndLoc = *PL;
389 }
390
391 commit.insertAfterToken(EndLoc, ClassString);
392 return true;
393}
394
395static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
396 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000397 const NSAPI &NS, edit::Commit &commit,
398 bool IsNSIntegerType) {
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000399 std::string ClassString =
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000400 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, " : "typedef NS_OPTIONS(NSUInteger, ";
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000401 ClassString += TypedefDcl->getIdentifier()->getName();
402 ClassString += ')';
403 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
404 commit.replace(R, ClassString);
405 SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
406 EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext());
407 if (!EndOfTypedefLoc.isInvalid()) {
408 commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc));
409 return true;
410 }
411 return false;
412}
413
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000414static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000415 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000416 const NSAPI &NS, edit::Commit &commit,
417 bool IsNSIntegerType) {
418 std::string ClassString =
419 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000420 ClassString += TypedefDcl->getIdentifier()->getName();
421 ClassString += ')';
422 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
423 commit.replace(R, ClassString);
424 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
425 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
426 return true;
427}
428
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000429static bool UseNSOptionsMacro(ASTContext &Ctx,
430 const EnumDecl *EnumDcl) {
431 bool PowerOfTwo = true;
432 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
433 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
434 EnumConstantDecl *Enumerator = (*EI);
435 const Expr *InitExpr = Enumerator->getInitExpr();
436 if (!InitExpr) {
437 PowerOfTwo = false;
438 continue;
439 }
440 InitExpr = InitExpr->IgnoreImpCasts();
441 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
442 if (BO->isShiftOp() || BO->isBitwiseOp())
443 return true;
444
445 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
446 if (PowerOfTwo && EnumVal && !llvm::isPowerOf2_64(EnumVal))
447 PowerOfTwo = false;
448 }
449 return PowerOfTwo;
450}
451
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000452void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000453 const ObjCImplementationDecl *ImpDecl) {
454 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
455 if (!IDecl || ObjCProtocolDecls.empty())
456 return;
457 // Find all implicit conforming protocols for this class
458 // and make them explicit.
459 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
460 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000461 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000462
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000463 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000464 ObjCProtocolDecls.begin(),
465 E = ObjCProtocolDecls.end(); I != E; ++I)
466 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000467 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000468
469 if (PotentialImplicitProtocols.empty())
470 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000471
472 // go through list of non-optional methods and properties in each protocol
473 // in the PotentialImplicitProtocols list. If class implements every one of the
474 // methods and properties, then this class conforms to this protocol.
475 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
476 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000477 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000478 PotentialImplicitProtocols[i]))
479 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000480
481 if (ConformingProtocols.empty())
482 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000483
484 // Further reduce number of conforming protocols. If protocol P1 is in the list
485 // protocol P2 (P2<P1>), No need to include P1.
486 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
487 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
488 bool DropIt = false;
489 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
490 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
491 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
492 if (PDecl == TargetPDecl)
493 continue;
494 if (PDecl->lookupProtocolNamed(
495 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
496 DropIt = true;
497 break;
498 }
499 }
500 if (!DropIt)
501 MinimalConformingProtocols.push_back(TargetPDecl);
502 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000503 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000504 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
505 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000506 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000507}
508
Fariborz Jahanian92463272013-07-18 20:11:45 +0000509void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
510 const EnumDecl *EnumDcl,
511 const TypedefDecl *TypedefDcl) {
512 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
513 !TypedefDcl->getIdentifier())
514 return;
515
516 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000517 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
518 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000519
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000520 if (!IsNSIntegerType && !IsNSUIntegerType) {
521 // Also check for typedef enum {...} TD;
522 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
523 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000524 bool NSOptions = UseNSOptionsMacro(Ctx, EnumDcl);
525 if (NSOptions) {
526 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
527 return;
528 }
529 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000530 return;
531 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000532 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000533 Editor->commit(commit);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000534 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000535 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000536 return;
537 }
538 if (IsNSIntegerType && UseNSOptionsMacro(Ctx, EnumDcl)) {
539 // We may still use NS_OPTIONS based on what we find in the enumertor list.
540 IsNSIntegerType = false;
541 IsNSUIntegerType = true;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000542 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000543
544 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000545 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
546 return;
547 // NS_OPTIONS must be available.
548 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000549 return;
550 edit::Commit commit(*Editor);
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000551 rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000552 Editor->commit(commit);
553}
554
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000555static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
556 ObjCMethodDecl *OM) {
557 SourceRange R;
558 std::string ClassString;
559 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
560 TypeLoc TL = TSInfo->getTypeLoc();
561 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
562 ClassString = "instancetype";
563 }
564 else {
565 R = SourceRange(OM->getLocStart(), OM->getLocStart());
566 ClassString = OM->isInstanceMethod() ? '-' : '+';
567 ClassString += " (instancetype)";
568 }
569 edit::Commit commit(*ASTC.Editor);
570 commit.replace(R, ClassString);
571 ASTC.Editor->commit(commit);
572}
573
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000574void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
575 ObjCContainerDecl *CDecl,
576 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +0000577 ObjCInstanceTypeFamily OIT_Family =
578 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000579
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000580 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000581 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000582 case OIT_None:
583 migrateFactoryMethod(Ctx, CDecl, OM);
584 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000585 case OIT_Array:
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000586 ClassName = "NSArray";
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000587 break;
588 case OIT_Dictionary:
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000589 ClassName = "NSDictionary";
590 break;
591 case OIT_MemManage:
592 ClassName = "NSObject";
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000593 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000594 case OIT_Singleton:
595 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000596 return;
597 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000598 if (!OM->getResultType()->isObjCIdType())
599 return;
600
601 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
602 if (!IDecl) {
603 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
604 IDecl = CatDecl->getClassInterface();
605 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
606 IDecl = ImpDecl->getClassInterface();
607 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000608 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000609 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
610 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000611 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000612 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000613 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000614}
615
616void ObjCMigrateASTConsumer::migrateInstanceType(ASTContext &Ctx,
617 ObjCContainerDecl *CDecl) {
618 // migrate methods which can have instancetype as their result type.
619 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
620 MEnd = CDecl->meth_end();
621 M != MEnd; ++M) {
622 ObjCMethodDecl *Method = (*M);
623 migrateMethodInstanceType(Ctx, CDecl, Method);
624 }
625}
626
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000627void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
628 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000629 ObjCMethodDecl *OM,
630 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +0000631 if (OM->isInstanceMethod() ||
632 OM->getResultType() == Ctx.getObjCInstanceType() ||
633 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000634 return;
635
636 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
637 // NSYYYNamE with matching names be at least 3 characters long.
638 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
639 if (!IDecl) {
640 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
641 IDecl = CatDecl->getClassInterface();
642 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
643 IDecl = ImpDecl->getClassInterface();
644 }
645 if (!IDecl)
646 return;
647
648 std::string StringClassName = IDecl->getName();
649 StringRef LoweredClassName(StringClassName);
650 std::string StringLoweredClassName = LoweredClassName.lower();
651 LoweredClassName = StringLoweredClassName;
652
653 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
654 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000655 if (OIT_Family == OIT_Singleton) {
656 StringRef STRefMethodName(MethodName);
657 size_t len = 0;
658 if (STRefMethodName.startswith("standard"))
659 len = strlen("standard");
660 else if (STRefMethodName.startswith("shared"))
661 len = strlen("shared");
662 else if (STRefMethodName.startswith("default"))
663 len = strlen("default");
664 else
665 return;
666 MethodName = STRefMethodName.substr(len);
667 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000668 std::string MethodNameSubStr = MethodName.substr(0, 3);
669 StringRef MethodNamePrefix(MethodNameSubStr);
670 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
671 MethodNamePrefix = StringLoweredMethodNamePrefix;
672 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
673 if (Ix == StringRef::npos)
674 return;
675 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
676 StringRef LoweredMethodName(MethodName);
677 std::string StringLoweredMethodName = LoweredMethodName.lower();
678 LoweredMethodName = StringLoweredMethodName;
679 if (!LoweredMethodName.startswith(ClassNamePostfix))
680 return;
681 ReplaceWithInstancetype(*this, OM);
682}
683
Ted Kremenekf7639e12012-03-06 20:06:33 +0000684namespace {
685
686class RewritesReceiver : public edit::EditsReceiver {
687 Rewriter &Rewrite;
688
689public:
690 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
691
692 virtual void insert(SourceLocation loc, StringRef text) {
693 Rewrite.InsertText(loc, text);
694 }
695 virtual void replace(CharSourceRange range, StringRef text) {
696 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
697 }
698};
699
700}
701
702void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000703
704 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000705 if (MigrateProperty)
706 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
707 D != DEnd; ++D) {
708 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
709 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000710 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
711 ObjCProtocolDecls.insert(PDecl);
712 else if (const ObjCImplementationDecl *ImpDecl =
713 dyn_cast<ObjCImplementationDecl>(*D))
714 migrateProtocolConformance(Ctx, ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000715 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
716 DeclContext::decl_iterator N = D;
717 ++N;
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000718 if (N != DEnd)
719 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N))
720 migrateNSEnumDecl(Ctx, ED, TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000721 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000722 // migrate methods which can have instancetype as their result type.
723 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D))
724 migrateInstanceType(Ctx, CDecl);
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000725 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000726
David Blaikiebbafb8a2012-03-11 07:00:24 +0000727 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000728 RewritesReceiver Rec(rewriter);
729 Editor->applyRewrites(Rec);
730
731 for (Rewriter::buffer_iterator
732 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
733 FileID FID = I->first;
734 RewriteBuffer &buf = I->second;
735 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
736 assert(file);
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000737 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000738 llvm::raw_svector_ostream vecOS(newText);
739 buf.write(vecOS);
740 vecOS.flush();
741 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
742 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000743 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000744 FileMgr.FixupRelativePath(filePath);
745 Remapper.remap(filePath.str(), memBuf);
746 }
747
748 if (IsOutputFile) {
749 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
750 } else {
751 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
752 }
753}
754
755bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +0000756 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000757 return true;
758}
759
760ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
761 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000762 PPConditionalDirectiveRecord *
763 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
764 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000765 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
766 /*MigrateLiterals=*/true,
767 /*MigrateSubscripting=*/true,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000768 /*MigrateProperty*/true,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000769 Remapper,
770 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000771 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000772 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000773 /*isOutputFile=*/true);
774}