blob: cd4b284e7dfb4e8a54e277d98eb982714151dccf [file] [log] [blame]
Ted Kremenekf7639e12012-03-06 20:06:33 +00001//===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Fariborz Jahanian85e988b2013-07-18 22:17:33 +000010#include "Transforms.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000011#include "clang/ARCMigrate/ARCMTActions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000012#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/NSAPI.h"
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +000015#include "clang/AST/ParentMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/RecursiveASTVisitor.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Edit/Commit.h"
19#include "clang/Edit/EditedSource.h"
20#include "clang/Edit/EditsReceiver.h"
21#include "clang/Edit/Rewriters.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000022#include "clang/Frontend/CompilerInstance.h"
23#include "clang/Frontend/MultiplexConsumer.h"
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000024#include "clang/Lex/PPConditionalDirectiveRecord.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Rewrite/Core/Rewriter.h"
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +000027#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000028#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000029#include "clang/AST/Attr.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000030#include "llvm/ADT/SmallString.h"
31
32using namespace clang;
33using namespace arcmt;
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000034using namespace ento::objc_retain;
Ted Kremenekf7639e12012-03-06 20:06:33 +000035
36namespace {
37
38class ObjCMigrateASTConsumer : public ASTConsumer {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000039 enum CF_BRIDGING_KIND {
40 CF_BRIDGING_NONE,
41 CF_BRIDGING_ENABLE,
42 CF_BRIDGING_MAY_INCLUDE
43 };
44
Ted Kremenekf7639e12012-03-06 20:06:33 +000045 void migrateDecl(Decl *D);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000046 void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCContainerDecl *D);
Fariborz Jahanian1be01532013-07-12 22:32:19 +000047 void migrateProtocolConformance(ASTContext &Ctx,
48 const ObjCImplementationDecl *ImpDecl);
Fariborz Jahanian92463272013-07-18 20:11:45 +000049 void migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
50 const TypedefDecl *TypedefDcl);
Fariborz Jahanian8c45e282013-10-02 22:49:59 +000051 void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000052 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
53 ObjCMethodDecl *OM);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000054 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +000055 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
Fariborz Jahanian10b74352013-09-24 20:20:52 +000056 void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000057 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000058 ObjCMethodDecl *OM,
59 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000060
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000061 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000062 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000063 const FunctionDecl *FuncDecl, bool ResultAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000064 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000065 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000066
Fariborz Jahanian301b5212013-08-20 22:42:13 +000067 void AnnotateImplicitBridging(ASTContext &Ctx);
68
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000069 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
70 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000071
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000072 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
73
Fariborz Jahanian89f6d102013-09-04 00:10:06 +000074 void migrateAddMethodAnnotation(ASTContext &Ctx,
75 const ObjCMethodDecl *MethodDecl);
Ted Kremenekf7639e12012-03-06 20:06:33 +000076public:
77 std::string MigrateDir;
Fariborz Jahanian182486c2013-10-02 17:08:12 +000078 unsigned ASTMigrateActions;
Fariborz Jahanianb8343522013-08-20 23:35:26 +000079 unsigned FileId;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000080 OwningPtr<NSAPI> NSAPIObj;
81 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000082 FileRemapper &Remapper;
83 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000084 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000085 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000086 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000087 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000088 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000089
Ted Kremenekf7639e12012-03-06 20:06:33 +000090 ObjCMigrateASTConsumer(StringRef migrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +000091 unsigned astMigrateActions,
Ted Kremenekf7639e12012-03-06 20:06:33 +000092 FileRemapper &remapper,
93 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000094 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000095 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +000096 bool isOutputFile = false)
97 : MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +000098 ASTMigrateActions(astMigrateActions),
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +000099 FileId(0), Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000100 IsOutputFile(isOutputFile) { }
101
102protected:
103 virtual void Initialize(ASTContext &Context) {
104 NSAPIObj.reset(new NSAPI(Context));
105 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000106 Context.getLangOpts(),
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +0000107 PPRec, false));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000108 }
109
110 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
111 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
112 migrateDecl(*I);
113 return true;
114 }
115 virtual void HandleInterestingDecl(DeclGroupRef DG) {
116 // Ignore decls from the PCH.
117 }
118 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
119 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
120 }
121
122 virtual void HandleTranslationUnit(ASTContext &Ctx);
123};
124
125}
126
127ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000128 StringRef migrateDir,
129 unsigned migrateAction)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000130 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000131 ObjCMigAction(migrateAction),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000132 CompInst(0) {
133 if (MigrateDir.empty())
134 MigrateDir = "."; // user current directory if none is given.
135}
136
137ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
138 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000139 PPConditionalDirectiveRecord *
140 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
141 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000142 ASTConsumer *
143 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
144 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000145 ObjCMigAction,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000146 Remapper,
147 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000148 PPRec,
149 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000150 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
151 return new MultiplexConsumer(Consumers);
152}
153
154bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
155 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
156 /*ignoreIfFilesChanges=*/true);
157 CompInst = &CI;
158 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000159 return true;
160}
161
162namespace {
163class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
164 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000165 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000166
167public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000168 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
169 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000170
171 bool shouldVisitTemplateInstantiations() const { return false; }
172 bool shouldWalkTypesOfTypeLocs() const { return false; }
173
174 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000175 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000176 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000177 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000178 Consumer.Editor->commit(commit);
179 }
180
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000181 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000182 edit::Commit commit(*Consumer.Editor);
183 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
184 Consumer.Editor->commit(commit);
185 }
186
187 return true;
188 }
189
190 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
191 // Do depth first; we want to rewrite the subexpressions first so that if
192 // we have to move expressions we will move them already rewritten.
193 for (Stmt::child_range range = E->children(); range; ++range)
194 if (!TraverseStmt(*range))
195 return false;
196
197 return WalkUpFromObjCMessageExpr(E);
198 }
199};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000200
201class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
202 ObjCMigrateASTConsumer &Consumer;
203 OwningPtr<ParentMap> PMap;
204
205public:
206 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
207
208 bool shouldVisitTemplateInstantiations() const { return false; }
209 bool shouldWalkTypesOfTypeLocs() const { return false; }
210
211 bool TraverseStmt(Stmt *S) {
212 PMap.reset(new ParentMap(S));
213 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
214 return true;
215 }
216};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000217}
218
219void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
220 if (!D)
221 return;
222 if (isa<ObjCMethodDecl>(D))
223 return; // Wait for the ObjC container declaration.
224
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000225 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000226}
227
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000228static void append_attr(std::string &PropertyString, const char *attr) {
229 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000230 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000231}
232
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000233static
234void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
235 const std::string& TypeString,
236 const char *name) {
237 const char *argPtr = TypeString.c_str();
238 int paren = 0;
239 while (*argPtr) {
240 switch (*argPtr) {
241 case '(':
242 PropertyString += *argPtr;
243 paren++;
244 break;
245 case ')':
246 PropertyString += *argPtr;
247 paren--;
248 break;
249 case '^':
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000250 case '*':
251 PropertyString += (*argPtr);
252 if (paren == 1) {
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000253 PropertyString += name;
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000254 name = "";
255 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000256 break;
257 default:
258 PropertyString += *argPtr;
259 break;
260 }
261 argPtr++;
262 }
263}
264
265
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000266static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
267 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000268 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000269 unsigned LengthOfPrefix,
270 bool Atomic) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000271 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000272 std::string PropertyString = "@property (";
273 PropertyString += (Atomic ? "atomic" : "nonatomic");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000274 std::string PropertyNameString = Getter->getNameAsString();
275 StringRef PropertyName(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000276 if (LengthOfPrefix > 0) {
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000277 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000278 PropertyString += PropertyNameString;
279 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000280 // Property with no setter may be suggested as a 'readonly' property.
281 if (!Setter)
282 append_attr(PropertyString, "readonly");
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000283
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000284 // Short circuit properties that contain the name "delegate" or "dataSource",
285 // or have exact name "target" to have unsafe_unretained attribute.
286 if (PropertyName.equals("target") ||
287 (PropertyName.find("delegate") != StringRef::npos) ||
288 (PropertyName.find("dataSource") != StringRef::npos))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000289 append_attr(PropertyString, "unsafe_unretained");
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000290 else if (Setter) {
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000291 const ParmVarDecl *argDecl = *Setter->param_begin();
292 QualType ArgType = Context.getCanonicalType(argDecl->getType());
293 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
294 bool RetainableObject = ArgType->isObjCRetainableType();
295 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
296 if (const ObjCObjectPointerType *ObjPtrTy =
297 ArgType->getAs<ObjCObjectPointerType>()) {
298 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
299 if (IDecl &&
300 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000301 append_attr(PropertyString, "copy");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000302 else
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000303 append_attr(PropertyString, "retain");
304 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000305 else if (ArgType->isBlockPointerType())
306 append_attr(PropertyString, "copy");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000307 } else if (propertyLifetime == Qualifiers::OCL_Weak)
308 // TODO. More precise determination of 'weak' attribute requires
309 // looking into setter's implementation for backing weak ivar.
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000310 append_attr(PropertyString, "weak");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000311 else if (RetainableObject)
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000312 append_attr(PropertyString,
313 ArgType->isBlockPointerType() ? "copy" : "retain");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000314 }
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000315 PropertyString += ')';
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000316 QualType RT = Getter->getResultType();
317 if (!isa<TypedefType>(RT)) {
318 // strip off any ARC lifetime qualifier.
319 QualType CanResultTy = Context.getCanonicalType(RT);
320 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
321 Qualifiers Qs = CanResultTy.getQualifiers();
322 Qs.removeObjCLifetime();
323 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
324 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000325 }
326 PropertyString += " ";
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000327 PrintingPolicy SubPolicy(Context.getPrintingPolicy());
328 SubPolicy.SuppressStrongLifetime = true;
Fariborz Jahaniande557f82013-10-09 17:37:28 +0000329 SubPolicy.SuppressLifetimeQualifiers = true;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000330 std::string TypeString = RT.getAsString(SubPolicy);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000331 if (LengthOfPrefix > 0) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000332 // property name must strip off "is" and lower case the first character
333 // after that; e.g. isContinuous will become continuous.
334 StringRef PropertyNameStringRef(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000335 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000336 PropertyNameString = PropertyNameStringRef;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000337 bool NoLowering = (isUppercase(PropertyNameString[0]) &&
338 PropertyNameString.size() > 1 &&
339 isUppercase(PropertyNameString[1]));
Fariborz Jahanian34fea362013-09-11 18:27:16 +0000340 if (!NoLowering)
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000341 PropertyNameString[0] = toLowercase(PropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000342 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000343 if (RT->isBlockPointerType() || RT->isFunctionPointerType())
344 MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
345 TypeString,
346 PropertyNameString.c_str());
347 else {
348 char LastChar = TypeString[TypeString.size()-1];
349 PropertyString += TypeString;
350 if (LastChar != '*')
351 PropertyString += ' ';
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000352 PropertyString += PropertyNameString;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000353 }
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000354 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
355 Selector GetterSelector = Getter->getSelector();
356
357 SourceLocation EndGetterSelectorLoc =
358 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000359 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000360 EndGetterSelectorLoc),
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000361 PropertyString);
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000362 if (Setter) {
363 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
364 // Get location past ';'
365 EndLoc = EndLoc.getLocWithOffset(1);
366 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
367 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000368 return true;
369}
370
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000371void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000372 ObjCContainerDecl *D) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000373 if (D->isDeprecated())
374 return;
375
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000376 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
377 M != MEnd; ++M) {
378 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000379 if (Method->isDeprecated())
380 continue;
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000381 migrateProperty(Ctx, D, Method);
Fariborz Jahanian8c45e282013-10-02 22:49:59 +0000382 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
383 migrateNsReturnsInnerPointer(Ctx, Method);
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000384 }
385 for (ObjCContainerDecl::prop_iterator P = D->prop_begin(),
386 E = D->prop_end(); P != E; ++P) {
387 ObjCPropertyDecl *Prop = *P;
Fariborz Jahanian8c45e282013-10-02 22:49:59 +0000388 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
389 !P->isDeprecated())
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000390 migratePropertyNsReturnsInnerPointer(Ctx, Prop);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000391 }
392}
393
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000394static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000395ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000396 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000397 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000398 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000399 // In auto-synthesis, protocol properties are not synthesized. So,
400 // a conforming protocol must have its required properties declared
401 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000402 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000403 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
404 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
405 E = PDecl->prop_end(); P != E; ++P) {
406 ObjCPropertyDecl *Property = *P;
407 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
408 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000409 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000410 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000411 if (R.size() == 0) {
412 // Relax the rule and look into class's implementation for a synthesize
413 // or dynamic declaration. Class is implementing a property coming from
414 // another protocol. This still makes the target protocol as conforming.
415 if (!ImpDecl->FindPropertyImplDecl(
416 Property->getDeclName().getAsIdentifierInfo()))
417 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000418 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000419 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
420 if ((ClassProperty->getPropertyAttributes()
421 != Property->getPropertyAttributes()) ||
422 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
423 return false;
424 }
425 else
426 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000427 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000428
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000429 // At this point, all required properties in this protocol conform to those
430 // declared in the class.
431 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000432 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000433 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
434 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000435 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000436 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
437 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
438 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000439 if (MD->isImplicit())
440 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000441 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
442 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000443 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000444 if (R.size() == 0)
445 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000446 bool match = false;
447 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000448 for (unsigned I = 0, N = R.size(); I != N; ++I)
449 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
450 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
451 match = true;
452 break;
453 }
454 if (!match)
455 return false;
456 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000457 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000458 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
459 return true;
460 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000461}
462
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000463static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
464 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
465 const NSAPI &NS, edit::Commit &commit) {
466 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
467 std::string ClassString;
468 SourceLocation EndLoc =
469 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
470
471 if (Protocols.empty()) {
472 ClassString = '<';
473 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
474 ClassString += ConformingProtocols[i]->getNameAsString();
475 if (i != (e-1))
476 ClassString += ", ";
477 }
478 ClassString += "> ";
479 }
480 else {
481 ClassString = ", ";
482 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
483 ClassString += ConformingProtocols[i]->getNameAsString();
484 if (i != (e-1))
485 ClassString += ", ";
486 }
487 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
488 EndLoc = *PL;
489 }
490
491 commit.insertAfterToken(EndLoc, ClassString);
492 return true;
493}
494
495static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
496 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000497 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000498 bool IsNSIntegerType,
499 bool NSOptions) {
500 std::string ClassString;
501 if (NSOptions)
502 ClassString = "typedef NS_OPTIONS(NSUInteger, ";
503 else
504 ClassString =
505 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, "
506 : "typedef NS_ENUM(NSUInteger, ";
507
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000508 ClassString += TypedefDcl->getIdentifier()->getName();
509 ClassString += ')';
510 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
511 commit.replace(R, ClassString);
512 SourceLocation EndOfTypedefLoc = TypedefDcl->getLocEnd();
Fariborz Jahanian1d27ffd2013-10-11 17:35:22 +0000513 EndOfTypedefLoc = trans::findLocationAfterSemi(EndOfTypedefLoc, NS.getASTContext(),
514 /*IsDecl*/true);
Fariborz Jahanian9218f512013-10-10 23:57:58 +0000515 SourceLocation BeginOfTypedefLoc = TypedefDcl->getLocStart();
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000516 if (!EndOfTypedefLoc.isInvalid()) {
Fariborz Jahanian9218f512013-10-10 23:57:58 +0000517 // FIXME. This assumes that typedef decl; is immediately preceeded by eoln.
518 // It is trying to remove the typedef decl. line entirely.
519 BeginOfTypedefLoc = BeginOfTypedefLoc.getLocWithOffset(-1);
520 commit.remove(SourceRange(BeginOfTypedefLoc, EndOfTypedefLoc));
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000521 return true;
522 }
523 return false;
524}
525
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000526static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000527 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000528 const NSAPI &NS, edit::Commit &commit,
529 bool IsNSIntegerType) {
530 std::string ClassString =
531 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000532 ClassString += TypedefDcl->getIdentifier()->getName();
533 ClassString += ')';
534 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
535 commit.replace(R, ClassString);
536 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
537 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
538 return true;
539}
540
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000541static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000542 const EnumDecl *EnumDcl) {
543 bool PowerOfTwo = true;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000544 bool AllHexdecimalEnumerator = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000545 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000546 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
547 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
548 EnumConstantDecl *Enumerator = (*EI);
549 const Expr *InitExpr = Enumerator->getInitExpr();
550 if (!InitExpr) {
551 PowerOfTwo = false;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000552 AllHexdecimalEnumerator = false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000553 continue;
554 }
Fariborz Jahanian6e1798e2013-09-17 23:32:51 +0000555 InitExpr = InitExpr->IgnoreParenCasts();
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000556 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
557 if (BO->isShiftOp() || BO->isBitwiseOp())
558 return true;
559
560 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000561 if (PowerOfTwo && EnumVal) {
562 if (!llvm::isPowerOf2_64(EnumVal))
563 PowerOfTwo = false;
564 else if (EnumVal > MaxPowerOfTwoVal)
565 MaxPowerOfTwoVal = EnumVal;
566 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000567 if (AllHexdecimalEnumerator && EnumVal) {
568 bool FoundHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000569 SourceLocation EndLoc = Enumerator->getLocEnd();
570 Token Tok;
571 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
572 if (Tok.isLiteral() && Tok.getLength() > 2) {
573 if (const char *StringLit = Tok.getLiteralData())
574 FoundHexdecimalEnumerator =
575 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
576 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000577 if (!FoundHexdecimalEnumerator)
578 AllHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000579 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000580 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000581 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000582}
583
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000584void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000585 const ObjCImplementationDecl *ImpDecl) {
586 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000587 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000588 return;
589 // Find all implicit conforming protocols for this class
590 // and make them explicit.
591 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
592 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000593 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000594
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000595 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000596 ObjCProtocolDecls.begin(),
597 E = ObjCProtocolDecls.end(); I != E; ++I)
598 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000599 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000600
601 if (PotentialImplicitProtocols.empty())
602 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000603
604 // go through list of non-optional methods and properties in each protocol
605 // in the PotentialImplicitProtocols list. If class implements every one of the
606 // methods and properties, then this class conforms to this protocol.
607 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
608 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000609 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000610 PotentialImplicitProtocols[i]))
611 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000612
613 if (ConformingProtocols.empty())
614 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000615
616 // Further reduce number of conforming protocols. If protocol P1 is in the list
617 // protocol P2 (P2<P1>), No need to include P1.
618 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
619 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
620 bool DropIt = false;
621 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
622 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
623 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
624 if (PDecl == TargetPDecl)
625 continue;
626 if (PDecl->lookupProtocolNamed(
627 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
628 DropIt = true;
629 break;
630 }
631 }
632 if (!DropIt)
633 MinimalConformingProtocols.push_back(TargetPDecl);
634 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000635 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000636 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
637 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000638 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000639}
640
Fariborz Jahanian92463272013-07-18 20:11:45 +0000641void ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
642 const EnumDecl *EnumDcl,
643 const TypedefDecl *TypedefDcl) {
644 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000645 !TypedefDcl->getIdentifier() ||
646 EnumDcl->isDeprecated() || TypedefDcl->isDeprecated())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000647 return;
648
649 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000650 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
651 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000652
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000653 if (!IsNSIntegerType && !IsNSUIntegerType) {
654 // Also check for typedef enum {...} TD;
655 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
656 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000657 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000658 if (NSOptions) {
659 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
660 return;
661 }
662 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000663 return;
664 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000665 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000666 Editor->commit(commit);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000667 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000668 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000669 return;
670 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000671
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000672 // We may still use NS_OPTIONS based on what we find in the enumertor list.
673 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000674 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000675 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
676 return;
677 // NS_OPTIONS must be available.
678 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian92463272013-07-18 20:11:45 +0000679 return;
680 edit::Commit commit(*Editor);
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000681 rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, IsNSIntegerType, NSOptions);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000682 Editor->commit(commit);
683}
684
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000685static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
686 ObjCMethodDecl *OM) {
687 SourceRange R;
688 std::string ClassString;
689 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
690 TypeLoc TL = TSInfo->getTypeLoc();
691 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
692 ClassString = "instancetype";
693 }
694 else {
695 R = SourceRange(OM->getLocStart(), OM->getLocStart());
696 ClassString = OM->isInstanceMethod() ? '-' : '+';
697 ClassString += " (instancetype)";
698 }
699 edit::Commit commit(*ASTC.Editor);
700 commit.replace(R, ClassString);
701 ASTC.Editor->commit(commit);
702}
703
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000704static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
705 ObjCMethodDecl *OM) {
706 ObjCInterfaceDecl *IDecl = OM->getClassInterface();
707 SourceRange R;
708 std::string ClassString;
709 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
710 TypeLoc TL = TSInfo->getTypeLoc();
711 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
712 ClassString = IDecl->getName();
713 ClassString += "*";
714 }
715 }
716 else {
717 R = SourceRange(OM->getLocStart(), OM->getLocStart());
718 ClassString = "+ (";
719 ClassString += IDecl->getName(); ClassString += "*)";
720 }
721 edit::Commit commit(*ASTC.Editor);
722 commit.replace(R, ClassString);
723 ASTC.Editor->commit(commit);
724}
725
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000726void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
727 ObjCContainerDecl *CDecl,
728 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +0000729 ObjCInstanceTypeFamily OIT_Family =
730 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000731
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000732 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000733 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000734 case OIT_None:
735 migrateFactoryMethod(Ctx, CDecl, OM);
736 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000737 case OIT_Array:
738 ClassName = "NSArray";
739 break;
740 case OIT_Dictionary:
741 ClassName = "NSDictionary";
742 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000743 case OIT_Singleton:
744 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000745 return;
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +0000746 case OIT_Init:
747 if (OM->getResultType()->isObjCIdType())
748 ReplaceWithInstancetype(*this, OM);
749 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000750 case OIT_ReturnsSelf:
751 migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
752 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000753 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000754 if (!OM->getResultType()->isObjCIdType())
755 return;
756
757 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
758 if (!IDecl) {
759 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
760 IDecl = CatDecl->getClassInterface();
761 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
762 IDecl = ImpDecl->getClassInterface();
763 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000764 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000765 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
766 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000767 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000768 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000769 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000770}
771
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000772static bool TypeIsInnerPointer(QualType T) {
773 if (!T->isAnyPointerType())
774 return false;
775 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
Fariborz Jahanian73466ca2013-09-26 21:43:47 +0000776 T->isBlockPointerType() || T->isFunctionPointerType() ||
777 ento::coreFoundation::isCFObjectRef(T))
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000778 return false;
Fariborz Jahanian9d5fffb2013-09-09 23:56:14 +0000779 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
780 // is not an innter pointer type.
781 QualType OrigT = T;
782 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
783 T = TD->getDecl()->getUnderlyingType();
784 if (OrigT == T || !T->isPointerType())
785 return true;
786 const PointerType* PT = T->getAs<PointerType>();
787 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
788 if (UPointeeT->isRecordType()) {
789 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
790 if (!RecordTy->getDecl()->isCompleteDefinition())
791 return false;
792 }
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000793 return true;
794}
795
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000796static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2) {
797 if (Decl1->hasAttrs() != Decl2->hasAttrs())
798 return false;
799
800 if (!Decl1->hasAttrs())
801 return true;
802
803 const AttrVec &Attrs1 = Decl1->getAttrs();
804 const AttrVec &Attrs2 = Decl2->getAttrs();
805 // This list is very small, so this need not be optimized.
806 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
807 bool match = false;
808 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
809 // Matching attribute kind only. We are not getting into
810 // details of the attributes. For all practical purposes
811 // this is sufficient.
812 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
813 match = true;
814 break;
815 }
816 }
817 if (!match)
818 return false;
819 }
820 return true;
821}
822
Fariborz Jahanian5d783df2013-09-27 22:55:54 +0000823static bool IsValidIdentifier(ASTContext &Ctx,
824 const char *Name) {
825 if (!isIdentifierHead(Name[0]))
826 return false;
827 std::string NameString = Name;
828 NameString[0] = toLowercase(NameString[0]);
829 IdentifierInfo *II = &Ctx.Idents.get(NameString);
830 return II->getTokenID() == tok::identifier;
831}
832
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000833bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000834 ObjCContainerDecl *D,
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000835 ObjCMethodDecl *Method) {
836 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
837 Method->param_size() != 0)
838 return false;
839 // Is this method candidate to be a getter?
840 QualType GRT = Method->getResultType();
841 if (GRT->isVoidType())
842 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000843
844 Selector GetterSelector = Method->getSelector();
Fariborz Jahanian7391a7b5a2013-09-25 00:17:07 +0000845 ObjCInstanceTypeFamily OIT_Family =
846 Selector::getInstTypeMethodFamily(GetterSelector);
847
848 if (OIT_Family != OIT_None)
849 return false;
850
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000851 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
852 Selector SetterSelector =
853 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
854 PP.getSelectorTable(),
855 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000856 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000857 unsigned LengthOfPrefix = 0;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000858 if (!SetterMethod) {
859 // try a different naming convention for getter: isXxxxx
860 StringRef getterNameString = getterName->getName();
Fariborz Jahanianca399602013-09-11 17:05:15 +0000861 bool IsPrefix = getterNameString.startswith("is");
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +0000862 // Note that we don't want to change an isXXX method of retainable object
863 // type to property (readonly or otherwise).
864 if (IsPrefix && GRT->isObjCRetainableType())
865 return false;
866 if (IsPrefix || getterNameString.startswith("get")) {
Fariborz Jahanianca399602013-09-11 17:05:15 +0000867 LengthOfPrefix = (IsPrefix ? 2 : 3);
868 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
869 // Make sure that first character after "is" or "get" prefix can
870 // start an identifier.
Fariborz Jahanian5d783df2013-09-27 22:55:54 +0000871 if (!IsValidIdentifier(Ctx, CGetterName))
Fariborz Jahanianca399602013-09-11 17:05:15 +0000872 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000873 if (CGetterName[0] && isUppercase(CGetterName[0])) {
874 getterName = &Ctx.Idents.get(CGetterName);
875 SetterSelector =
876 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
877 PP.getSelectorTable(),
878 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000879 SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000880 }
881 }
882 }
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +0000883
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000884 if (SetterMethod) {
Fariborz Jahanianc1213862013-10-02 21:32:39 +0000885 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
886 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000887 if (SetterMethod->isDeprecated() ||
888 !AttributesMatch(Method, SetterMethod))
Fariborz Jahanianf6c65052013-09-17 22:41:25 +0000889 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000890
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000891 // Is this a valid setter, matching the target getter?
892 QualType SRT = SetterMethod->getResultType();
893 if (!SRT->isVoidType())
894 return false;
895 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
896 QualType ArgType = argDecl->getType();
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000897 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000898 return false;
899 edit::Commit commit(*Editor);
900 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000901 LengthOfPrefix,
902 (ASTMigrateActions &
903 FrontendOptions::ObjCMT_AtomicProperty) != 0);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000904 Editor->commit(commit);
905 return true;
906 }
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000907 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000908 // Try a non-void method with no argument (and no setter or property of same name
909 // as a 'readonly' property.
910 edit::Commit commit(*Editor);
911 rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000912 LengthOfPrefix,
913 (ASTMigrateActions &
914 FrontendOptions::ObjCMT_AtomicProperty) != 0);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000915 Editor->commit(commit);
916 return true;
917 }
918 return false;
919}
920
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000921void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
922 ObjCMethodDecl *OM) {
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000923 if (OM->isImplicit() ||
Fariborz Jahanian7c1a4452013-09-26 22:43:41 +0000924 !OM->isInstanceMethod() ||
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000925 OM->hasAttr<ObjCReturnsInnerPointerAttr>())
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000926 return;
927
928 QualType RT = OM->getResultType();
929 if (!TypeIsInnerPointer(RT) ||
930 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
931 return;
932
933 edit::Commit commit(*Editor);
934 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
935 Editor->commit(commit);
936}
937
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000938void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
939 ObjCPropertyDecl *P) {
940 QualType T = P->getType();
941
942 if (!TypeIsInnerPointer(T) ||
943 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
944 return;
945 edit::Commit commit(*Editor);
946 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
947 Editor->commit(commit);
948}
949
Fariborz Jahanian8c45e282013-10-02 22:49:59 +0000950void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
Fariborz Jahanian71221352013-07-23 22:42:28 +0000951 ObjCContainerDecl *CDecl) {
Fariborz Jahaniane47a14a2013-09-18 15:43:52 +0000952 if (CDecl->isDeprecated())
953 return;
954
Fariborz Jahanian71221352013-07-23 22:42:28 +0000955 // migrate methods which can have instancetype as their result type.
956 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
957 MEnd = CDecl->meth_end();
958 M != MEnd; ++M) {
959 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000960 if (Method->isDeprecated())
961 continue;
Fariborz Jahanian71221352013-07-23 22:42:28 +0000962 migrateMethodInstanceType(Ctx, CDecl, Method);
963 }
964}
965
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000966void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
967 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000968 ObjCMethodDecl *OM,
969 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +0000970 if (OM->isInstanceMethod() ||
971 OM->getResultType() == Ctx.getObjCInstanceType() ||
972 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000973 return;
974
975 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
976 // NSYYYNamE with matching names be at least 3 characters long.
977 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
978 if (!IDecl) {
979 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
980 IDecl = CatDecl->getClassInterface();
981 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
982 IDecl = ImpDecl->getClassInterface();
983 }
984 if (!IDecl)
985 return;
986
987 std::string StringClassName = IDecl->getName();
988 StringRef LoweredClassName(StringClassName);
989 std::string StringLoweredClassName = LoweredClassName.lower();
990 LoweredClassName = StringLoweredClassName;
991
992 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +0000993 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
994 if (!MethodIdName)
995 return;
996
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000997 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000998 if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000999 StringRef STRefMethodName(MethodName);
1000 size_t len = 0;
1001 if (STRefMethodName.startswith("standard"))
1002 len = strlen("standard");
1003 else if (STRefMethodName.startswith("shared"))
1004 len = strlen("shared");
1005 else if (STRefMethodName.startswith("default"))
1006 len = strlen("default");
1007 else
1008 return;
1009 MethodName = STRefMethodName.substr(len);
1010 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001011 std::string MethodNameSubStr = MethodName.substr(0, 3);
1012 StringRef MethodNamePrefix(MethodNameSubStr);
1013 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1014 MethodNamePrefix = StringLoweredMethodNamePrefix;
1015 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1016 if (Ix == StringRef::npos)
1017 return;
1018 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1019 StringRef LoweredMethodName(MethodName);
1020 std::string StringLoweredMethodName = LoweredMethodName.lower();
1021 LoweredMethodName = StringLoweredMethodName;
1022 if (!LoweredMethodName.startswith(ClassNamePostfix))
1023 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001024 if (OIT_Family == OIT_ReturnsSelf)
1025 ReplaceWithClasstype(*this, OM);
1026 else
1027 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001028}
1029
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001030static bool IsVoidStarType(QualType Ty) {
1031 if (!Ty->isPointerType())
1032 return false;
1033
1034 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1035 Ty = TD->getDecl()->getUnderlyingType();
1036
1037 // Is the type void*?
1038 const PointerType* PT = Ty->getAs<PointerType>();
1039 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1040 return true;
1041 return IsVoidStarType(PT->getPointeeType());
1042}
1043
Fariborz Jahanian94279392013-08-20 18:54:39 +00001044/// AuditedType - This routine audits the type AT and returns false if it is one of known
1045/// CF object types or of the "void *" variety. It returns true if we don't care about the type
1046/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001047static bool AuditedType (QualType AT) {
1048 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001049 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001050 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +00001051 if (ento::coreFoundation::isCFObjectRef(AT) ||
1052 IsVoidStarType(AT) ||
1053 // If an ObjC object is type, assuming that it is not a CF function and
1054 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +00001055 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001056 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +00001057 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001058 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001059}
1060
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001061void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001062 if (CFFunctionIBCandidates.empty())
1063 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001064 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
1065 CFFunctionIBCandidates.clear();
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001066 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001067 return;
1068 }
1069 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001070 const Decl *FirstFD = CFFunctionIBCandidates[0];
1071 const Decl *LastFD =
1072 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001073 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1074 edit::Commit commit(*Editor);
1075 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
1076 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1077 SourceLocation EndLoc = LastFD->getLocEnd();
1078 // get location just past end of function location.
1079 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001080 if (isa<FunctionDecl>(LastFD)) {
1081 // For Methods, EndLoc points to the ending semcolon. So,
1082 // not of these extra work is needed.
1083 Token Tok;
1084 // get locaiton of token that comes after end of function.
1085 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1086 if (!Failed)
1087 EndLoc = Tok.getLocation();
1088 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001089 commit.insertAfterToken(EndLoc, PragmaString);
1090 Editor->commit(commit);
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001091 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001092 CFFunctionIBCandidates.clear();
1093}
1094
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001095void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001096 if (Decl->isDeprecated())
1097 return;
1098
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001099 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001100 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001101 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001102 "provided CF_IMPLICIT_BRIDGING_ENABLE");
1103 return;
1104 }
1105
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001106 // Finction must be annotated first.
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001107 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1108 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1109 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001110 CFFunctionIBCandidates.push_back(Decl);
1111 if (!FileId)
1112 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1113 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001114 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1115 if (!CFFunctionIBCandidates.empty()) {
1116 CFFunctionIBCandidates.push_back(Decl);
1117 if (!FileId)
1118 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1119 }
1120 }
1121 else
1122 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001123 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001124 else {
1125 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001126 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001127 }
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001128}
1129
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001130void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1131 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001132 const FunctionDecl *FuncDecl,
1133 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001134 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001135 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001136 RetEffect Ret = CE.getReturnValue();
1137 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001138 if (Ret.getObjKind() == RetEffect::CF) {
1139 if (Ret.isOwned() &&
1140 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001141 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001142 else if (Ret.notOwned() &&
1143 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001144 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1145 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001146 else if (Ret.getObjKind() == RetEffect::ObjC) {
1147 if (Ret.isOwned() &&
1148 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1149 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001150 }
1151
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001152 if (AnnotationString) {
1153 edit::Commit commit(*Editor);
1154 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1155 Editor->commit(commit);
1156 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001157 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001158 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1159 unsigned i = 0;
1160 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1161 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +00001162 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001163 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001164 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1165 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1166 edit::Commit commit(*Editor);
1167 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1168 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +00001169 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001170 else if (AE == DecRefMsg && !pd->getAttr<NSConsumedAttr>() &&
1171 Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
1172 edit::Commit commit(*Editor);
1173 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1174 Editor->commit(commit);
1175 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001176 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001177}
1178
1179
1180ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1181 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1182 ASTContext &Ctx,
1183 const FunctionDecl *FuncDecl) {
1184 if (FuncDecl->hasBody())
1185 return CF_BRIDGING_NONE;
1186
1187 CallEffects CE = CallEffects::getEffect(FuncDecl);
1188 bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001189 FuncDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1190 FuncDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001191 FuncDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1192 FuncDecl->getAttr<NSReturnsAutoreleasedAttr>());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001193
1194 // Trivial case of when funciton is annotated and has no argument.
1195 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1196 return CF_BRIDGING_NONE;
1197
1198 bool ReturnCFAudited = false;
1199 if (!FuncIsReturnAnnotated) {
1200 RetEffect Ret = CE.getReturnValue();
1201 if (Ret.getObjKind() == RetEffect::CF &&
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001202 (Ret.isOwned() || Ret.notOwned()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001203 ReturnCFAudited = true;
1204 else if (!AuditedType(FuncDecl->getResultType()))
1205 return CF_BRIDGING_NONE;
1206 }
1207
1208 // At this point result type is audited for potential inclusion.
1209 // Now, how about argument types.
1210 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1211 unsigned i = 0;
1212 bool ArgCFAudited = false;
1213 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1214 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1215 const ParmVarDecl *pd = *pi;
1216 ArgEffect AE = AEArgs[i];
1217 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1218 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
1219 ArgCFAudited = true;
1220 else if (AE == IncRef)
1221 ArgCFAudited = true;
1222 }
1223 else {
1224 QualType AT = pd->getType();
1225 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001226 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001227 return CF_BRIDGING_NONE;
1228 }
1229 }
1230 }
1231 if (ReturnCFAudited || ArgCFAudited)
1232 return CF_BRIDGING_ENABLE;
1233
1234 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001235}
1236
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001237void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1238 ObjCContainerDecl *CDecl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001239 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001240 return;
1241
1242 // migrate methods which can have instancetype as their result type.
1243 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1244 MEnd = CDecl->meth_end();
1245 M != MEnd; ++M) {
1246 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001247 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001248 }
1249}
1250
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001251void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1252 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001253 const ObjCMethodDecl *MethodDecl,
1254 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001255 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001256 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001257 RetEffect Ret = CE.getReturnValue();
1258 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001259 if (Ret.getObjKind() == RetEffect::CF) {
1260 if (Ret.isOwned() &&
1261 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001262 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001263 else if (Ret.notOwned() &&
1264 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001265 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1266 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001267 else if (Ret.getObjKind() == RetEffect::ObjC) {
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001268 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1269 switch (OMF) {
1270 case clang::OMF_alloc:
1271 case clang::OMF_new:
1272 case clang::OMF_copy:
1273 case clang::OMF_init:
1274 case clang::OMF_mutableCopy:
1275 break;
1276
1277 default:
1278 if (Ret.isOwned() &&
1279 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1280 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001281 break;
1282 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001283 }
1284
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001285 if (AnnotationString) {
1286 edit::Commit commit(*Editor);
1287 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1288 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001289 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001290 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001291 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1292 unsigned i = 0;
1293 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1294 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1295 const ParmVarDecl *pd = *pi;
1296 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001297 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1298 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1299 edit::Commit commit(*Editor);
1300 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1301 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001302 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001303 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001304}
1305
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001306void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001307 ASTContext &Ctx,
1308 const ObjCMethodDecl *MethodDecl) {
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001309 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001310 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001311
1312 CallEffects CE = CallEffects::getEffect(MethodDecl);
1313 bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001314 MethodDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1315 MethodDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001316 MethodDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1317 MethodDecl->getAttr<NSReturnsAutoreleasedAttr>());
1318
1319 if (CE.getReceiver() == DecRefMsg &&
1320 !MethodDecl->getAttr<NSConsumesSelfAttr>() &&
1321 MethodDecl->getMethodFamily() != OMF_init &&
1322 MethodDecl->getMethodFamily() != OMF_release &&
1323 Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
1324 edit::Commit commit(*Editor);
1325 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1326 Editor->commit(commit);
1327 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001328
1329 // Trivial case of when funciton is annotated and has no argument.
1330 if (MethodIsReturnAnnotated &&
1331 (MethodDecl->param_begin() == MethodDecl->param_end()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001332 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001333
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001334 if (!MethodIsReturnAnnotated) {
1335 RetEffect Ret = CE.getReturnValue();
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001336 if ((Ret.getObjKind() == RetEffect::CF ||
1337 Ret.getObjKind() == RetEffect::ObjC) &&
1338 (Ret.isOwned() || Ret.notOwned())) {
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001339 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1340 return;
1341 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001342 else if (!AuditedType(MethodDecl->getResultType()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001343 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001344 }
1345
1346 // At this point result type is either annotated or audited.
1347 // Now, how about argument types.
1348 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1349 unsigned i = 0;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001350 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1351 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1352 const ParmVarDecl *pd = *pi;
1353 ArgEffect AE = AEArgs[i];
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001354 if ((AE == DecRef && !pd->getAttr<CFConsumedAttr>()) || AE == IncRef ||
1355 !AuditedType(pd->getType())) {
1356 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1357 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001358 }
1359 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001360 return;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001361}
1362
Ted Kremenekf7639e12012-03-06 20:06:33 +00001363namespace {
1364
1365class RewritesReceiver : public edit::EditsReceiver {
1366 Rewriter &Rewrite;
1367
1368public:
1369 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1370
1371 virtual void insert(SourceLocation loc, StringRef text) {
1372 Rewrite.InsertText(loc, text);
1373 }
1374 virtual void replace(CharSourceRange range, StringRef text) {
1375 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1376 }
1377};
1378
1379}
1380
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001381static bool
1382IsReallyASystemHeader(ASTContext &Ctx, const FileEntry *file, FileID FID) {
1383 bool Invalid = false;
1384 const SrcMgr::SLocEntry &SEntry =
1385 Ctx.getSourceManager().getSLocEntry(FID, &Invalid);
1386 if (!Invalid && SEntry.isFile()) {
1387 const SrcMgr::FileInfo &FI = SEntry.getFile();
1388 if (!FI.hasLineDirectives()) {
1389 if (FI.getFileCharacteristic() == SrcMgr::C_ExternCSystem)
1390 return true;
1391 if (FI.getFileCharacteristic() == SrcMgr::C_System) {
1392 // This file is in a system header directory. Continue with commiting change
1393 // only if it is a user specified system directory because user put a
1394 // .system_framework file in the framework directory.
1395 StringRef Directory(file->getDir()->getName());
1396 size_t Ix = Directory.rfind(".framework");
1397 if (Ix == StringRef::npos)
1398 return true;
1399 std::string PatchToSystemFramework = Directory.slice(0, Ix+sizeof(".framework"));
1400 PatchToSystemFramework += ".system_framework";
1401 if (!llvm::sys::fs::exists(PatchToSystemFramework.data()))
1402 return true;
1403 }
1404 }
1405 }
1406 return false;
1407}
1408
Ted Kremenekf7639e12012-03-06 20:06:33 +00001409void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001410
1411 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001412 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001413 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1414 D != DEnd; ++D) {
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001415 if (unsigned FID =
1416 PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue())
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001417 if (FileId && FileId != FID) {
1418 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1419 AnnotateImplicitBridging(Ctx);
1420 }
1421
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001422 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1423 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001424 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D))
1425 migrateObjCInterfaceDecl(Ctx, CatDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001426 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1427 ObjCProtocolDecls.insert(PDecl);
1428 else if (const ObjCImplementationDecl *ImpDecl =
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001429 dyn_cast<ObjCImplementationDecl>(*D)) {
1430 if (ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance)
1431 migrateProtocolConformance(Ctx, ImpDecl);
1432 }
Fariborz Jahanian92463272013-07-18 20:11:45 +00001433 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1434 DeclContext::decl_iterator N = D;
1435 ++N;
Fariborz Jahanian008ef722013-07-19 17:44:32 +00001436 if (N != DEnd)
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001437 if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N)) {
1438 if (ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros)
1439 migrateNSEnumDecl(Ctx, ED, TD);
1440 }
Fariborz Jahanian92463272013-07-18 20:11:45 +00001441 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001442 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
1443 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1444 migrateCFAnnotation(Ctx, FD);
1445 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001446
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001447 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1448 // migrate methods which can have instancetype as their result type.
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001449 if (ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype)
1450 migrateAllMethodInstaceType(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001451 // annotate methods with CF annotations.
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001452 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1453 migrateARCSafeAnnotation(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001454 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001455 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001456 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1457 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001458 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001459
David Blaikiebbafb8a2012-03-11 07:00:24 +00001460 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001461 RewritesReceiver Rec(rewriter);
1462 Editor->applyRewrites(Rec);
1463
1464 for (Rewriter::buffer_iterator
1465 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1466 FileID FID = I->first;
1467 RewriteBuffer &buf = I->second;
1468 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1469 assert(file);
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001470 if (IsReallyASystemHeader(Ctx, file, FID))
1471 continue;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001472 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001473 llvm::raw_svector_ostream vecOS(newText);
1474 buf.write(vecOS);
1475 vecOS.flush();
1476 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1477 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001478 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001479 FileMgr.FixupRelativePath(filePath);
1480 Remapper.remap(filePath.str(), memBuf);
1481 }
1482
1483 if (IsOutputFile) {
1484 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1485 } else {
1486 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1487 }
1488}
1489
1490bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001491 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001492 return true;
1493}
1494
1495ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1496 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001497 PPConditionalDirectiveRecord *
1498 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1499 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001500 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001501 FrontendOptions::ObjCMT_MigrateAll,
Ted Kremenekf7639e12012-03-06 20:06:33 +00001502 Remapper,
1503 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001504 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001505 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +00001506 /*isOutputFile=*/true);
1507}