blob: dce5ff9b15aa6d84ca8e0431fad0e38933fc7721 [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 Jahaniand41dbad2013-10-31 16:10:44 +000047 void migrateDeprecatedAnnotation(ASTContext &Ctx, ObjCCategoryDecl *CatDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +000048 void migrateProtocolConformance(ASTContext &Ctx,
49 const ObjCImplementationDecl *ImpDecl);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +000050 void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +000051 bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
Fariborz Jahanian92463272013-07-18 20:11:45 +000052 const TypedefDecl *TypedefDcl);
Fariborz Jahanian8c45e282013-10-02 22:49:59 +000053 void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000054 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
55 ObjCMethodDecl *OM);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000056 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +000057 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
Fariborz Jahanian10b74352013-09-24 20:20:52 +000058 void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000059 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000060 ObjCMethodDecl *OM,
61 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000062
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000063 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000064 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000065 const FunctionDecl *FuncDecl, bool ResultAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000066 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000067 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000068
Fariborz Jahanian301b5212013-08-20 22:42:13 +000069 void AnnotateImplicitBridging(ASTContext &Ctx);
70
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000071 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
72 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000073
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000074 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
75
Fariborz Jahanian89f6d102013-09-04 00:10:06 +000076 void migrateAddMethodAnnotation(ASTContext &Ctx,
77 const ObjCMethodDecl *MethodDecl);
Ted Kremenekf7639e12012-03-06 20:06:33 +000078public:
79 std::string MigrateDir;
Fariborz Jahanian182486c2013-10-02 17:08:12 +000080 unsigned ASTMigrateActions;
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +000081 FileID FileId;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +000082 const TypedefDecl *NSIntegerTypedefed;
83 const TypedefDecl *NSUIntegerTypedefed;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000084 OwningPtr<NSAPI> NSAPIObj;
85 OwningPtr<edit::EditedSource> Editor;
Ted Kremenekf7639e12012-03-06 20:06:33 +000086 FileRemapper &Remapper;
87 FileManager &FileMgr;
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000088 const PPConditionalDirectiveRecord *PPRec;
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000089 Preprocessor &PP;
Ted Kremenekf7639e12012-03-06 20:06:33 +000090 bool IsOutputFile;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000091 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000092 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Fariborz Jahanian1be01532013-07-12 22:32:19 +000093
Ted Kremenekf7639e12012-03-06 20:06:33 +000094 ObjCMigrateASTConsumer(StringRef migrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +000095 unsigned astMigrateActions,
Ted Kremenekf7639e12012-03-06 20:06:33 +000096 FileRemapper &remapper,
97 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000098 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +000099 Preprocessor &PP,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000100 bool isOutputFile = false)
101 : MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000102 ASTMigrateActions(astMigrateActions),
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +0000103 NSIntegerTypedefed(0), NSUIntegerTypedefed(0),
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000104 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000105 IsOutputFile(isOutputFile) { }
106
107protected:
108 virtual void Initialize(ASTContext &Context) {
109 NSAPIObj.reset(new NSAPI(Context));
110 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000111 Context.getLangOpts(),
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +0000112 PPRec, false));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000113 }
114
115 virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
116 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
117 migrateDecl(*I);
118 return true;
119 }
120 virtual void HandleInterestingDecl(DeclGroupRef DG) {
121 // Ignore decls from the PCH.
122 }
123 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) {
124 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
125 }
126
127 virtual void HandleTranslationUnit(ASTContext &Ctx);
128};
129
130}
131
132ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000133 StringRef migrateDir,
134 unsigned migrateAction)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000135 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000136 ObjCMigAction(migrateAction),
Ted Kremenekf7639e12012-03-06 20:06:33 +0000137 CompInst(0) {
138 if (MigrateDir.empty())
139 MigrateDir = "."; // user current directory if none is given.
140}
141
142ASTConsumer *ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI,
143 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000144 PPConditionalDirectiveRecord *
145 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
146 CompInst->getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000147 ASTConsumer *
148 WrappedConsumer = WrapperFrontendAction::CreateASTConsumer(CI, InFile);
149 ASTConsumer *MTConsumer = new ObjCMigrateASTConsumer(MigrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000150 ObjCMigAction,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000151 Remapper,
152 CompInst->getFileManager(),
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000153 PPRec,
154 CompInst->getPreprocessor());
Ted Kremenekf7639e12012-03-06 20:06:33 +0000155 ASTConsumer *Consumers[] = { MTConsumer, WrappedConsumer };
156 return new MultiplexConsumer(Consumers);
157}
158
159bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
160 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
161 /*ignoreIfFilesChanges=*/true);
162 CompInst = &CI;
163 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000164 return true;
165}
166
167namespace {
168class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
169 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000170 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000171
172public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000173 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
174 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000175
176 bool shouldVisitTemplateInstantiations() const { return false; }
177 bool shouldWalkTypesOfTypeLocs() const { return false; }
178
179 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000180 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000181 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000182 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000183 Consumer.Editor->commit(commit);
184 }
185
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000186 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000187 edit::Commit commit(*Consumer.Editor);
188 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
189 Consumer.Editor->commit(commit);
190 }
191
192 return true;
193 }
194
195 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
196 // Do depth first; we want to rewrite the subexpressions first so that if
197 // we have to move expressions we will move them already rewritten.
198 for (Stmt::child_range range = E->children(); range; ++range)
199 if (!TraverseStmt(*range))
200 return false;
201
202 return WalkUpFromObjCMessageExpr(E);
203 }
204};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000205
206class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
207 ObjCMigrateASTConsumer &Consumer;
208 OwningPtr<ParentMap> PMap;
209
210public:
211 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
212
213 bool shouldVisitTemplateInstantiations() const { return false; }
214 bool shouldWalkTypesOfTypeLocs() const { return false; }
215
216 bool TraverseStmt(Stmt *S) {
217 PMap.reset(new ParentMap(S));
218 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
219 return true;
220 }
221};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000222}
223
224void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
225 if (!D)
226 return;
227 if (isa<ObjCMethodDecl>(D))
228 return; // Wait for the ObjC container declaration.
229
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000230 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000231}
232
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000233static void append_attr(std::string &PropertyString, const char *attr,
234 bool &LParenAdded) {
235 if (!LParenAdded) {
236 PropertyString += "(";
237 LParenAdded = true;
238 }
239 else
240 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000241 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000242}
243
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000244static
245void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
246 const std::string& TypeString,
247 const char *name) {
248 const char *argPtr = TypeString.c_str();
249 int paren = 0;
250 while (*argPtr) {
251 switch (*argPtr) {
252 case '(':
253 PropertyString += *argPtr;
254 paren++;
255 break;
256 case ')':
257 PropertyString += *argPtr;
258 paren--;
259 break;
260 case '^':
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000261 case '*':
262 PropertyString += (*argPtr);
263 if (paren == 1) {
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000264 PropertyString += name;
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000265 name = "";
266 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000267 break;
268 default:
269 PropertyString += *argPtr;
270 break;
271 }
272 argPtr++;
273 }
274}
275
276
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000277static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000278 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000279 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000280 unsigned LengthOfPrefix,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +0000281 bool Atomic, bool UseNsIosOnlyMacro,
282 bool AvailabilityArgsMatch) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000283 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000284 bool LParenAdded = false;
285 std::string PropertyString = "@property ";
Fariborz Jahanian2e793d62013-11-13 00:08:36 +0000286 if (UseNsIosOnlyMacro && Context.Idents.get("NS_NONATOMIC_IOSONLY").hasMacroDefinition()) {
Fariborz Jahanianbed1be92013-11-12 19:25:50 +0000287 PropertyString += "(NS_NONATOMIC_IOSONLY";
288 LParenAdded = true;
289 } else if (!Atomic) {
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000290 PropertyString += "(nonatomic";
291 LParenAdded = true;
292 }
293
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000294 std::string PropertyNameString = Getter->getNameAsString();
295 StringRef PropertyName(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000296 if (LengthOfPrefix > 0) {
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000297 if (!LParenAdded) {
298 PropertyString += "(getter=";
299 LParenAdded = true;
300 }
301 else
302 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000303 PropertyString += PropertyNameString;
304 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000305 // Property with no setter may be suggested as a 'readonly' property.
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000306 if (!Setter) {
307 if (!LParenAdded) {
308 PropertyString += "(readonly";
309 LParenAdded = true;
310 }
311 else
312 append_attr(PropertyString, "readonly", LParenAdded);
313 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000314
Fariborz Jahanian33304e302013-10-16 18:52:17 +0000315 // Short circuit 'delegate' properties that contain the name "delegate" or
316 // "dataSource", or have exact name "target" to have 'assign' attribute.
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000317 if (PropertyName.equals("target") ||
318 (PropertyName.find("delegate") != StringRef::npos) ||
Fariborz Jahanian78bff052013-10-16 20:44:26 +0000319 (PropertyName.find("dataSource") != StringRef::npos)) {
320 QualType QT = Getter->getResultType();
321 if (!QT->isRealType())
322 append_attr(PropertyString, "assign", LParenAdded);
323 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000324 else if (Setter) {
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000325 const ParmVarDecl *argDecl = *Setter->param_begin();
326 QualType ArgType = Context.getCanonicalType(argDecl->getType());
327 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
328 bool RetainableObject = ArgType->isObjCRetainableType();
329 if (RetainableObject && propertyLifetime == Qualifiers::OCL_Strong) {
330 if (const ObjCObjectPointerType *ObjPtrTy =
331 ArgType->getAs<ObjCObjectPointerType>()) {
332 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
333 if (IDecl &&
334 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000335 append_attr(PropertyString, "copy", LParenAdded);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000336 else
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000337 append_attr(PropertyString, "retain", LParenAdded);
Fariborz Jahanian447b15e2013-08-21 18:49:03 +0000338 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000339 else if (ArgType->isBlockPointerType())
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000340 append_attr(PropertyString, "copy", LParenAdded);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000341 } else if (propertyLifetime == Qualifiers::OCL_Weak)
342 // TODO. More precise determination of 'weak' attribute requires
343 // looking into setter's implementation for backing weak ivar.
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000344 append_attr(PropertyString, "weak", LParenAdded);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000345 else if (RetainableObject)
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000346 append_attr(PropertyString,
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000347 ArgType->isBlockPointerType() ? "copy" : "retain", LParenAdded);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000348 }
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000349 if (LParenAdded)
350 PropertyString += ')';
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000351 QualType RT = Getter->getResultType();
352 if (!isa<TypedefType>(RT)) {
353 // strip off any ARC lifetime qualifier.
354 QualType CanResultTy = Context.getCanonicalType(RT);
355 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
356 Qualifiers Qs = CanResultTy.getQualifiers();
357 Qs.removeObjCLifetime();
358 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
359 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000360 }
361 PropertyString += " ";
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000362 PrintingPolicy SubPolicy(Context.getPrintingPolicy());
363 SubPolicy.SuppressStrongLifetime = true;
Fariborz Jahaniande557f82013-10-09 17:37:28 +0000364 SubPolicy.SuppressLifetimeQualifiers = true;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000365 std::string TypeString = RT.getAsString(SubPolicy);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000366 if (LengthOfPrefix > 0) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000367 // property name must strip off "is" and lower case the first character
368 // after that; e.g. isContinuous will become continuous.
369 StringRef PropertyNameStringRef(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000370 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000371 PropertyNameString = PropertyNameStringRef;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000372 bool NoLowering = (isUppercase(PropertyNameString[0]) &&
373 PropertyNameString.size() > 1 &&
374 isUppercase(PropertyNameString[1]));
Fariborz Jahanian34fea362013-09-11 18:27:16 +0000375 if (!NoLowering)
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000376 PropertyNameString[0] = toLowercase(PropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000377 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000378 if (RT->isBlockPointerType() || RT->isFunctionPointerType())
379 MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
380 TypeString,
381 PropertyNameString.c_str());
382 else {
383 char LastChar = TypeString[TypeString.size()-1];
384 PropertyString += TypeString;
385 if (LastChar != '*')
386 PropertyString += ' ';
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000387 PropertyString += PropertyNameString;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000388 }
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000389 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
390 Selector GetterSelector = Getter->getSelector();
391
392 SourceLocation EndGetterSelectorLoc =
393 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000394 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000395 EndGetterSelectorLoc),
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000396 PropertyString);
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000397 if (Setter && AvailabilityArgsMatch) {
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000398 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
399 // Get location past ';'
400 EndLoc = EndLoc.getLocWithOffset(1);
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000401 SourceLocation BeginOfSetterDclLoc = Setter->getLocStart();
402 // FIXME. This assumes that setter decl; is immediately preceeded by eoln.
403 // It is trying to remove the setter method decl. line entirely.
404 BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
405 commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000406 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000407}
408
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000409void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000410 ObjCContainerDecl *D) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000411 if (D->isDeprecated())
412 return;
413
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000414 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
415 M != MEnd; ++M) {
416 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000417 if (Method->isDeprecated())
418 continue;
Fariborz Jahanianec7cea92013-11-08 01:15:17 +0000419 bool PropertyInferred = migrateProperty(Ctx, D, Method);
420 // If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to
421 // the getter method as it ends up on the property itself which we don't want
422 // to do unless -objcmt-returns-innerpointer-property option is on.
423 if (!PropertyInferred ||
424 (ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
Fariborz Jahanian22626e72013-11-08 02:00:22 +0000425 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
426 migrateNsReturnsInnerPointer(Ctx, Method);
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000427 }
Fariborz Jahanian23417072013-11-05 22:28:30 +0000428 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
429 return;
430
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000431 for (ObjCContainerDecl::prop_iterator P = D->prop_begin(),
432 E = D->prop_end(); P != E; ++P) {
433 ObjCPropertyDecl *Prop = *P;
Fariborz Jahanian8c45e282013-10-02 22:49:59 +0000434 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000435 !Prop->isDeprecated())
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000436 migratePropertyNsReturnsInnerPointer(Ctx, Prop);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000437 }
438}
439
Fariborz Jahaniand41dbad2013-10-31 16:10:44 +0000440void ObjCMigrateASTConsumer::migrateDeprecatedAnnotation(ASTContext &Ctx,
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000441 ObjCCategoryDecl *CatDecl) {
442 StringRef Name = CatDecl->getName();
Fariborz Jahaniand41dbad2013-10-31 16:10:44 +0000443 if (!Name.endswith("Deprecated"))
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000444 return;
445
446 if (!Ctx.Idents.get("DEPRECATED").hasMacroDefinition())
447 return;
448
449 ObjCContainerDecl *D = cast<ObjCContainerDecl>(CatDecl);
450
451 for (ObjCContainerDecl::method_iterator M = D->meth_begin(), MEnd = D->meth_end();
452 M != MEnd; ++M) {
453 ObjCMethodDecl *Method = (*M);
454 if (Method->isDeprecated() || Method->isImplicit())
455 continue;
456 // Annotate with DEPRECATED
457 edit::Commit commit(*Editor);
458 commit.insertBefore(Method->getLocEnd(), " DEPRECATED");
459 Editor->commit(commit);
460 }
461 for (ObjCContainerDecl::prop_iterator P = D->prop_begin(),
462 E = D->prop_end(); P != E; ++P) {
463 ObjCPropertyDecl *Prop = *P;
464 if (Prop->isDeprecated())
465 continue;
466 // Annotate with DEPRECATED
467 edit::Commit commit(*Editor);
468 commit.insertAfterToken(Prop->getLocEnd(), " DEPRECATED");
469 Editor->commit(commit);
470 }
471}
472
473static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000474ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000475 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000476 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000477 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000478 // In auto-synthesis, protocol properties are not synthesized. So,
479 // a conforming protocol must have its required properties declared
480 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000481 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000482 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
483 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
484 E = PDecl->prop_end(); P != E; ++P) {
485 ObjCPropertyDecl *Property = *P;
486 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
487 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000488 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000489 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000490 if (R.size() == 0) {
491 // Relax the rule and look into class's implementation for a synthesize
492 // or dynamic declaration. Class is implementing a property coming from
493 // another protocol. This still makes the target protocol as conforming.
494 if (!ImpDecl->FindPropertyImplDecl(
495 Property->getDeclName().getAsIdentifierInfo()))
496 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000497 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000498 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
499 if ((ClassProperty->getPropertyAttributes()
500 != Property->getPropertyAttributes()) ||
501 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
502 return false;
503 }
504 else
505 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000506 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000507
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000508 // At this point, all required properties in this protocol conform to those
509 // declared in the class.
510 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000511 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000512 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
513 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000514 return HasAtleastOneRequiredProperty;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000515 for (ObjCContainerDecl::method_iterator M = PDecl->meth_begin(),
516 MEnd = PDecl->meth_end(); M != MEnd; ++M) {
517 ObjCMethodDecl *MD = (*M);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000518 if (MD->isImplicit())
519 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000520 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
521 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000522 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000523 if (R.size() == 0)
524 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000525 bool match = false;
526 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000527 for (unsigned I = 0, N = R.size(); I != N; ++I)
528 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
529 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
530 match = true;
531 break;
532 }
533 if (!match)
534 return false;
535 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000536 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000537 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
538 return true;
539 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000540}
541
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000542static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
543 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
544 const NSAPI &NS, edit::Commit &commit) {
545 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
546 std::string ClassString;
547 SourceLocation EndLoc =
548 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
549
550 if (Protocols.empty()) {
551 ClassString = '<';
552 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
553 ClassString += ConformingProtocols[i]->getNameAsString();
554 if (i != (e-1))
555 ClassString += ", ";
556 }
557 ClassString += "> ";
558 }
559 else {
560 ClassString = ", ";
561 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
562 ClassString += ConformingProtocols[i]->getNameAsString();
563 if (i != (e-1))
564 ClassString += ", ";
565 }
566 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
567 EndLoc = *PL;
568 }
569
570 commit.insertAfterToken(EndLoc, ClassString);
571 return true;
572}
573
574static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
575 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000576 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000577 bool IsNSIntegerType,
578 bool NSOptions) {
579 std::string ClassString;
580 if (NSOptions)
581 ClassString = "typedef NS_OPTIONS(NSUInteger, ";
582 else
583 ClassString =
584 IsNSIntegerType ? "typedef NS_ENUM(NSInteger, "
585 : "typedef NS_ENUM(NSUInteger, ";
586
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000587 ClassString += TypedefDcl->getIdentifier()->getName();
588 ClassString += ')';
589 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
590 commit.replace(R, ClassString);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000591 SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
592 EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
593 NS.getASTContext(), /*IsDecl*/true);
594 if (!EndOfEnumDclLoc.isInvalid()) {
595 SourceRange EnumDclRange(EnumDcl->getLocStart(), EndOfEnumDclLoc);
596 commit.insertFromRange(TypedefDcl->getLocStart(), EnumDclRange);
597 }
598 else
599 return false;
600
601 SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
602 EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
603 NS.getASTContext(), /*IsDecl*/true);
604 if (!EndTypedefDclLoc.isInvalid()) {
605 SourceRange TDRange(TypedefDcl->getLocStart(), EndTypedefDclLoc);
606 commit.remove(TDRange);
607 }
608 else
609 return false;
610
611 EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
Fariborz Jahanian1d27ffd2013-10-11 17:35:22 +0000612 /*IsDecl*/true);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000613 if (!EndOfEnumDclLoc.isInvalid()) {
614 SourceLocation BeginOfEnumDclLoc = EnumDcl->getLocStart();
615 // FIXME. This assumes that enum decl; is immediately preceeded by eoln.
616 // It is trying to remove the enum decl. lines entirely.
617 BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
618 commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000619 return true;
620 }
621 return false;
622}
623
Fariborz Jahanian403425b2013-10-17 23:13:13 +0000624static void rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000625 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000626 const NSAPI &NS, edit::Commit &commit,
627 bool IsNSIntegerType) {
628 std::string ClassString =
629 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000630 ClassString += TypedefDcl->getIdentifier()->getName();
631 ClassString += ')';
632 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
633 commit.replace(R, ClassString);
634 SourceLocation TypedefLoc = TypedefDcl->getLocEnd();
635 commit.remove(SourceRange(TypedefLoc, TypedefLoc));
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000636}
637
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000638static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000639 const EnumDecl *EnumDcl) {
640 bool PowerOfTwo = true;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000641 bool AllHexdecimalEnumerator = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000642 uint64_t MaxPowerOfTwoVal = 0;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000643 for (EnumDecl::enumerator_iterator EI = EnumDcl->enumerator_begin(),
644 EE = EnumDcl->enumerator_end(); EI != EE; ++EI) {
645 EnumConstantDecl *Enumerator = (*EI);
646 const Expr *InitExpr = Enumerator->getInitExpr();
647 if (!InitExpr) {
648 PowerOfTwo = false;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000649 AllHexdecimalEnumerator = false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000650 continue;
651 }
Fariborz Jahanian6e1798e2013-09-17 23:32:51 +0000652 InitExpr = InitExpr->IgnoreParenCasts();
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000653 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
654 if (BO->isShiftOp() || BO->isBitwiseOp())
655 return true;
656
657 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000658 if (PowerOfTwo && EnumVal) {
659 if (!llvm::isPowerOf2_64(EnumVal))
660 PowerOfTwo = false;
661 else if (EnumVal > MaxPowerOfTwoVal)
662 MaxPowerOfTwoVal = EnumVal;
663 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000664 if (AllHexdecimalEnumerator && EnumVal) {
665 bool FoundHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000666 SourceLocation EndLoc = Enumerator->getLocEnd();
667 Token Tok;
668 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
669 if (Tok.isLiteral() && Tok.getLength() > 2) {
670 if (const char *StringLit = Tok.getLiteralData())
671 FoundHexdecimalEnumerator =
672 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
673 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000674 if (!FoundHexdecimalEnumerator)
675 AllHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000676 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000677 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000678 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000679}
680
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000681void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000682 const ObjCImplementationDecl *ImpDecl) {
683 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000684 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000685 return;
686 // Find all implicit conforming protocols for this class
687 // and make them explicit.
688 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
689 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000690 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000691
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000692 for (llvm::SmallPtrSet<ObjCProtocolDecl*, 32>::iterator I =
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000693 ObjCProtocolDecls.begin(),
694 E = ObjCProtocolDecls.end(); I != E; ++I)
695 if (!ExplicitProtocols.count(*I))
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000696 PotentialImplicitProtocols.push_back(*I);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000697
698 if (PotentialImplicitProtocols.empty())
699 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000700
701 // go through list of non-optional methods and properties in each protocol
702 // in the PotentialImplicitProtocols list. If class implements every one of the
703 // methods and properties, then this class conforms to this protocol.
704 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
705 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000706 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000707 PotentialImplicitProtocols[i]))
708 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000709
710 if (ConformingProtocols.empty())
711 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000712
713 // Further reduce number of conforming protocols. If protocol P1 is in the list
714 // protocol P2 (P2<P1>), No need to include P1.
715 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
716 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
717 bool DropIt = false;
718 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
719 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
720 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
721 if (PDecl == TargetPDecl)
722 continue;
723 if (PDecl->lookupProtocolNamed(
724 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
725 DropIt = true;
726 break;
727 }
728 }
729 if (!DropIt)
730 MinimalConformingProtocols.push_back(TargetPDecl);
731 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000732 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000733 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
734 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000735 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000736}
737
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000738void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
739 const TypedefDecl *TypedefDcl) {
740
741 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
742 if (NSAPIObj->isObjCNSIntegerType(qt))
743 NSIntegerTypedefed = TypedefDcl;
744 else if (NSAPIObj->isObjCNSUIntegerType(qt))
745 NSUIntegerTypedefed = TypedefDcl;
746}
747
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000748bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
Fariborz Jahanian92463272013-07-18 20:11:45 +0000749 const EnumDecl *EnumDcl,
750 const TypedefDecl *TypedefDcl) {
751 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000752 EnumDcl->isDeprecated())
753 return false;
754 if (!TypedefDcl) {
755 if (NSIntegerTypedefed) {
756 TypedefDcl = NSIntegerTypedefed;
757 NSIntegerTypedefed = 0;
758 }
759 else if (NSUIntegerTypedefed) {
760 TypedefDcl = NSUIntegerTypedefed;
761 NSUIntegerTypedefed = 0;
762 }
763 else
764 return false;
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +0000765 FileID FileIdOfTypedefDcl =
766 PP.getSourceManager().getFileID(TypedefDcl->getLocation());
767 FileID FileIdOfEnumDcl =
768 PP.getSourceManager().getFileID(EnumDcl->getLocation());
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000769 if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
770 return false;
771 }
772 if (TypedefDcl->isDeprecated())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000773 return false;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000774
775 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000776 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt);
777 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000778
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000779 if (!IsNSIntegerType && !IsNSUIntegerType) {
780 // Also check for typedef enum {...} TD;
781 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
782 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000783 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000784 if (NSOptions) {
785 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000786 return false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000787 }
788 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000789 return false;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000790 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000791 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000792 Editor->commit(commit);
Fariborz Jahaniande79e812013-10-17 22:23:32 +0000793 return true;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000794 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000795 }
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000796 return false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000797 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000798
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000799 // We may still use NS_OPTIONS based on what we find in the enumertor list.
800 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000801 // NS_ENUM must be available.
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000802 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000803 return false;
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000804 // NS_OPTIONS must be available.
805 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000806 return false;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000807 edit::Commit commit(*Editor);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000808 bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
809 commit, IsNSIntegerType, NSOptions);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000810 Editor->commit(commit);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000811 return Res;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000812}
813
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000814static void ReplaceWithInstancetype(const ObjCMigrateASTConsumer &ASTC,
815 ObjCMethodDecl *OM) {
816 SourceRange R;
817 std::string ClassString;
818 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
819 TypeLoc TL = TSInfo->getTypeLoc();
820 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
821 ClassString = "instancetype";
822 }
823 else {
824 R = SourceRange(OM->getLocStart(), OM->getLocStart());
825 ClassString = OM->isInstanceMethod() ? '-' : '+';
826 ClassString += " (instancetype)";
827 }
828 edit::Commit commit(*ASTC.Editor);
829 commit.replace(R, ClassString);
830 ASTC.Editor->commit(commit);
831}
832
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000833static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
834 ObjCMethodDecl *OM) {
835 ObjCInterfaceDecl *IDecl = OM->getClassInterface();
836 SourceRange R;
837 std::string ClassString;
838 if (TypeSourceInfo *TSInfo = OM->getResultTypeSourceInfo()) {
839 TypeLoc TL = TSInfo->getTypeLoc();
840 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
841 ClassString = IDecl->getName();
842 ClassString += "*";
843 }
844 }
845 else {
846 R = SourceRange(OM->getLocStart(), OM->getLocStart());
847 ClassString = "+ (";
848 ClassString += IDecl->getName(); ClassString += "*)";
849 }
850 edit::Commit commit(*ASTC.Editor);
851 commit.replace(R, ClassString);
852 ASTC.Editor->commit(commit);
853}
854
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000855void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
856 ObjCContainerDecl *CDecl,
857 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +0000858 ObjCInstanceTypeFamily OIT_Family =
859 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000860
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000861 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000862 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000863 case OIT_None:
864 migrateFactoryMethod(Ctx, CDecl, OM);
865 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +0000866 case OIT_Array:
867 ClassName = "NSArray";
868 break;
869 case OIT_Dictionary:
870 ClassName = "NSDictionary";
871 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000872 case OIT_Singleton:
873 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000874 return;
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +0000875 case OIT_Init:
876 if (OM->getResultType()->isObjCIdType())
877 ReplaceWithInstancetype(*this, OM);
878 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000879 case OIT_ReturnsSelf:
880 migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
881 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000882 }
Fariborz Jahanian71221352013-07-23 22:42:28 +0000883 if (!OM->getResultType()->isObjCIdType())
884 return;
885
886 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
887 if (!IDecl) {
888 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
889 IDecl = CatDecl->getClassInterface();
890 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
891 IDecl = ImpDecl->getClassInterface();
892 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000893 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000894 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
895 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000896 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +0000897 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000898 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +0000899}
900
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000901static bool TypeIsInnerPointer(QualType T) {
902 if (!T->isAnyPointerType())
903 return false;
904 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
Fariborz Jahanian73466ca2013-09-26 21:43:47 +0000905 T->isBlockPointerType() || T->isFunctionPointerType() ||
906 ento::coreFoundation::isCFObjectRef(T))
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000907 return false;
Fariborz Jahanian9d5fffb2013-09-09 23:56:14 +0000908 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
909 // is not an innter pointer type.
910 QualType OrigT = T;
911 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
912 T = TD->getDecl()->getUnderlyingType();
913 if (OrigT == T || !T->isPointerType())
914 return true;
915 const PointerType* PT = T->getAs<PointerType>();
916 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
917 if (UPointeeT->isRecordType()) {
918 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
919 if (!RecordTy->getDecl()->isCompleteDefinition())
920 return false;
921 }
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +0000922 return true;
923}
924
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000925/// \brief Check whether the two versions match.
926static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) {
927 return (X == Y);
928}
929
930/// AvailabilityAttrsMatch - This routine checks that if comparing two
931/// availability attributes, all their components match. It returns
932/// true, if not dealing with availability or when all components of
933/// availability attributes match. This routine is only called when
934/// the attributes are of the same kind.
935static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) {
936 const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1);
937 if (!AA1)
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000938 return true;
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000939 const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2);
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000940
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000941 VersionTuple Introduced1 = AA1->getIntroduced();
942 VersionTuple Deprecated1 = AA1->getDeprecated();
943 VersionTuple Obsoleted1 = AA1->getObsoleted();
944 bool IsUnavailable1 = AA1->getUnavailable();
945 VersionTuple Introduced2 = AA2->getIntroduced();
946 VersionTuple Deprecated2 = AA2->getDeprecated();
947 VersionTuple Obsoleted2 = AA2->getObsoleted();
948 bool IsUnavailable2 = AA2->getUnavailable();
949 return (versionsMatch(Introduced1, Introduced2) &&
950 versionsMatch(Deprecated1, Deprecated2) &&
951 versionsMatch(Obsoleted1, Obsoleted2) &&
952 IsUnavailable1 == IsUnavailable2);
953
954}
955
956static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2,
957 bool &AvailabilityArgsMatch) {
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000958 // This list is very small, so this need not be optimized.
959 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
960 bool match = false;
961 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000962 // Matching attribute kind only. Except for Availabilty attributes,
963 // we are not getting into details of the attributes. For all practical purposes
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000964 // this is sufficient.
965 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000966 if (AvailabilityArgsMatch)
967 AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]);
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +0000968 match = true;
969 break;
970 }
971 }
972 if (!match)
973 return false;
974 }
975 return true;
976}
977
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000978/// AttributesMatch - This routine checks list of attributes for two
979/// decls. It returns false, if there is a mismatch in kind of
980/// attributes seen in the decls. It returns true if the two decls
981/// have list of same kind of attributes. Furthermore, when there
982/// are availability attributes in the two decls, it sets the
983/// AvailabilityArgsMatch to false if availability attributes have
984/// different versions, etc.
985static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2,
986 bool &AvailabilityArgsMatch) {
987 if (!Decl1->hasAttrs() || !Decl2->hasAttrs()) {
988 AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs());
989 return true;
990 }
991 AvailabilityArgsMatch = true;
992 const AttrVec &Attrs1 = Decl1->getAttrs();
993 const AttrVec &Attrs2 = Decl2->getAttrs();
994 bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch);
995 if (match && (Attrs2.size() > Attrs1.size()))
996 return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch);
997 return match;
998}
999
Fariborz Jahanian5d783df2013-09-27 22:55:54 +00001000static bool IsValidIdentifier(ASTContext &Ctx,
1001 const char *Name) {
1002 if (!isIdentifierHead(Name[0]))
1003 return false;
1004 std::string NameString = Name;
1005 NameString[0] = toLowercase(NameString[0]);
1006 IdentifierInfo *II = &Ctx.Idents.get(NameString);
1007 return II->getTokenID() == tok::identifier;
1008}
1009
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001010bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001011 ObjCContainerDecl *D,
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001012 ObjCMethodDecl *Method) {
1013 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
1014 Method->param_size() != 0)
1015 return false;
1016 // Is this method candidate to be a getter?
1017 QualType GRT = Method->getResultType();
1018 if (GRT->isVoidType())
1019 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001020
1021 Selector GetterSelector = Method->getSelector();
Fariborz Jahanian7391a7b5a2013-09-25 00:17:07 +00001022 ObjCInstanceTypeFamily OIT_Family =
1023 Selector::getInstTypeMethodFamily(GetterSelector);
1024
1025 if (OIT_Family != OIT_None)
1026 return false;
1027
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001028 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
1029 Selector SetterSelector =
1030 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1031 PP.getSelectorTable(),
1032 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001033 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanianca399602013-09-11 17:05:15 +00001034 unsigned LengthOfPrefix = 0;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001035 if (!SetterMethod) {
1036 // try a different naming convention for getter: isXxxxx
1037 StringRef getterNameString = getterName->getName();
Fariborz Jahanianca399602013-09-11 17:05:15 +00001038 bool IsPrefix = getterNameString.startswith("is");
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +00001039 // Note that we don't want to change an isXXX method of retainable object
1040 // type to property (readonly or otherwise).
1041 if (IsPrefix && GRT->isObjCRetainableType())
1042 return false;
1043 if (IsPrefix || getterNameString.startswith("get")) {
Fariborz Jahanianca399602013-09-11 17:05:15 +00001044 LengthOfPrefix = (IsPrefix ? 2 : 3);
1045 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
1046 // Make sure that first character after "is" or "get" prefix can
1047 // start an identifier.
Fariborz Jahanian5d783df2013-09-27 22:55:54 +00001048 if (!IsValidIdentifier(Ctx, CGetterName))
Fariborz Jahanianca399602013-09-11 17:05:15 +00001049 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001050 if (CGetterName[0] && isUppercase(CGetterName[0])) {
1051 getterName = &Ctx.Idents.get(CGetterName);
1052 SetterSelector =
1053 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1054 PP.getSelectorTable(),
1055 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001056 SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001057 }
1058 }
1059 }
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +00001060
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001061 if (SetterMethod) {
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001062 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
1063 return false;
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001064 bool AvailabilityArgsMatch;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001065 if (SetterMethod->isDeprecated() ||
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001066 !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch))
Fariborz Jahanianf6c65052013-09-17 22:41:25 +00001067 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001068
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001069 // Is this a valid setter, matching the target getter?
1070 QualType SRT = SetterMethod->getResultType();
1071 if (!SRT->isVoidType())
1072 return false;
1073 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
1074 QualType ArgType = argDecl->getType();
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001075 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001076 return false;
1077 edit::Commit commit(*Editor);
1078 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001079 LengthOfPrefix,
1080 (ASTMigrateActions &
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001081 FrontendOptions::ObjCMT_AtomicProperty) != 0,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001082 (ASTMigrateActions &
1083 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001084 AvailabilityArgsMatch);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001085 Editor->commit(commit);
1086 return true;
1087 }
Fariborz Jahanian182486c2013-10-02 17:08:12 +00001088 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001089 // Try a non-void method with no argument (and no setter or property of same name
1090 // as a 'readonly' property.
1091 edit::Commit commit(*Editor);
1092 rewriteToObjCProperty(Method, 0 /*SetterMethod*/, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001093 LengthOfPrefix,
1094 (ASTMigrateActions &
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001095 FrontendOptions::ObjCMT_AtomicProperty) != 0,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001096 (ASTMigrateActions &
1097 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001098 /*AvailabilityArgsMatch*/false);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001099 Editor->commit(commit);
1100 return true;
1101 }
1102 return false;
1103}
1104
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001105void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
1106 ObjCMethodDecl *OM) {
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001107 if (OM->isImplicit() ||
Fariborz Jahanian7c1a4452013-09-26 22:43:41 +00001108 !OM->isInstanceMethod() ||
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001109 OM->hasAttr<ObjCReturnsInnerPointerAttr>())
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001110 return;
1111
1112 QualType RT = OM->getResultType();
1113 if (!TypeIsInnerPointer(RT) ||
1114 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
1115 return;
1116
1117 edit::Commit commit(*Editor);
1118 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
1119 Editor->commit(commit);
1120}
1121
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001122void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
1123 ObjCPropertyDecl *P) {
1124 QualType T = P->getType();
1125
1126 if (!TypeIsInnerPointer(T) ||
1127 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
1128 return;
1129 edit::Commit commit(*Editor);
1130 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
1131 Editor->commit(commit);
1132}
1133
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001134void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
Fariborz Jahanian71221352013-07-23 22:42:28 +00001135 ObjCContainerDecl *CDecl) {
Fariborz Jahaniane47a14a2013-09-18 15:43:52 +00001136 if (CDecl->isDeprecated())
1137 return;
1138
Fariborz Jahanian71221352013-07-23 22:42:28 +00001139 // migrate methods which can have instancetype as their result type.
1140 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1141 MEnd = CDecl->meth_end();
1142 M != MEnd; ++M) {
1143 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001144 if (Method->isDeprecated())
1145 continue;
Fariborz Jahanian71221352013-07-23 22:42:28 +00001146 migrateMethodInstanceType(Ctx, CDecl, Method);
1147 }
1148}
1149
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001150void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
1151 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001152 ObjCMethodDecl *OM,
1153 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +00001154 if (OM->isInstanceMethod() ||
1155 OM->getResultType() == Ctx.getObjCInstanceType() ||
1156 !OM->getResultType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001157 return;
1158
1159 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1160 // NSYYYNamE with matching names be at least 3 characters long.
1161 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1162 if (!IDecl) {
1163 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1164 IDecl = CatDecl->getClassInterface();
1165 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1166 IDecl = ImpDecl->getClassInterface();
1167 }
1168 if (!IDecl)
1169 return;
1170
1171 std::string StringClassName = IDecl->getName();
1172 StringRef LoweredClassName(StringClassName);
1173 std::string StringLoweredClassName = LoweredClassName.lower();
1174 LoweredClassName = StringLoweredClassName;
1175
1176 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001177 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1178 if (!MethodIdName)
1179 return;
1180
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001181 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001182 if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001183 StringRef STRefMethodName(MethodName);
1184 size_t len = 0;
1185 if (STRefMethodName.startswith("standard"))
1186 len = strlen("standard");
1187 else if (STRefMethodName.startswith("shared"))
1188 len = strlen("shared");
1189 else if (STRefMethodName.startswith("default"))
1190 len = strlen("default");
1191 else
1192 return;
1193 MethodName = STRefMethodName.substr(len);
1194 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001195 std::string MethodNameSubStr = MethodName.substr(0, 3);
1196 StringRef MethodNamePrefix(MethodNameSubStr);
1197 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1198 MethodNamePrefix = StringLoweredMethodNamePrefix;
1199 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1200 if (Ix == StringRef::npos)
1201 return;
1202 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1203 StringRef LoweredMethodName(MethodName);
1204 std::string StringLoweredMethodName = LoweredMethodName.lower();
1205 LoweredMethodName = StringLoweredMethodName;
1206 if (!LoweredMethodName.startswith(ClassNamePostfix))
1207 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001208 if (OIT_Family == OIT_ReturnsSelf)
1209 ReplaceWithClasstype(*this, OM);
1210 else
1211 ReplaceWithInstancetype(*this, OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001212}
1213
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001214static bool IsVoidStarType(QualType Ty) {
1215 if (!Ty->isPointerType())
1216 return false;
1217
1218 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1219 Ty = TD->getDecl()->getUnderlyingType();
1220
1221 // Is the type void*?
1222 const PointerType* PT = Ty->getAs<PointerType>();
1223 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1224 return true;
1225 return IsVoidStarType(PT->getPointeeType());
1226}
1227
Fariborz Jahanian94279392013-08-20 18:54:39 +00001228/// AuditedType - This routine audits the type AT and returns false if it is one of known
1229/// CF object types or of the "void *" variety. It returns true if we don't care about the type
1230/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001231static bool AuditedType (QualType AT) {
1232 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001233 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001234 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +00001235 if (ento::coreFoundation::isCFObjectRef(AT) ||
1236 IsVoidStarType(AT) ||
1237 // If an ObjC object is type, assuming that it is not a CF function and
1238 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +00001239 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001240 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +00001241 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001242 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001243}
1244
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001245void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001246 if (CFFunctionIBCandidates.empty())
1247 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001248 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
1249 CFFunctionIBCandidates.clear();
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001250 FileId = FileID();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001251 return;
1252 }
1253 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001254 const Decl *FirstFD = CFFunctionIBCandidates[0];
1255 const Decl *LastFD =
1256 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001257 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1258 edit::Commit commit(*Editor);
1259 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
1260 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1261 SourceLocation EndLoc = LastFD->getLocEnd();
1262 // get location just past end of function location.
1263 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001264 if (isa<FunctionDecl>(LastFD)) {
1265 // For Methods, EndLoc points to the ending semcolon. So,
1266 // not of these extra work is needed.
1267 Token Tok;
1268 // get locaiton of token that comes after end of function.
1269 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1270 if (!Failed)
1271 EndLoc = Tok.getLocation();
1272 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001273 commit.insertAfterToken(EndLoc, PragmaString);
1274 Editor->commit(commit);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001275 FileId = FileID();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001276 CFFunctionIBCandidates.clear();
1277}
1278
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001279void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001280 if (Decl->isDeprecated())
1281 return;
1282
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001283 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001284 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001285 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001286 "provided CF_IMPLICIT_BRIDGING_ENABLE");
1287 return;
1288 }
1289
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001290 // Finction must be annotated first.
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001291 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1292 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1293 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001294 CFFunctionIBCandidates.push_back(Decl);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001295 if (FileId.isInvalid())
1296 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001297 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001298 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1299 if (!CFFunctionIBCandidates.empty()) {
1300 CFFunctionIBCandidates.push_back(Decl);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001301 if (FileId.isInvalid())
1302 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001303 }
1304 }
1305 else
1306 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001307 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001308 else {
1309 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001310 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001311 }
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001312}
1313
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001314void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1315 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001316 const FunctionDecl *FuncDecl,
1317 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001318 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001319 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001320 RetEffect Ret = CE.getReturnValue();
1321 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001322 if (Ret.getObjKind() == RetEffect::CF) {
1323 if (Ret.isOwned() &&
1324 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001325 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001326 else if (Ret.notOwned() &&
1327 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001328 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1329 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001330 else if (Ret.getObjKind() == RetEffect::ObjC) {
1331 if (Ret.isOwned() &&
1332 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1333 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001334 }
1335
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001336 if (AnnotationString) {
1337 edit::Commit commit(*Editor);
1338 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1339 Editor->commit(commit);
1340 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001341 }
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001342 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1343 unsigned i = 0;
1344 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1345 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +00001346 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001347 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001348 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1349 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1350 edit::Commit commit(*Editor);
1351 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1352 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +00001353 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001354 else if (AE == DecRefMsg && !pd->getAttr<NSConsumedAttr>() &&
1355 Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
1356 edit::Commit commit(*Editor);
1357 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1358 Editor->commit(commit);
1359 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001360 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001361}
1362
1363
1364ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1365 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1366 ASTContext &Ctx,
1367 const FunctionDecl *FuncDecl) {
1368 if (FuncDecl->hasBody())
1369 return CF_BRIDGING_NONE;
1370
1371 CallEffects CE = CallEffects::getEffect(FuncDecl);
1372 bool FuncIsReturnAnnotated = (FuncDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001373 FuncDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1374 FuncDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001375 FuncDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1376 FuncDecl->getAttr<NSReturnsAutoreleasedAttr>());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001377
1378 // Trivial case of when funciton is annotated and has no argument.
1379 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1380 return CF_BRIDGING_NONE;
1381
1382 bool ReturnCFAudited = false;
1383 if (!FuncIsReturnAnnotated) {
1384 RetEffect Ret = CE.getReturnValue();
1385 if (Ret.getObjKind() == RetEffect::CF &&
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001386 (Ret.isOwned() || Ret.notOwned()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001387 ReturnCFAudited = true;
1388 else if (!AuditedType(FuncDecl->getResultType()))
1389 return CF_BRIDGING_NONE;
1390 }
1391
1392 // At this point result type is audited for potential inclusion.
1393 // Now, how about argument types.
1394 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1395 unsigned i = 0;
1396 bool ArgCFAudited = false;
1397 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1398 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1399 const ParmVarDecl *pd = *pi;
1400 ArgEffect AE = AEArgs[i];
1401 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1402 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>())
1403 ArgCFAudited = true;
1404 else if (AE == IncRef)
1405 ArgCFAudited = true;
1406 }
1407 else {
1408 QualType AT = pd->getType();
1409 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001410 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001411 return CF_BRIDGING_NONE;
1412 }
1413 }
1414 }
1415 if (ReturnCFAudited || ArgCFAudited)
1416 return CF_BRIDGING_ENABLE;
1417
1418 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001419}
1420
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001421void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1422 ObjCContainerDecl *CDecl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001423 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001424 return;
1425
1426 // migrate methods which can have instancetype as their result type.
1427 for (ObjCContainerDecl::method_iterator M = CDecl->meth_begin(),
1428 MEnd = CDecl->meth_end();
1429 M != MEnd; ++M) {
1430 ObjCMethodDecl *Method = (*M);
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001431 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001432 }
1433}
1434
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001435void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1436 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001437 const ObjCMethodDecl *MethodDecl,
1438 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001439 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001440 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001441 RetEffect Ret = CE.getReturnValue();
1442 const char *AnnotationString = 0;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001443 if (Ret.getObjKind() == RetEffect::CF) {
1444 if (Ret.isOwned() &&
1445 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001446 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001447 else if (Ret.notOwned() &&
1448 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001449 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1450 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001451 else if (Ret.getObjKind() == RetEffect::ObjC) {
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001452 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1453 switch (OMF) {
1454 case clang::OMF_alloc:
1455 case clang::OMF_new:
1456 case clang::OMF_copy:
1457 case clang::OMF_init:
1458 case clang::OMF_mutableCopy:
1459 break;
1460
1461 default:
1462 if (Ret.isOwned() &&
1463 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1464 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001465 break;
1466 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001467 }
1468
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001469 if (AnnotationString) {
1470 edit::Commit commit(*Editor);
1471 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1472 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001473 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001474 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001475 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1476 unsigned i = 0;
1477 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1478 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1479 const ParmVarDecl *pd = *pi;
1480 ArgEffect AE = AEArgs[i];
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001481 if (AE == DecRef && !pd->getAttr<CFConsumedAttr>() &&
1482 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1483 edit::Commit commit(*Editor);
1484 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1485 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001486 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001487 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001488}
1489
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001490void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001491 ASTContext &Ctx,
1492 const ObjCMethodDecl *MethodDecl) {
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001493 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001494 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001495
1496 CallEffects CE = CallEffects::getEffect(MethodDecl);
1497 bool MethodIsReturnAnnotated = (MethodDecl->getAttr<CFReturnsRetainedAttr>() ||
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001498 MethodDecl->getAttr<CFReturnsNotRetainedAttr>() ||
1499 MethodDecl->getAttr<NSReturnsRetainedAttr>() ||
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001500 MethodDecl->getAttr<NSReturnsNotRetainedAttr>() ||
1501 MethodDecl->getAttr<NSReturnsAutoreleasedAttr>());
1502
1503 if (CE.getReceiver() == DecRefMsg &&
1504 !MethodDecl->getAttr<NSConsumesSelfAttr>() &&
1505 MethodDecl->getMethodFamily() != OMF_init &&
1506 MethodDecl->getMethodFamily() != OMF_release &&
1507 Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
1508 edit::Commit commit(*Editor);
1509 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1510 Editor->commit(commit);
1511 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001512
1513 // Trivial case of when funciton is annotated and has no argument.
1514 if (MethodIsReturnAnnotated &&
1515 (MethodDecl->param_begin() == MethodDecl->param_end()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001516 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001517
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001518 if (!MethodIsReturnAnnotated) {
1519 RetEffect Ret = CE.getReturnValue();
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001520 if ((Ret.getObjKind() == RetEffect::CF ||
1521 Ret.getObjKind() == RetEffect::ObjC) &&
1522 (Ret.isOwned() || Ret.notOwned())) {
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001523 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1524 return;
1525 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001526 else if (!AuditedType(MethodDecl->getResultType()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001527 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001528 }
1529
1530 // At this point result type is either annotated or audited.
1531 // Now, how about argument types.
1532 llvm::ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1533 unsigned i = 0;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001534 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1535 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1536 const ParmVarDecl *pd = *pi;
1537 ArgEffect AE = AEArgs[i];
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001538 if ((AE == DecRef && !pd->getAttr<CFConsumedAttr>()) || AE == IncRef ||
1539 !AuditedType(pd->getType())) {
1540 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1541 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001542 }
1543 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001544 return;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001545}
1546
Ted Kremenekf7639e12012-03-06 20:06:33 +00001547namespace {
1548
1549class RewritesReceiver : public edit::EditsReceiver {
1550 Rewriter &Rewrite;
1551
1552public:
1553 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1554
1555 virtual void insert(SourceLocation loc, StringRef text) {
1556 Rewrite.InsertText(loc, text);
1557 }
1558 virtual void replace(CharSourceRange range, StringRef text) {
1559 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1560 }
1561};
1562
1563}
1564
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001565static bool
1566IsReallyASystemHeader(ASTContext &Ctx, const FileEntry *file, FileID FID) {
1567 bool Invalid = false;
1568 const SrcMgr::SLocEntry &SEntry =
1569 Ctx.getSourceManager().getSLocEntry(FID, &Invalid);
1570 if (!Invalid && SEntry.isFile()) {
1571 const SrcMgr::FileInfo &FI = SEntry.getFile();
1572 if (!FI.hasLineDirectives()) {
1573 if (FI.getFileCharacteristic() == SrcMgr::C_ExternCSystem)
1574 return true;
1575 if (FI.getFileCharacteristic() == SrcMgr::C_System) {
1576 // This file is in a system header directory. Continue with commiting change
1577 // only if it is a user specified system directory because user put a
1578 // .system_framework file in the framework directory.
1579 StringRef Directory(file->getDir()->getName());
1580 size_t Ix = Directory.rfind(".framework");
1581 if (Ix == StringRef::npos)
1582 return true;
1583 std::string PatchToSystemFramework = Directory.slice(0, Ix+sizeof(".framework"));
1584 PatchToSystemFramework += ".system_framework";
1585 if (!llvm::sys::fs::exists(PatchToSystemFramework.data()))
1586 return true;
1587 }
1588 }
1589 }
1590 return false;
1591}
1592
Ted Kremenekf7639e12012-03-06 20:06:33 +00001593void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001594
1595 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001596 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001597 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1598 D != DEnd; ++D) {
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001599 FileID FID = PP.getSourceManager().getFileID((*D)->getLocation());
1600 if (!FID.isInvalid())
1601 if (!FileId.isInvalid() && FileId != FID) {
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001602 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1603 AnnotateImplicitBridging(Ctx);
1604 }
1605
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001606 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1607 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001608 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) {
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001609 migrateObjCInterfaceDecl(Ctx, CatDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001610 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
Fariborz Jahaniand41dbad2013-10-31 16:10:44 +00001611 migrateDeprecatedAnnotation(Ctx, CatDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001612 }
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001613 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
1614 ObjCProtocolDecls.insert(PDecl);
1615 else if (const ObjCImplementationDecl *ImpDecl =
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001616 dyn_cast<ObjCImplementationDecl>(*D)) {
1617 if (ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance)
1618 migrateProtocolConformance(Ctx, ImpDecl);
1619 }
Fariborz Jahanian92463272013-07-18 20:11:45 +00001620 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001621 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1622 continue;
Fariborz Jahanian92463272013-07-18 20:11:45 +00001623 DeclContext::decl_iterator N = D;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001624 if (++N != DEnd) {
1625 const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
1626 if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
1627 D++;
1628 }
1629 else
1630 migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */0);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001631 }
1632 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001633 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1634 continue;
1635 DeclContext::decl_iterator N = D;
1636 if (++N == DEnd)
1637 continue;
1638 if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001639 if (++N != DEnd)
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001640 if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) {
1641 // prefer typedef-follows-enum to enum-follows-typedef pattern.
1642 if (migrateNSEnumDecl(Ctx, ED, TDF)) {
1643 ++D; ++D;
1644 CacheObjCNSIntegerTypedefed(TD);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001645 continue;
1646 }
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001647 }
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001648 if (migrateNSEnumDecl(Ctx, ED, TD)) {
1649 ++D;
1650 continue;
1651 }
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001652 }
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001653 CacheObjCNSIntegerTypedefed(TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001654 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001655 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
1656 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1657 migrateCFAnnotation(Ctx, FD);
1658 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001659
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001660 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1661 // migrate methods which can have instancetype as their result type.
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001662 if (ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype)
1663 migrateAllMethodInstaceType(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001664 // annotate methods with CF annotations.
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001665 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1666 migrateARCSafeAnnotation(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001667 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001668 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001669 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1670 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001671 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001672
David Blaikiebbafb8a2012-03-11 07:00:24 +00001673 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001674 RewritesReceiver Rec(rewriter);
1675 Editor->applyRewrites(Rec);
1676
1677 for (Rewriter::buffer_iterator
1678 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1679 FileID FID = I->first;
1680 RewriteBuffer &buf = I->second;
1681 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1682 assert(file);
Fariborz Jahanian8f5225b2013-10-01 21:16:29 +00001683 if (IsReallyASystemHeader(Ctx, file, FID))
1684 continue;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001685 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001686 llvm::raw_svector_ostream vecOS(newText);
1687 buf.write(vecOS);
1688 vecOS.flush();
1689 llvm::MemoryBuffer *memBuf = llvm::MemoryBuffer::getMemBufferCopy(
1690 StringRef(newText.data(), newText.size()), file->getName());
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001691 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001692 FileMgr.FixupRelativePath(filePath);
1693 Remapper.remap(filePath.str(), memBuf);
1694 }
1695
1696 if (IsOutputFile) {
1697 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1698 } else {
1699 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1700 }
1701}
1702
1703bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001704 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001705 return true;
1706}
1707
1708ASTConsumer *MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI,
1709 StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001710 PPConditionalDirectiveRecord *
1711 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
1712 CI.getPreprocessor().addPPCallbacks(PPRec);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001713 return new ObjCMigrateASTConsumer(CI.getFrontendOpts().OutputFile,
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001714 FrontendOptions::ObjCMT_MigrateAll,
Ted Kremenekf7639e12012-03-06 20:06:33 +00001715 Remapper,
1716 CI.getFileManager(),
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001717 PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001718 CI.getPreprocessor(),
Ted Kremenekf7639e12012-03-06 20:06:33 +00001719 /*isOutputFile=*/true);
1720}