blob: 1bc0b8c891c70f7aff2216b6d77ed25346d454b4 [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);
Ted Kremenekf7639e12012-03-06 20:06:33 +000041
42public:
43 std::string MigrateDir;
44 bool MigrateLiterals;
45 bool MigrateSubscripting;
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000046 bool MigrateProperty;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000047 OwningPtr<NSAPI> NSAPIObj;
48 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000049 FileRemapper &Remapper;
50 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000051 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000052 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000053 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000054 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
55
Ted Kremenekf7639e12012-03-06 20:06:33 +000056 ObjCMigrateASTConsumer(StringRef migrateDir,
57 bool migrateLiterals,
58 bool migrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000059 bool migrateProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +000060 FileRemapper &remapper,
61 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000062 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000063 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +000064 bool isOutputFile = false)
65 : MigrateDir(migrateDir),
66 MigrateLiterals(migrateLiterals),
67 MigrateSubscripting(migrateSubscripting),
Fariborz Jahaniand83ef842013-07-09 16:59:14 +000068 MigrateProperty(migrateProperty),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000069 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +000070 IsOutputFile(isOutputFile) { }
71
72protected:
73 virtual void Initialize(ASTContext &Context) {
74 NSAPIObj.reset(new NSAPI(Context));
75 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +000076 Context.getLangOpts(),
Ted Kremenekf7639e12012-03-06 20:06:33 +000077 PPRec));
78 }
79
80 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
81 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
82 migrateDecl(*I);
83 return true;
84 }
85 virtual void HandleInterestingDecl(DeclGroupRef DG) {
86 // Ignore decls from the PCH.
87 }
88 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
89 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
90 }
91
92 virtual void HandleTranslationUnit(ASTContext &Ctx);
93};
94
95}
96
97ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
98 StringRef migrateDir,
99 bool migrateLiterals,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000100 bool migrateSubscripting,
101 bool migrateProperty)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000102 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
103 MigrateLiterals(migrateLiterals), MigrateSubscripting(migrateSubscripting),
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000104 MigrateProperty(migrateProperty),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000105 CompInst(0) {
106 if (MigrateDir.empty())
107 MigrateDir = "."; // user current directory if none is given.
108}
109
110ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
111 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000112 PPConditionalDirectiveRecord *
113 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
114 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000115 ASTConsumer *
116 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
117 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
118 MigrateLiterals,
119 MigrateSubscripting,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000120 MigrateProperty,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000121 Remapper,
122 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000123 PPRec,
124 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000125 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
126 return new MultiplexConsumer(Consumers);
127}
128
129bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
130 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
131 /*ignoreIfFilesChanges=*/true);
132 CompInst = &CI;
133 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000134 return true;
135}
136
137namespace {
138class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
139 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000140 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000141
142public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000143 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
144 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000145
146 bool shouldVisitTemplateInstantiations() const { return false; }
147 bool shouldWalkTypesOfTypeLocs() const { return false; }
148
149 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
150 if (Consumer.MigrateLiterals) {
151 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000152 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000153 Consumer.Editor->commit(commit);
154 }
155
156 if (Consumer.MigrateSubscripting) {
157 edit::Commit commit(*Consumer.Editor);
158 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
159 Consumer.Editor->commit(commit);
160 }
161
162 return true;
163 }
164
165 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
166 // Do depth first; we want to rewrite the subexpressions first so that if
167 // we have to move expressions we will move them already rewritten.
168 for (Stmt::child_range range = E->children(); range; ++range)
169 if (!TraverseStmt(*range))
170 return false;
171
172 return WalkUpFromObjCMessageExpr(E);
173 }
174};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000175
176class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
177 ObjCMigrateASTConsumer &Consumer;
178 OwningPtr<ParentMap> PMap;
179
180public:
181 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
182
183 bool shouldVisitTemplateInstantiations() const { return false; }
184 bool shouldWalkTypesOfTypeLocs() const { return false; }
185
186 bool TraverseStmt(Stmt *S) {
187 PMap.reset(new ParentMap(S));
188 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
189 return true;
190 }
191};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000192}
193
194void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
195 if (!D)
196 return;
197 if (isa<ObjCMethodDecl>(D))
198 return; // Wait for the ObjC container declaration.
199
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000200 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000201}
202
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000203static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
204 const ObjCMethodDecl *Setter,
205 const NSAPI &NS, edit::Commit &commit) {
206 ASTContext &Context = NS.getASTContext();
207 std::string PropertyString = "@property";
208 const ParmVarDecl *argDecl = *Setter->param_begin();
209 QualType ArgType = Context.getCanonicalType(argDecl->getType());
210 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
211
212 if (ArgType->isObjCRetainableType() &&
213 propertyLifetime == Qualifiers::OCL_Strong) {
214 if (const ObjCObjectPointerType *ObjPtrTy =
215 ArgType->getAs<ObjCObjectPointerType>()) {
216 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
217 if (IDecl &&
218 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
219 PropertyString += "(copy)";
220 }
221 }
222 else if (propertyLifetime == Qualifiers::OCL_Weak)
223 // TODO. More precise determination of 'weak' attribute requires
224 // looking into setter's implementation for backing weak ivar.
225 PropertyString += "(weak)";
226 else
227 PropertyString += "(unsafe_unretained)";
228
229 // strip off any ARC lifetime qualifier.
230 QualType CanResultTy = Context.getCanonicalType(Getter->getResultType());
231 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
232 Qualifiers Qs = CanResultTy.getQualifiers();
233 Qs.removeObjCLifetime();
234 CanResultTy = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
235 }
236 PropertyString += " ";
237 PropertyString += CanResultTy.getAsString(Context.getPrintingPolicy());
238 PropertyString += " ";
239 PropertyString += Getter->getNameAsString();
240 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
241 Getter->getDeclaratorEndLoc()),
242 PropertyString);
243 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
244 // Get location past ';'
245 EndLoc = EndLoc.getLocWithOffset(1);
246 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
247 return true;
248}
249
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000250void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
251 ObjCInterfaceDecl *D) {
252 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
253 M != MEnd; ++M) {
254 ObjCMethodDecl *Method = (*M);
Fariborz Jahaniande661002013-07-03 23:44:11 +0000255 if (Method->isPropertyAccessor() || Method->param_size() != 0)
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000256 continue;
257 // Is this method candidate to be a getter?
Fariborz Jahaniande661002013-07-03 23:44:11 +0000258 QualType GRT = Method->getResultType();
259 if (GRT->isVoidType())
260 continue;
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000261 // FIXME. Don't know what todo with attributes, skip for now.
262 if (Method->hasAttrs())
263 continue;
264
Fariborz Jahaniande661002013-07-03 23:44:11 +0000265 Selector GetterSelector = Method->getSelector();
266 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
267 Selector SetterSelector =
268 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
269 PP.getSelectorTable(),
270 getterName);
271 if (ObjCMethodDecl *SetterMethod = D->lookupMethod(SetterSelector, true)) {
272 // Is this a valid setter, matching the target getter?
273 QualType SRT = SetterMethod->getResultType();
274 if (!SRT->isVoidType())
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000275 continue;
Fariborz Jahaniande661002013-07-03 23:44:11 +0000276 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000277 QualType ArgType = argDecl->getType();
Fariborz Jahanian7ac20e12013-07-08 22:49:25 +0000278 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT) ||
279 SetterMethod->hasAttrs())
Fariborz Jahanian43bbaac2013-07-04 00:24:32 +0000280 continue;
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000281 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000282 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit);
Fariborz Jahanian266926d2013-07-05 20:46:03 +0000283 Editor->commit(commit);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000284 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000285 }
286}
287
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000288static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000289ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000290 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000291 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000292 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000293 // In auto-synthesis, protocol properties are not synthesized. So,
294 // a conforming protocol must have its required properties declared
295 // in class interface.
296 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
297 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
298 E = PDecl->prop_end(); P != E; ++P) {
299 ObjCPropertyDecl *Property = *P;
300 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
301 continue;
302 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000303 if (R.size() == 0) {
304 // Relax the rule and look into class's implementation for a synthesize
305 // or dynamic declaration. Class is implementing a property coming from
306 // another protocol. This still makes the target protocol as conforming.
307 if (!ImpDecl->FindPropertyImplDecl(
308 Property->getDeclName().getAsIdentifierInfo()))
309 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000310 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000311 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
312 if ((ClassProperty->getPropertyAttributes()
313 != Property->getPropertyAttributes()) ||
314 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
315 return false;
316 }
317 else
318 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000319 }
320 // At this point, all required properties in this protocol conform to those
321 // declared in the class.
322 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000323 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
324 if (PDecl->meth_begin() == PDecl->meth_end())
325 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000326 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
327 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
328 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000329 if (MD->isImplicit())
330 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000331 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
332 continue;
333 bool match = false;
334 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000335 if (R.size() == 0)
336 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000337 for (unsigned I = 0, N = R.size(); I != N; ++I)
338 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
339 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
340 match = true;
341 break;
342 }
343 if (!match)
344 return false;
345 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000346 }
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000347
348 return true;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000349}
350
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000351static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
352 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
353 const NSAPI &NS, edit::Commit &commit) {
354 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
355 std::string ClassString;
356 SourceLocation EndLoc =
357 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
358
359 if (Protocols.empty()) {
360 ClassString = '<';
361 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
362 ClassString += ConformingProtocols[i]->getNameAsString();
363 if (i != (e-1))
364 ClassString += ", ";
365 }
366 ClassString += "> ";
367 }
368 else {
369 ClassString = ", ";
370 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
371 ClassString += ConformingProtocols[i]->getNameAsString();
372 if (i != (e-1))
373 ClassString += ", ";
374 }
375 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
376 EndLoc = *PL;
377 }
378
379 commit.insertAfterToken(EndLoc, ClassString);
380 return true;
381}
382
383static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
384 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000385 const NSAPI &NS, edit::Commit &commit,
386 bool IsNSIntegerType) {
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000387 std::string ClassString =
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000388 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, " : "typedef NS_OPTIONS(NSUInteger, ";
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000389 ClassString += TypedefDcl->getIdentifier()->getName();
390 ClassString += ')';
391 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
392 commit.replace(R, ClassString);
393 SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
394 EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext());
395 if (!EndOfTypedefLoc.isInvalid()) {
396 commit.remove(SourceRange(TypedefDcl->getLocStart(), EndOfTypedefLoc));
397 return true;
398 }
399 return false;
400}
401
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000402static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000403 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000404 const NSAPI &NS, edit::Commit &commit,
405 bool IsNSIntegerType) {
406 std::string ClassString =
407 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000408 ClassString += TypedefDcl->getIdentifier()->getName();
409 ClassString += ')';
410 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
411 commit.replace(R, ClassString);
412 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
413 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
414 return true;
415}
416
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000417static bool UseNSOptionsMacro(ASTContext &Ctx,
418 const EnumDecl *EnumDcl) {
419 bool PowerOfTwo = true;
420 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
421 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
422 EnumConstantDecl *Enumerator = (*EI);
423 const Expr *InitExpr = Enumerator->getInitExpr();
424 if (!InitExpr) {
425 PowerOfTwo = false;
426 continue;
427 }
428 InitExpr = InitExpr->IgnoreImpCasts();
429 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
430 if (BO->isShiftOp() || BO->isBitwiseOp())
431 return true;
432
433 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
434 if (PowerOfTwo && EnumVal && !llvm::isPowerOf2_64(EnumVal))
435 PowerOfTwo = false;
436 }
437 return PowerOfTwo;
438}
439
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000440void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000441 const ObjCImplementationDecl *ImpDecl) {
442 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
443 if (!IDecl || ObjCProtocolDecls.empty())
444 return;
445 // Find all implicit conforming protocols for this class
446 // and make them explicit.
447 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
448 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000449 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000450
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000451 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000452 ObjCProtocolDecls.begin(),
453 E = ObjCProtocolDecls.end(); I != E; ++I)
454 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000455 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000456
457 if (PotentialImplicitProtocols.empty())
458 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000459
460 // go through list of non-optional methods and properties in each protocol
461 // in the PotentialImplicitProtocols list. If class implements every one of the
462 // methods and properties, then this class conforms to this protocol.
463 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
464 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000465 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000466 PotentialImplicitProtocols[i]))
467 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000468
469 if (ConformingProtocols.empty())
470 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000471
472 // Further reduce number of conforming protocols. If protocol P1 is in the list
473 // protocol P2 (P2<P1>), No need to include P1.
474 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
475 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
476 bool DropIt = false;
477 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
478 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
479 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
480 if (PDecl == TargetPDecl)
481 continue;
482 if (PDecl->lookupProtocolNamed(
483 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
484 DropIt = true;
485 break;
486 }
487 }
488 if (!DropIt)
489 MinimalConformingProtocols.push_back(TargetPDecl);
490 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000491 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000492 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
493 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000494 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000495}
496
Fariborz Jahanian92463272013-07-18 20:11:45 +0000497void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
498 const EnumDecl *EnumDcl,
499 const TypedefDecl *TypedefDcl) {
500 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
501 !TypedefDcl->getIdentifier())
502 return;
503
504 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000505 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
506 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000507
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000508 if (!IsNSIntegerType && !IsNSUIntegerType) {
509 // Also check for typedef enum {...} TD;
510 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
511 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000512 bool NSOptions = UseNSOptionsMacro(Ctx, EnumDcl);
513 if (NSOptions) {
514 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
515 return;
516 }
517 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000518 return;
519 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000520 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000521 Editor->commit(commit);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000522 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000523 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000524 return;
525 }
526 if (IsNSIntegerType && UseNSOptionsMacro(Ctx, EnumDcl)) {
527 // We may still use NS_OPTIONS based on what we find in the enumertor list.
528 IsNSIntegerType = false;
529 IsNSUIntegerType = true;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000530 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000531
532 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000533 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
534 return;
535 // NS_OPTIONS must be available.
536 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000537 return;
538 edit::Commit commit(*Editor);
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000539 rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000540 Editor->commit(commit);
541}
542
Ted Kremenekf7639e12012-03-06 20:06:33 +0000543namespace {
544
545class RewritesReceiver : public edit::EditsReceiver {
546 Rewriter &Rewrite;
547
548public:
549 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
550
551 virtual void insert(SourceLocation loc, StringRef text) {
552 Rewrite.InsertText(loc, text);
553 }
554 virtual void replace(CharSourceRange range, StringRef text) {
555 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
556 }
557};
558
559}
560
561void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000562
563 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000564 if (MigrateProperty)
565 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
566 D != DEnd; ++D) {
567 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
568 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000569 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
570 ObjCProtocolDecls.insert(PDecl);
571 else if (const ObjCImplementationDecl *ImpDecl =
572 dyn_cast<ObjCImplementationDecl>(*D))
573 migrateProtocolConformance(Ctx, ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000574 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
575 DeclContext::decl_iterator N = D;
576 ++N;
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000577 if (N != DEnd)
578 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N))
579 migrateNSEnumDecl(Ctx, ED, TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000580 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000581 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000582
David Blaikiebbafb8a2012-03-11 07:00:24 +0000583 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000584 RewritesReceiver Rec(rewriter);
585 Editor->applyRewrites(Rec);
586
587 for (Rewriter::buffer_iterator
588 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
589 FileID FID = I->first;
590 RewriteBuffer &buf = I->second;
591 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
592 assert(file);
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000593 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000594 llvm::raw_svector_ostream vecOS(newText);
595 buf.write(vecOS);
596 vecOS.flush();
597 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
598 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000599 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000600 FileMgr.FixupRelativePath(filePath);
601 Remapper.remap(filePath.str(), memBuf);
602 }
603
604 if (IsOutputFile) {
605 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
606 } else {
607 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
608 }
609}
610
611bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +0000612 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000613 return true;
614}
615
616ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
617 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000618 PPConditionalDirectiveRecord *
619 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
620 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000621 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
622 /*MigrateLiterals=*/true,
623 /*MigrateSubscripting=*/true,
Fariborz Jahaniand83ef842013-07-09 16:59:14 +0000624 /*MigrateProperty*/true,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000625 Remapper,
626 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000627 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000628 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000629 /*isOutputFile=*/true);
630}