blob: 65825cea27855ab16c6a6de2f05ff103532a7f93 [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 Jahanian059e05e2013-10-15 00:00:28 +000049 void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +000050 bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
Fariborz Jahanian92463272013-07-18 20:11:45 +000051 const TypedefDecl *TypedefDcl);
Fariborz Jahanian8c45e282013-10-02 22:49:59 +000052 void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000053 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
54 ObjCMethodDecl *OM);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000055 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +000056 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
Fariborz Jahanian10b74352013-09-24 20:20:52 +000057 void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000058 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000059 ObjCMethodDecl *OM,
60 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000061
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000062 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000063 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000064 const FunctionDecl *FuncDecl, bool ResultAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000065 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000066 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000067
Fariborz Jahanian301b5212013-08-20 22:42:13 +000068 void AnnotateImplicitBridging(ASTContext &Ctx);
69
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000070 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
71 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000072
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000073 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
74
Fariborz Jahanian89f6d102013-09-04 00:10:06 +000075 void migrateAddMethodAnnotation(ASTContext &Ctx,
76 const ObjCMethodDecl *MethodDecl);
Ted Kremenekf7639e12012-03-06 20:06:33 +000077public:
78 std::string MigrateDir;
Fariborz Jahanian182486c2013-10-02 17:08:12 +000079 unsigned ASTMigrateActions;
Fariborz Jahanianb8343522013-08-20 23:35:26 +000080 unsigned FileId;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +000081 const TypedefDecl *NSIntegerTypedefed;
82 const TypedefDecl *NSUIntegerTypedefed;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000083 OwningPtr<NSAPI> NSAPIObj;
84 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000085 FileRemapper &Remapper;
86 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000087 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000088 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000089 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000090 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000091 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000092
Ted Kremenekf7639e12012-03-06 20:06:33 +000093 ObjCMigrateASTConsumer(StringRef migrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +000094 unsigned astMigrateActions,
Ted Kremenekf7639e12012-03-06 20:06:33 +000095 FileRemapper &remapper,
96 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000097 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000098 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +000099 bool isOutputFile = false)
100 : MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000101 ASTMigrateActions(astMigrateActions),
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000102 FileId(0), NSIntegerTypedefed(0), NSUIntegerTypedefed(0),
103 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000104 IsOutputFile(isOutputFile) { }
105
106protected:
107 virtual void Initialize(ASTContext &Context) {
108 NSAPIObj.reset(new NSAPI(Context));
109 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000110 Context.getLangOpts(),
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +0000111 PPRec, false));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000112 }
113
114 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
115 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
116 migrateDecl(*I);
117 return true;
118 }
119 virtual void HandleInterestingDecl(DeclGroupRef DG) {
120 // Ignore decls from the PCH.
121 }
122 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
123 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
124 }
125
126 virtual void HandleTranslationUnit(ASTContext &Ctx);
127};
128
129}
130
131ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000132 StringRef migrateDir,
133 unsigned migrateAction)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000134 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000135 ObjCMigAction(migrateAction),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000136 CompInst(0) {
137 if (MigrateDir.empty())
138 MigrateDir = "."; // user current directory if none is given.
139}
140
141ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
142 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000143 PPConditionalDirectiveRecord *
144 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
145 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000146 ASTConsumer *
147 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
148 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000149 ObjCMigAction,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000150 Remapper,
151 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000152 PPRec,
153 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000154 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
155 return new MultiplexConsumer(Consumers);
156}
157
158bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
159 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
160 /*ignoreIfFilesChanges=*/true);
161 CompInst = &CI;
162 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000163 return true;
164}
165
166namespace {
167class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
168 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000169 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000170
171public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000172 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
173 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000174
175 bool shouldVisitTemplateInstantiations() const { return false; }
176 bool shouldWalkTypesOfTypeLocs() const { return false; }
177
178 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000179 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000180 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000181 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000182 Consumer.Editor->commit(commit);
183 }
184
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000185 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000186 edit::Commit commit(*Consumer.Editor);
187 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
188 Consumer.Editor->commit(commit);
189 }
190
191 return true;
192 }
193
194 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
195 // Do depth first; we want to rewrite the subexpressions first so that if
196 // we have to move expressions we will move them already rewritten.
197 for (Stmt::child_range range = E->children(); range; ++range)
198 if (!TraverseStmt(*range))
199 return false;
200
201 return WalkUpFromObjCMessageExpr(E);
202 }
203};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000204
205class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
206 ObjCMigrateASTConsumer &Consumer;
207 OwningPtr<ParentMap> PMap;
208
209public:
210 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
211
212 bool shouldVisitTemplateInstantiations() const { return false; }
213 bool shouldWalkTypesOfTypeLocs() const { return false; }
214
215 bool TraverseStmt(Stmt *S) {
216 PMap.reset(new ParentMap(S));
217 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
218 return true;
219 }
220};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000221}
222
223void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
224 if (!D)
225 return;
226 if (isa<ObjCMethodDecl>(D))
227 return; // Wait for the ObjC container declaration.
228
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000229 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000230}
231
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000232static void append_attr(std::string &PropertyString, const char *attr) {
233 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000234 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000235}
236
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000237static
238void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
239 const std::string& TypeString,
240 const char *name) {
241 const char *argPtr = TypeString.c_str();
242 int paren = 0;
243 while (*argPtr) {
244 switch (*argPtr) {
245 case '(':
246 PropertyString += *argPtr;
247 paren++;
248 break;
249 case ')':
250 PropertyString += *argPtr;
251 paren--;
252 break;
253 case '^':
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000254 case '*':
255 PropertyString += (*argPtr);
256 if (paren == 1) {
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000257 PropertyString += name;
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000258 name = "";
259 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000260 break;
261 default:
262 PropertyString += *argPtr;
263 break;
264 }
265 argPtr++;
266 }
267}
268
269
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000270static bool rewriteToObjCProperty(const ObjCMethodDecl *Getter,
271 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000272 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000273 unsigned LengthOfPrefix,
274 bool Atomic) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000275 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000276 std::string PropertyString = "@property (";
277 PropertyString += (Atomic ? "atomic" : "nonatomic");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000278 std::string PropertyNameString = Getter->getNameAsString();
279 StringRef PropertyName(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000280 if (LengthOfPrefix > 0) {
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000281 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000282 PropertyString += PropertyNameString;
283 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000284 // Property with no setter may be suggested as a 'readonly' property.
285 if (!Setter)
286 append_attr(PropertyString, "readonly");
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000287
Fariborz Jahanian33304e302013-10-16 18:52:17 +0000288 // Short circuit 'delegate' properties that contain the name "delegate" or
289 // "dataSource", or have exact name "target" to have 'assign' attribute.
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000290 if (PropertyName.equals("target") ||
291 (PropertyName.find("delegate") != StringRef::npos) ||
292 (PropertyName.find("dataSource") != StringRef::npos))
Fariborz Jahanian33304e302013-10-16 18:52:17 +0000293 append_attr(PropertyString, "assign");
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000294 else if (Setter) {
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000295 const ParmVarDecl *argDecl = *Setter->param_begin();
296 QualType ArgType = Context.getCanonicalType(argDecl->getType());
297 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
298 bool RetainableObject = ArgType->isObjCRetainableType();
299 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
300 if (const ObjCObjectPointerType *ObjPtrTy =
301 ArgType->getAs<ObjCObjectPointerType>()) {
302 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
303 if (IDecl &&
304 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000305 append_attr(PropertyString, "copy");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000306 else
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000307 append_attr(PropertyString, "retain");
308 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000309 else if (ArgType->isBlockPointerType())
310 append_attr(PropertyString, "copy");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000311 } else if (propertyLifetime == Qualifiers::OCL_Weak)
312 // TODO. More precise determination of 'weak' attribute requires
313 // looking into setter's implementation for backing weak ivar.
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000314 append_attr(PropertyString, "weak");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000315 else if (RetainableObject)
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000316 append_attr(PropertyString,
317 ArgType->isBlockPointerType() ? "copy" : "retain");
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000318 }
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000319 PropertyString += ')';
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000320 QualType RT = Getter->getResultType();
321 if (!isa<TypedefType>(RT)) {
322 // strip off any ARC lifetime qualifier.
323 QualType CanResultTy = Context.getCanonicalType(RT);
324 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
325 Qualifiers Qs = CanResultTy.getQualifiers();
326 Qs.removeObjCLifetime();
327 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
328 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000329 }
330 PropertyString += " ";
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000331 PrintingPolicy SubPolicy(Context.getPrintingPolicy());
332 SubPolicy.SuppressStrongLifetime = true;
Fariborz Jahaniande557f82013-10-09 17:37:28 +0000333 SubPolicy.SuppressLifetimeQualifiers = true;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000334 std::string TypeString = RT.getAsString(SubPolicy);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000335 if (LengthOfPrefix > 0) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000336 // property name must strip off "is" and lower case the first character
337 // after that; e.g. isContinuous will become continuous.
338 StringRef PropertyNameStringRef(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000339 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000340 PropertyNameString = PropertyNameStringRef;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000341 bool NoLowering = (isUppercase(PropertyNameString[0]) &&
342 PropertyNameString.size() > 1 &&
343 isUppercase(PropertyNameString[1]));
Fariborz Jahanian34fea362013-09-11 18:27:16 +0000344 if (!NoLowering)
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000345 PropertyNameString[0] = toLowercase(PropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000346 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000347 if (RT->isBlockPointerType() || RT->isFunctionPointerType())
348 MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
349 TypeString,
350 PropertyNameString.c_str());
351 else {
352 char LastChar = TypeString[TypeString.size()-1];
353 PropertyString += TypeString;
354 if (LastChar != '*')
355 PropertyString += ' ';
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000356 PropertyString += PropertyNameString;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000357 }
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000358 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
359 Selector GetterSelector = Getter->getSelector();
360
361 SourceLocation EndGetterSelectorLoc =
362 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000363 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000364 EndGetterSelectorLoc),
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000365 PropertyString);
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000366 if (Setter) {
367 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
368 // Get location past ';'
369 EndLoc = EndLoc.getLocWithOffset(1);
370 commit.remove(CharSourceRange::getCharRange(Setter->getLocStart(), EndLoc));
371 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000372 return true;
373}
374
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000375void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000376 ObjCContainerDecl *D) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000377 if (D->isDeprecated())
378 return;
379
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000380 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
381 M != MEnd; ++M) {
382 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000383 if (Method->isDeprecated())
384 continue;
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000385 migrateProperty(Ctx, D, Method);
Fariborz Jahanian8c45e282013-10-02 22:49:59 +0000386 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
387 migrateNsReturnsInnerPointer(Ctx, Method);
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000388 }
389 for (ObjCContainerDecl::prop_iterator P = D->prop_begin(),
390 E = D->prop_end(); P != E; ++P) {
391 ObjCPropertyDecl *Prop = *P;
Fariborz Jahanian8c45e282013-10-02 22:49:59 +0000392 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
393 !P->isDeprecated())
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000394 migratePropertyNsReturnsInnerPointer(Ctx, Prop);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000395 }
396}
397
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000398static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000399ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000400 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000401 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000402 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000403 // In auto-synthesis, protocol properties are not synthesized. So,
404 // a conforming protocol must have its required properties declared
405 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000406 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000407 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
408 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
409 E = PDecl->prop_end(); P != E; ++P) {
410 ObjCPropertyDecl *Property = *P;
411 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
412 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000413 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000414 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000415 if (R.size() == 0) {
416 // Relax the rule and look into class's implementation for a synthesize
417 // or dynamic declaration. Class is implementing a property coming from
418 // another protocol. This still makes the target protocol as conforming.
419 if (!ImpDecl->FindPropertyImplDecl(
420 Property->getDeclName().getAsIdentifierInfo()))
421 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000422 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000423 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
424 if ((ClassProperty->getPropertyAttributes()
425 != Property->getPropertyAttributes()) ||
426 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
427 return false;
428 }
429 else
430 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000431 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000432
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000433 // At this point, all required properties in this protocol conform to those
434 // declared in the class.
435 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000436 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000437 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
438 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000439 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000440 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
441 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
442 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000443 if (MD->isImplicit())
444 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000445 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
446 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000447 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000448 if (R.size() == 0)
449 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000450 bool match = false;
451 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000452 for (unsigned I = 0, N = R.size(); I != N; ++I)
453 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
454 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
455 match = true;
456 break;
457 }
458 if (!match)
459 return false;
460 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000461 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000462 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
463 return true;
464 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000465}
466
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000467static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
468 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
469 const NSAPI &NS, edit::Commit &commit) {
470 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
471 std::string ClassString;
472 SourceLocation EndLoc =
473 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
474
475 if (Protocols.empty()) {
476 ClassString = '<';
477 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
478 ClassString += ConformingProtocols[i]->getNameAsString();
479 if (i != (e-1))
480 ClassString += ", ";
481 }
482 ClassString += "> ";
483 }
484 else {
485 ClassString = ", ";
486 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
487 ClassString += ConformingProtocols[i]->getNameAsString();
488 if (i != (e-1))
489 ClassString += ", ";
490 }
491 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
492 EndLoc = *PL;
493 }
494
495 commit.insertAfterToken(EndLoc, ClassString);
496 return true;
497}
498
499static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
500 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000501 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000502 bool IsNSIntegerType,
503 bool NSOptions) {
504 std::string ClassString;
505 if (NSOptions)
506 ClassString = "typedef NS_OPTIONS(NSUInteger, ";
507 else
508 ClassString =
509 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, "
510 : "typedef NS_ENUM(NSUInteger, ";
511
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000512 ClassString += TypedefDcl->getIdentifier()->getName();
513 ClassString += ')';
514 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
515 commit.replace(R, ClassString);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000516 SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
517 EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
518 NS.getASTContext(), /*IsDecl*/true);
519 if (!EndOfEnumDclLoc.isInvalid()) {
520 SourceRange EnumDclRange(EnumDcl->getLocStart(), EndOfEnumDclLoc);
521 commit.insertFromRange(TypedefDcl->getLocStart(), EnumDclRange);
522 }
523 else
524 return false;
525
526 SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
527 EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
528 NS.getASTContext(), /*IsDecl*/true);
529 if (!EndTypedefDclLoc.isInvalid()) {
530 SourceRange TDRange(TypedefDcl->getLocStart(), EndTypedefDclLoc);
531 commit.remove(TDRange);
532 }
533 else
534 return false;
535
536 EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
Fariborz Jahanian1d27ffd2013-10-11 17:35:22 +0000537 /*IsDecl*/true);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000538 if (!EndOfEnumDclLoc.isInvalid()) {
539 SourceLocation BeginOfEnumDclLoc = EnumDcl->getLocStart();
540 // FIXME. This assumes that enum decl; is immediately preceeded by eoln.
541 // It is trying to remove the enum decl. lines entirely.
542 BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
543 commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000544 return true;
545 }
546 return false;
547}
548
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000549static bool rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000550 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000551 const NSAPI &NS, edit::Commit &commit,
552 bool IsNSIntegerType) {
553 std::string ClassString =
554 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000555 ClassString += TypedefDcl->getIdentifier()->getName();
556 ClassString += ')';
557 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
558 commit.replace(R, ClassString);
559 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
560 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
561 return true;
562}
563
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000564static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000565 const EnumDecl *EnumDcl) {
566 bool PowerOfTwo = true;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000567 bool AllHexdecimalEnumerator = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000568 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000569 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
570 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
571 EnumConstantDecl *Enumerator = (*EI);
572 const Expr *InitExpr = Enumerator->getInitExpr();
573 if (!InitExpr) {
574 PowerOfTwo = false;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000575 AllHexdecimalEnumerator = false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000576 continue;
577 }
Fariborz Jahanian6e1798e2013-09-17 23:32:51 +0000578 InitExpr = InitExpr->IgnoreParenCasts();
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000579 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
580 if (BO->isShiftOp() || BO->isBitwiseOp())
581 return true;
582
583 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000584 if (PowerOfTwo && EnumVal) {
585 if (!llvm::isPowerOf2_64(EnumVal))
586 PowerOfTwo = false;
587 else if (EnumVal > MaxPowerOfTwoVal)
588 MaxPowerOfTwoVal = EnumVal;
589 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000590 if (AllHexdecimalEnumerator && EnumVal) {
591 bool FoundHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000592 SourceLocation EndLoc = Enumerator->getLocEnd();
593 Token Tok;
594 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
595 if (Tok.isLiteral() && Tok.getLength() > 2) {
596 if (const char *StringLit = Tok.getLiteralData())
597 FoundHexdecimalEnumerator =
598 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
599 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000600 if (!FoundHexdecimalEnumerator)
601 AllHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000602 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000603 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000604 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000605}
606
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000607void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000608 const ObjCImplementationDecl *ImpDecl) {
609 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000610 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000611 return;
612 // Find all implicit conforming protocols for this class
613 // and make them explicit.
614 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
615 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000616 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000617
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000618 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000619 ObjCProtocolDecls.begin(),
620 E = ObjCProtocolDecls.end(); I != E; ++I)
621 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000622 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000623
624 if (PotentialImplicitProtocols.empty())
625 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000626
627 // go through list of non-optional methods and properties in each protocol
628 // in the PotentialImplicitProtocols list. If class implements every one of the
629 // methods and properties, then this class conforms to this protocol.
630 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
631 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000632 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000633 PotentialImplicitProtocols[i]))
634 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000635
636 if (ConformingProtocols.empty())
637 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000638
639 // Further reduce number of conforming protocols. If protocol P1 is in the list
640 // protocol P2 (P2<P1>), No need to include P1.
641 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
642 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
643 bool DropIt = false;
644 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
645 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
646 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
647 if (PDecl == TargetPDecl)
648 continue;
649 if (PDecl->lookupProtocolNamed(
650 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
651 DropIt = true;
652 break;
653 }
654 }
655 if (!DropIt)
656 MinimalConformingProtocols.push_back(TargetPDecl);
657 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000658 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000659 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
660 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000661 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000662}
663
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000664void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
665 const TypedefDecl *TypedefDcl) {
666
667 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
668 if (NSAPIObj->isObjCNSIntegerType(qt))
669 NSIntegerTypedefed = TypedefDcl;
670 else if (NSAPIObj->isObjCNSUIntegerType(qt))
671 NSUIntegerTypedefed = TypedefDcl;
672}
673
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000674bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
Fariborz Jahanian92463272013-07-18 20:11:45 +0000675 const EnumDecl *EnumDcl,
676 const TypedefDecl *TypedefDcl) {
677 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000678 EnumDcl->isDeprecated())
679 return false;
680 if (!TypedefDcl) {
681 if (NSIntegerTypedefed) {
682 TypedefDcl = NSIntegerTypedefed;
683 NSIntegerTypedefed = 0;
684 }
685 else if (NSUIntegerTypedefed) {
686 TypedefDcl = NSUIntegerTypedefed;
687 NSUIntegerTypedefed = 0;
688 }
689 else
690 return false;
691 unsigned FileIdOfTypedefDcl =
692 PP.getSourceManager().getFileID(TypedefDcl->getLocation()).getHashValue();
693 unsigned FileIdOfEnumDcl =
694 PP.getSourceManager().getFileID(EnumDcl->getLocation()).getHashValue();
695 if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
696 return false;
697 }
698 if (TypedefDcl->isDeprecated())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000699 return false;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000700
701 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000702 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
703 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000704
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000705 if (!IsNSIntegerType && !IsNSUIntegerType) {
706 // Also check for typedef enum {...} TD;
707 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
708 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000709 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000710 if (NSOptions) {
711 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000712 return false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000713 }
714 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000715 return false;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000716 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000717 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000718 Editor->commit(commit);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000719 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000720 }
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000721 return false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000722 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000723
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000724 // We may still use NS_OPTIONS based on what we find in the enumertor list.
725 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000726 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000727 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000728 return false;
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000729 // NS_OPTIONS must be available.
730 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000731 return false;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000732 edit::Commit commit(*Editor);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000733 bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
734 commit, IsNSIntegerType, NSOptions);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000735 Editor->commit(commit);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000736 return Res;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000737}
738
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000739static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
740 ObjCMethodDecl *OM) {
741 SourceRange R;
742 std::string ClassString;
743 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
744 TypeLoc TL = TSInfo->getTypeLoc();
745 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
746 ClassString = "instancetype";
747 }
748 else {
749 R = SourceRange(OM->getLocStart(), OM->getLocStart());
750 ClassString = OM->isInstanceMethod() ? '-' : '+';
751 ClassString += " (instancetype)";
752 }
753 edit::Commit commit(*ASTC.Editor);
754 commit.replace(R, ClassString);
755 ASTC.Editor->commit(commit);
756}
757
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000758static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
759 ObjCMethodDecl *OM) {
760 ObjCInterfaceDecl *IDecl = OM->getClassInterface();
761 SourceRange R;
762 std::string ClassString;
763 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
764 TypeLoc TL = TSInfo->getTypeLoc();
765 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
766 ClassString = IDecl->getName();
767 ClassString += "*";
768 }
769 }
770 else {
771 R = SourceRange(OM->getLocStart(), OM->getLocStart());
772 ClassString = "+ (";
773 ClassString += IDecl->getName(); ClassString += "*)";
774 }
775 edit::Commit commit(*ASTC.Editor);
776 commit.replace(R, ClassString);
777 ASTC.Editor->commit(commit);
778}
779
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000780void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
781 ObjCContainerDecl *CDecl,
782 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +0000783 ObjCInstanceTypeFamily OIT_Family =
784 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000785
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000786 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000787 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000788 case OIT_None:
789 migrateFactoryMethod(Ctx, CDecl, OM);
790 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000791 case OIT_Array:
792 ClassName = "NSArray";
793 break;
794 case OIT_Dictionary:
795 ClassName = "NSDictionary";
796 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000797 case OIT_Singleton:
798 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000799 return;
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +0000800 case OIT_Init:
801 if (OM->getResultType()->isObjCIdType())
802 ReplaceWithInstancetype(*this, OM);
803 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000804 case OIT_ReturnsSelf:
805 migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
806 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000807 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000808 if (!OM->getResultType()->isObjCIdType())
809 return;
810
811 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
812 if (!IDecl) {
813 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
814 IDecl = CatDecl->getClassInterface();
815 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
816 IDecl = ImpDecl->getClassInterface();
817 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000818 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000819 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
820 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000821 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000822 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000823 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000824}
825
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000826static bool TypeIsInnerPointer(QualType T) {
827 if (!T->isAnyPointerType())
828 return false;
829 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
Fariborz Jahanian73466ca2013-09-26 21:43:47 +0000830 T->isBlockPointerType() || T->isFunctionPointerType() ||
831 ento::coreFoundation::isCFObjectRef(T))
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000832 return false;
Fariborz Jahanian9d5fffb2013-09-09 23:56:14 +0000833 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
834 // is not an innter pointer type.
835 QualType OrigT = T;
836 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
837 T = TD->getDecl()->getUnderlyingType();
838 if (OrigT == T || !T->isPointerType())
839 return true;
840 const PointerType* PT = T->getAs<PointerType>();
841 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
842 if (UPointeeT->isRecordType()) {
843 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
844 if (!RecordTy->getDecl()->isCompleteDefinition())
845 return false;
846 }
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000847 return true;
848}
849
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000850static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2) {
851 if (Decl1->hasAttrs() != Decl2->hasAttrs())
852 return false;
853
854 if (!Decl1->hasAttrs())
855 return true;
856
857 const AttrVec &Attrs1 = Decl1->getAttrs();
858 const AttrVec &Attrs2 = Decl2->getAttrs();
859 // This list is very small, so this need not be optimized.
860 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
861 bool match = false;
862 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
863 // Matching attribute kind only. We are not getting into
864 // details of the attributes. For all practical purposes
865 // this is sufficient.
866 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
867 match = true;
868 break;
869 }
870 }
871 if (!match)
872 return false;
873 }
874 return true;
875}
876
Fariborz Jahanian5d783df2013-09-27 22:55:54 +0000877static bool IsValidIdentifier(ASTContext &Ctx,
878 const char *Name) {
879 if (!isIdentifierHead(Name[0]))
880 return false;
881 std::string NameString = Name;
882 NameString[0] = toLowercase(NameString[0]);
883 IdentifierInfo *II = &Ctx.Idents.get(NameString);
884 return II->getTokenID() == tok::identifier;
885}
886
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000887bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000888 ObjCContainerDecl *D,
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000889 ObjCMethodDecl *Method) {
890 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
891 Method->param_size() != 0)
892 return false;
893 // Is this method candidate to be a getter?
894 QualType GRT = Method->getResultType();
895 if (GRT->isVoidType())
896 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000897
898 Selector GetterSelector = Method->getSelector();
Fariborz Jahanian7391a7b5a2013-09-25 00:17:07 +0000899 ObjCInstanceTypeFamily OIT_Family =
900 Selector::getInstTypeMethodFamily(GetterSelector);
901
902 if (OIT_Family != OIT_None)
903 return false;
904
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000905 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
906 Selector SetterSelector =
907 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
908 PP.getSelectorTable(),
909 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000910 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000911 unsigned LengthOfPrefix = 0;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000912 if (!SetterMethod) {
913 // try a different naming convention for getter: isXxxxx
914 StringRef getterNameString = getterName->getName();
Fariborz Jahanianca399602013-09-11 17:05:15 +0000915 bool IsPrefix = getterNameString.startswith("is");
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +0000916 // Note that we don't want to change an isXXX method of retainable object
917 // type to property (readonly or otherwise).
918 if (IsPrefix && GRT->isObjCRetainableType())
919 return false;
920 if (IsPrefix || getterNameString.startswith("get")) {
Fariborz Jahanianca399602013-09-11 17:05:15 +0000921 LengthOfPrefix = (IsPrefix ? 2 : 3);
922 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
923 // Make sure that first character after "is" or "get" prefix can
924 // start an identifier.
Fariborz Jahanian5d783df2013-09-27 22:55:54 +0000925 if (!IsValidIdentifier(Ctx, CGetterName))
Fariborz Jahanianca399602013-09-11 17:05:15 +0000926 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000927 if (CGetterName[0] && isUppercase(CGetterName[0])) {
928 getterName = &Ctx.Idents.get(CGetterName);
929 SetterSelector =
930 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
931 PP.getSelectorTable(),
932 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000933 SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000934 }
935 }
936 }
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +0000937
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000938 if (SetterMethod) {
Fariborz Jahanianc1213862013-10-02 21:32:39 +0000939 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
940 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000941 if (SetterMethod->isDeprecated() ||
942 !AttributesMatch(Method, SetterMethod))
Fariborz Jahanianf6c65052013-09-17 22:41:25 +0000943 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000944
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000945 // Is this a valid setter, matching the target getter?
946 QualType SRT = SetterMethod->getResultType();
947 if (!SRT->isVoidType())
948 return false;
949 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
950 QualType ArgType = argDecl->getType();
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000951 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000952 return false;
953 edit::Commit commit(*Editor);
954 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000955 LengthOfPrefix,
956 (ASTMigrateActions &
957 FrontendOptions::ObjCMT_AtomicProperty) != 0);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000958 Editor->commit(commit);
959 return true;
960 }
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000961 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000962 // Try a non-void method with no argument (and no setter or property of same name
963 // as a 'readonly' property.
964 edit::Commit commit(*Editor);
965 rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000966 LengthOfPrefix,
967 (ASTMigrateActions &
968 FrontendOptions::ObjCMT_AtomicProperty) != 0);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000969 Editor->commit(commit);
970 return true;
971 }
972 return false;
973}
974
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000975void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
976 ObjCMethodDecl *OM) {
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000977 if (OM->isImplicit() ||
Fariborz Jahanian7c1a4452013-09-26 22:43:41 +0000978 !OM->isInstanceMethod() ||
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000979 OM->hasAttr<ObjCReturnsInnerPointerAttr>())
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000980 return;
981
982 QualType RT = OM->getResultType();
983 if (!TypeIsInnerPointer(RT) ||
984 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
985 return;
986
987 edit::Commit commit(*Editor);
988 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
989 Editor->commit(commit);
990}
991
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000992void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
993 ObjCPropertyDecl *P) {
994 QualType T = P->getType();
995
996 if (!TypeIsInnerPointer(T) ||
997 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
998 return;
999 edit::Commit commit(*Editor);
1000 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
1001 Editor->commit(commit);
1002}
1003
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001004void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
Fariborz Jahanian71221352013-07-23 22:42:28 +00001005 ObjCContainerDecl *CDecl) {
Fariborz Jahaniane47a14a2013-09-18 15:43:52 +00001006 if (CDecl->isDeprecated())
1007 return;
1008
Fariborz Jahanian71221352013-07-23 22:42:28 +00001009 // migrate methods which can have instancetype as their result type.
1010 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1011 MEnd = CDecl->meth_end();
1012 M != MEnd; ++M) {
1013 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001014 if (Method->isDeprecated())
1015 continue;
Fariborz Jahanian71221352013-07-23 22:42:28 +00001016 migrateMethodInstanceType(Ctx, CDecl, Method);
1017 }
1018}
1019
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001020void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
1021 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001022 ObjCMethodDecl *OM,
1023 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +00001024 if (OM->isInstanceMethod() ||
1025 OM->getResultType() == Ctx.getObjCInstanceType() ||
1026 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001027 return;
1028
1029 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1030 // NSYYYNamE with matching names be at least 3 characters long.
1031 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1032 if (!IDecl) {
1033 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1034 IDecl = CatDecl->getClassInterface();
1035 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1036 IDecl = ImpDecl->getClassInterface();
1037 }
1038 if (!IDecl)
1039 return;
1040
1041 std::string StringClassName = IDecl->getName();
1042 StringRef LoweredClassName(StringClassName);
1043 std::string StringLoweredClassName = LoweredClassName.lower();
1044 LoweredClassName = StringLoweredClassName;
1045
1046 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001047 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1048 if (!MethodIdName)
1049 return;
1050
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001051 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001052 if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001053 StringRef STRefMethodName(MethodName);
1054 size_t len = 0;
1055 if (STRefMethodName.startswith("standard"))
1056 len = strlen("standard");
1057 else if (STRefMethodName.startswith("shared"))
1058 len = strlen("shared");
1059 else if (STRefMethodName.startswith("default"))
1060 len = strlen("default");
1061 else
1062 return;
1063 MethodName = STRefMethodName.substr(len);
1064 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001065 std::string MethodNameSubStr = MethodName.substr(0, 3);
1066 StringRef MethodNamePrefix(MethodNameSubStr);
1067 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1068 MethodNamePrefix = StringLoweredMethodNamePrefix;
1069 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1070 if (Ix == StringRef::npos)
1071 return;
1072 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1073 StringRef LoweredMethodName(MethodName);
1074 std::string StringLoweredMethodName = LoweredMethodName.lower();
1075 LoweredMethodName = StringLoweredMethodName;
1076 if (!LoweredMethodName.startswith(ClassNamePostfix))
1077 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001078 if (OIT_Family == OIT_ReturnsSelf)
1079 ReplaceWithClasstype(*this, OM);
1080 else
1081 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001082}
1083
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001084static bool IsVoidStarType(QualType Ty) {
1085 if (!Ty->isPointerType())
1086 return false;
1087
1088 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1089 Ty = TD->getDecl()->getUnderlyingType();
1090
1091 // Is the type void*?
1092 const PointerType* PT = Ty->getAs<PointerType>();
1093 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1094 return true;
1095 return IsVoidStarType(PT->getPointeeType());
1096}
1097
Fariborz Jahanian94279392013-08-20 18:54:39 +00001098/// AuditedType - This routine audits the type AT and returns false if it is one of known
1099/// CF object types or of the "void *" variety. It returns true if we don't care about the type
1100/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001101static bool AuditedType (QualType AT) {
1102 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001103 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001104 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +00001105 if (ento::coreFoundation::isCFObjectRef(AT) ||
1106 IsVoidStarType(AT) ||
1107 // If an ObjC object is type, assuming that it is not a CF function and
1108 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +00001109 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001110 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +00001111 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001112 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001113}
1114
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001115void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001116 if (CFFunctionIBCandidates.empty())
1117 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001118 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
1119 CFFunctionIBCandidates.clear();
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001120 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001121 return;
1122 }
1123 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001124 const Decl *FirstFD = CFFunctionIBCandidates[0];
1125 const Decl *LastFD =
1126 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001127 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1128 edit::Commit commit(*Editor);
1129 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
1130 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1131 SourceLocation EndLoc = LastFD->getLocEnd();
1132 // get location just past end of function location.
1133 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001134 if (isa<FunctionDecl>(LastFD)) {
1135 // For Methods, EndLoc points to the ending semcolon. So,
1136 // not of these extra work is needed.
1137 Token Tok;
1138 // get locaiton of token that comes after end of function.
1139 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1140 if (!Failed)
1141 EndLoc = Tok.getLocation();
1142 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001143 commit.insertAfterToken(EndLoc, PragmaString);
1144 Editor->commit(commit);
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001145 FileId = 0;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001146 CFFunctionIBCandidates.clear();
1147}
1148
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001149void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001150 if (Decl->isDeprecated())
1151 return;
1152
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001153 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001154 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001155 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001156 "provided CF_IMPLICIT_BRIDGING_ENABLE");
1157 return;
1158 }
1159
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001160 // Finction must be annotated first.
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001161 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1162 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1163 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001164 CFFunctionIBCandidates.push_back(Decl);
1165 if (!FileId)
1166 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1167 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001168 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1169 if (!CFFunctionIBCandidates.empty()) {
1170 CFFunctionIBCandidates.push_back(Decl);
1171 if (!FileId)
1172 FileId = PP.getSourceManager().getFileID(Decl->getLocation()).getHashValue();
1173 }
1174 }
1175 else
1176 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001177 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001178 else {
1179 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001180 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001181 }
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001182}
1183
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001184void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1185 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001186 const FunctionDecl *FuncDecl,
1187 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001188 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001189 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001190 RetEffect Ret = CE.getReturnValue();
1191 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001192 if (Ret.getObjKind() == RetEffect::CF) {
1193 if (Ret.isOwned() &&
1194 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001195 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001196 else if (Ret.notOwned() &&
1197 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001198 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1199 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001200 else if (Ret.getObjKind() == RetEffect::ObjC) {
1201 if (Ret.isOwned() &&
1202 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1203 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001204 }
1205
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001206 if (AnnotationString) {
1207 edit::Commit commit(*Editor);
1208 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1209 Editor->commit(commit);
1210 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001211 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001212 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1213 unsigned i = 0;
1214 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1215 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +00001216 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001217 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001218 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1219 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1220 edit::Commit commit(*Editor);
1221 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1222 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +00001223 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001224 else if (AE == DecRefMsg && !pd->getAttr<NSConsumedAttr>() &&
1225 Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
1226 edit::Commit commit(*Editor);
1227 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1228 Editor->commit(commit);
1229 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001230 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001231}
1232
1233
1234ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1235 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1236 ASTContext &Ctx,
1237 const FunctionDecl *FuncDecl) {
1238 if (FuncDecl->hasBody())
1239 return CF_BRIDGING_NONE;
1240
1241 CallEffects CE = CallEffects::getEffect(FuncDecl);
1242 bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001243 FuncDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1244 FuncDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001245 FuncDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1246 FuncDecl->getAttr<NSReturnsAutoreleasedAttr>());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001247
1248 // Trivial case of when funciton is annotated and has no argument.
1249 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1250 return CF_BRIDGING_NONE;
1251
1252 bool ReturnCFAudited = false;
1253 if (!FuncIsReturnAnnotated) {
1254 RetEffect Ret = CE.getReturnValue();
1255 if (Ret.getObjKind() == RetEffect::CF &&
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001256 (Ret.isOwned() || Ret.notOwned()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001257 ReturnCFAudited = true;
1258 else if (!AuditedType(FuncDecl->getResultType()))
1259 return CF_BRIDGING_NONE;
1260 }
1261
1262 // At this point result type is audited for potential inclusion.
1263 // Now, how about argument types.
1264 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1265 unsigned i = 0;
1266 bool ArgCFAudited = false;
1267 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1268 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1269 const ParmVarDecl *pd = *pi;
1270 ArgEffect AE = AEArgs[i];
1271 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1272 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
1273 ArgCFAudited = true;
1274 else if (AE == IncRef)
1275 ArgCFAudited = true;
1276 }
1277 else {
1278 QualType AT = pd->getType();
1279 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001280 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001281 return CF_BRIDGING_NONE;
1282 }
1283 }
1284 }
1285 if (ReturnCFAudited || ArgCFAudited)
1286 return CF_BRIDGING_ENABLE;
1287
1288 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001289}
1290
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001291void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1292 ObjCContainerDecl *CDecl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001293 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001294 return;
1295
1296 // migrate methods which can have instancetype as their result type.
1297 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1298 MEnd = CDecl->meth_end();
1299 M != MEnd; ++M) {
1300 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001301 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001302 }
1303}
1304
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001305void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1306 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001307 const ObjCMethodDecl *MethodDecl,
1308 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001309 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001310 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001311 RetEffect Ret = CE.getReturnValue();
1312 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001313 if (Ret.getObjKind() == RetEffect::CF) {
1314 if (Ret.isOwned() &&
1315 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001316 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001317 else if (Ret.notOwned() &&
1318 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001319 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1320 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001321 else if (Ret.getObjKind() == RetEffect::ObjC) {
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001322 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1323 switch (OMF) {
1324 case clang::OMF_alloc:
1325 case clang::OMF_new:
1326 case clang::OMF_copy:
1327 case clang::OMF_init:
1328 case clang::OMF_mutableCopy:
1329 break;
1330
1331 default:
1332 if (Ret.isOwned() &&
1333 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1334 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001335 break;
1336 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001337 }
1338
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001339 if (AnnotationString) {
1340 edit::Commit commit(*Editor);
1341 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1342 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001343 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001344 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001345 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1346 unsigned i = 0;
1347 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1348 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1349 const ParmVarDecl *pd = *pi;
1350 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001351 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1352 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1353 edit::Commit commit(*Editor);
1354 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1355 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001356 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001357 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001358}
1359
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001360void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001361 ASTContext &Ctx,
1362 const ObjCMethodDecl *MethodDecl) {
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001363 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001364 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001365
1366 CallEffects CE = CallEffects::getEffect(MethodDecl);
1367 bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001368 MethodDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1369 MethodDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001370 MethodDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1371 MethodDecl->getAttr<NSReturnsAutoreleasedAttr>());
1372
1373 if (CE.getReceiver() == DecRefMsg &&
1374 !MethodDecl->getAttr<NSConsumesSelfAttr>() &&
1375 MethodDecl->getMethodFamily() != OMF_init &&
1376 MethodDecl->getMethodFamily() != OMF_release &&
1377 Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
1378 edit::Commit commit(*Editor);
1379 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1380 Editor->commit(commit);
1381 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001382
1383 // Trivial case of when funciton is annotated and has no argument.
1384 if (MethodIsReturnAnnotated &&
1385 (MethodDecl->param_begin() == MethodDecl->param_end()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001386 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001387
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001388 if (!MethodIsReturnAnnotated) {
1389 RetEffect Ret = CE.getReturnValue();
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001390 if ((Ret.getObjKind() == RetEffect::CF ||
1391 Ret.getObjKind() == RetEffect::ObjC) &&
1392 (Ret.isOwned() || Ret.notOwned())) {
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001393 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1394 return;
1395 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001396 else if (!AuditedType(MethodDecl->getResultType()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001397 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001398 }
1399
1400 // At this point result type is either annotated or audited.
1401 // Now, how about argument types.
1402 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1403 unsigned i = 0;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001404 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1405 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1406 const ParmVarDecl *pd = *pi;
1407 ArgEffect AE = AEArgs[i];
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001408 if ((AE == DecRef && !pd->getAttr<CFConsumedAttr>()) || AE == IncRef ||
1409 !AuditedType(pd->getType())) {
1410 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1411 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001412 }
1413 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001414 return;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001415}
1416
Ted Kremenekf7639e12012-03-06 20:06:33 +00001417namespace {
1418
1419class RewritesReceiver : public edit::EditsReceiver {
1420 Rewriter &Rewrite;
1421
1422public:
1423 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1424
1425 virtual void insert(SourceLocation loc, StringRef text) {
1426 Rewrite.InsertText(loc, text);
1427 }
1428 virtual void replace(CharSourceRange range, StringRef text) {
1429 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1430 }
1431};
1432
1433}
1434
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001435static bool
1436IsReallyASystemHeader(ASTContext &Ctx, const FileEntry *file, FileID FID) {
1437 bool Invalid = false;
1438 const SrcMgr::SLocEntry &SEntry =
1439 Ctx.getSourceManager().getSLocEntry(FID, &Invalid);
1440 if (!Invalid && SEntry.isFile()) {
1441 const SrcMgr::FileInfo &FI = SEntry.getFile();
1442 if (!FI.hasLineDirectives()) {
1443 if (FI.getFileCharacteristic() == SrcMgr::C_ExternCSystem)
1444 return true;
1445 if (FI.getFileCharacteristic() == SrcMgr::C_System) {
1446 // This file is in a system header directory. Continue with commiting change
1447 // only if it is a user specified system directory because user put a
1448 // .system_framework file in the framework directory.
1449 StringRef Directory(file->getDir()->getName());
1450 size_t Ix = Directory.rfind(".framework");
1451 if (Ix == StringRef::npos)
1452 return true;
1453 std::string PatchToSystemFramework = Directory.slice(0, Ix+sizeof(".framework"));
1454 PatchToSystemFramework += ".system_framework";
1455 if (!llvm::sys::fs::exists(PatchToSystemFramework.data()))
1456 return true;
1457 }
1458 }
1459 }
1460 return false;
1461}
1462
Ted Kremenekf7639e12012-03-06 20:06:33 +00001463void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001464
1465 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001466 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001467 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1468 D != DEnd; ++D) {
Fariborz Jahanianb8343522013-08-20 23:35:26 +00001469 if (unsigned FID =
1470 PP.getSourceManager().getFileID((*D)->getLocation()).getHashValue())
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001471 if (FileId && FileId != FID) {
1472 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1473 AnnotateImplicitBridging(Ctx);
1474 }
1475
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001476 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1477 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001478 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D))
1479 migrateObjCInterfaceDecl(Ctx, CatDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001480 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1481 ObjCProtocolDecls.insert(PDecl);
1482 else if (const ObjCImplementationDecl *ImpDecl =
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001483 dyn_cast<ObjCImplementationDecl>(*D)) {
1484 if (ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance)
1485 migrateProtocolConformance(Ctx, ImpDecl);
1486 }
Fariborz Jahanian92463272013-07-18 20:11:45 +00001487 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001488 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1489 continue;
Fariborz Jahanian92463272013-07-18 20:11:45 +00001490 DeclContext::decl_iterator N = D;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001491 if (++N != DEnd) {
1492 const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
1493 if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
1494 D++;
1495 }
1496 else
1497 migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */0);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001498 }
1499 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001500 if (ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros) {
1501 DeclContext::decl_iterator N = D;
1502 if (++N != DEnd)
1503 if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
1504 if (migrateNSEnumDecl(Ctx, ED, TD)) {
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001505 ++D;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001506 continue;
1507 }
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001508 }
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001509 CacheObjCNSIntegerTypedefed(TD);
1510 }
Fariborz Jahanian92463272013-07-18 20:11:45 +00001511 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001512 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
1513 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1514 migrateCFAnnotation(Ctx, FD);
1515 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001516
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001517 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1518 // migrate methods which can have instancetype as their result type.
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001519 if (ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype)
1520 migrateAllMethodInstaceType(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001521 // annotate methods with CF annotations.
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001522 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1523 migrateARCSafeAnnotation(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001524 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001525 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001526 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1527 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001528 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001529
David Blaikiebbafb8a2012-03-11 07:00:24 +00001530 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001531 RewritesReceiver Rec(rewriter);
1532 Editor->applyRewrites(Rec);
1533
1534 for (Rewriter::buffer_iterator
1535 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1536 FileID FID = I->first;
1537 RewriteBuffer &buf = I->second;
1538 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1539 assert(file);
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001540 if (IsReallyASystemHeader(Ctx, file, FID))
1541 continue;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001542 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001543 llvm::raw_svector_ostream vecOS(newText);
1544 buf.write(vecOS);
1545 vecOS.flush();
1546 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1547 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001548 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001549 FileMgr.FixupRelativePath(filePath);
1550 Remapper.remap(filePath.str(), memBuf);
1551 }
1552
1553 if (IsOutputFile) {
1554 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1555 } else {
1556 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1557 }
1558}
1559
1560bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001561 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001562 return true;
1563}
1564
1565ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1566 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001567 PPConditionalDirectiveRecord *
1568 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1569 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001570 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001571 FrontendOptions::ObjCMT_MigrateAll,
Ted Kremenekf7639e12012-03-06 20:06:33 +00001572 Remapper,
1573 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001574 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001575 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +00001576 /*isOutputFile=*/true);
1577}