blob: 7eebdb78d8982acd2538f4981f314682834ecd42 [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"
Hans Wennborgbf6dda52013-12-12 02:24:20 +000011#include "clang/ARCMigrate/ARCMT.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000012#include "clang/ARCMigrate/ARCMTActions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000013#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000015#include "clang/AST/Attr.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/NSAPI.h"
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +000017#include "clang/AST/ParentMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000019#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Basic/FileManager.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/EditedSource.h"
23#include "clang/Edit/EditsReceiver.h"
24#include "clang/Edit/Rewriters.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000025#include "clang/Frontend/CompilerInstance.h"
26#include "clang/Frontend/MultiplexConsumer.h"
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +000027#include "clang/Lex/PPConditionalDirectiveRecord.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Lex/Preprocessor.h"
29#include "clang/Rewrite/Core/Rewriter.h"
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000030#include "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000031#include "llvm/ADT/SmallString.h"
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +000032#include "llvm/Support/Path.h"
Hans Wennborgbf6dda52013-12-12 02:24:20 +000033#include "llvm/Support/SourceMgr.h"
34#include "llvm/Support/YAMLParser.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000035
36using namespace clang;
37using namespace arcmt;
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +000038using namespace ento::objc_retain;
Ted Kremenekf7639e12012-03-06 20:06:33 +000039
40namespace {
41
42class ObjCMigrateASTConsumer : public ASTConsumer {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000043 enum CF_BRIDGING_KIND {
44 CF_BRIDGING_NONE,
45 CF_BRIDGING_ENABLE,
46 CF_BRIDGING_MAY_INCLUDE
47 };
48
Ted Kremenekf7639e12012-03-06 20:06:33 +000049 void migrateDecl(Decl *D);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000050 void migrateObjCInterfaceDecl(ASTContext &Ctx, ObjCContainerDecl *D);
Fariborz Jahanian1be01532013-07-12 22:32:19 +000051 void migrateProtocolConformance(ASTContext &Ctx,
52 const ObjCImplementationDecl *ImpDecl);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +000053 void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +000054 bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
Fariborz Jahanian92463272013-07-18 20:11:45 +000055 const TypedefDecl *TypedefDcl);
Fariborz Jahanian8c45e282013-10-02 22:49:59 +000056 void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
Fariborz Jahanian670ef262013-07-23 23:34:42 +000057 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
58 ObjCMethodDecl *OM);
Fariborz Jahanian92f72422013-09-17 19:00:30 +000059 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +000060 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
Fariborz Jahanian10b74352013-09-24 20:20:52 +000061 void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
Fariborz Jahanianc4291852013-08-02 18:00:53 +000062 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +000063 ObjCMethodDecl *OM,
64 ObjCInstanceTypeFamily OIT_Family = OIT_None);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000065
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +000066 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000067 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000068 const FunctionDecl *FuncDecl, bool ResultAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000069 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +000070 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +000071
Fariborz Jahanian301b5212013-08-20 22:42:13 +000072 void AnnotateImplicitBridging(ASTContext &Ctx);
73
Fariborz Jahanian63ffce22013-08-27 22:42:30 +000074 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
75 const FunctionDecl *FuncDecl);
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +000076
Fariborz Jahanian926fafb2013-08-22 18:35:27 +000077 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
78
Fariborz Jahanian89f6d102013-09-04 00:10:06 +000079 void migrateAddMethodAnnotation(ASTContext &Ctx,
80 const ObjCMethodDecl *MethodDecl);
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +000081
82 void inferDesignatedInitializers(ASTContext &Ctx,
83 const ObjCImplementationDecl *ImplD);
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +000084
85 bool InsertFoundation(ASTContext &Ctx, SourceLocation Loc);
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +000086
Ted Kremenekf7639e12012-03-06 20:06:33 +000087public:
88 std::string MigrateDir;
Fariborz Jahanian182486c2013-10-02 17:08:12 +000089 unsigned ASTMigrateActions;
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +000090 FileID FileId;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +000091 const TypedefDecl *NSIntegerTypedefed;
92 const TypedefDecl *NSUIntegerTypedefed;
Ahmed Charlesb8984322014-03-07 20:03:18 +000093 std::unique_ptr<NSAPI> NSAPIObj;
94 std::unique_ptr<edit::EditedSource> Editor;
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;
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +0000100 bool FoundationIncluded;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000101 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
Fariborz Jahanian926fafb2013-08-22 18:35:27 +0000102 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000103 llvm::StringMap<char> WhiteListFilenames;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000104
Ted Kremenekf7639e12012-03-06 20:06:33 +0000105 ObjCMigrateASTConsumer(StringRef migrateDir,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000106 unsigned astMigrateActions,
Ted Kremenekf7639e12012-03-06 20:06:33 +0000107 FileRemapper &remapper,
108 FileManager &fileMgr,
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000109 const PPConditionalDirectiveRecord *PPRec,
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000110 Preprocessor &PP,
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000111 bool isOutputFile,
112 ArrayRef<std::string> WhiteList)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000113 : MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000114 ASTMigrateActions(astMigrateActions),
Craig Topper8ae12032014-05-07 06:21:57 +0000115 NSIntegerTypedefed(nullptr), NSUIntegerTypedefed(nullptr),
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000116 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +0000117 IsOutputFile(isOutputFile),
118 FoundationIncluded(false){
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000119
120 for (ArrayRef<std::string>::iterator
121 I = WhiteList.begin(), E = WhiteList.end(); I != E; ++I) {
122 WhiteListFilenames.GetOrCreateValue(*I);
123 }
124 }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000125
126protected:
Craig Topperb45acb82014-03-14 06:02:07 +0000127 void Initialize(ASTContext &Context) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000128 NSAPIObj.reset(new NSAPI(Context));
129 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000130 Context.getLangOpts(),
Argyrios Kyrtzidis7dd31332014-04-28 02:38:51 +0000131 PPRec));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000132 }
133
Craig Topperb45acb82014-03-14 06:02:07 +0000134 bool HandleTopLevelDecl(DeclGroupRef DG) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000135 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
136 migrateDecl(*I);
137 return true;
138 }
Craig Topperb45acb82014-03-14 06:02:07 +0000139 void HandleInterestingDecl(DeclGroupRef DG) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000140 // Ignore decls from the PCH.
141 }
Craig Topperb45acb82014-03-14 06:02:07 +0000142 void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000143 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
144 }
145
Craig Topperb45acb82014-03-14 06:02:07 +0000146 void HandleTranslationUnit(ASTContext &Ctx) override;
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +0000147
148 bool canModifyFile(StringRef Path) {
149 if (WhiteListFilenames.empty())
150 return true;
151 return WhiteListFilenames.find(llvm::sys::path::filename(Path))
152 != WhiteListFilenames.end();
153 }
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +0000154 bool canModifyFile(const FileEntry *FE) {
155 if (!FE)
156 return false;
157 return canModifyFile(FE->getName());
158 }
159 bool canModifyFile(FileID FID) {
160 if (FID.isInvalid())
161 return false;
162 return canModifyFile(PP.getSourceManager().getFileEntryForID(FID));
163 }
164
165 bool canModify(const Decl *D) {
166 if (!D)
167 return false;
168 if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(D))
169 return canModify(CatImpl->getCategoryDecl());
170 if (const ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D))
171 return canModify(Impl->getClassInterface());
172 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
173 return canModify(cast<Decl>(MD->getDeclContext()));
174
175 FileID FID = PP.getSourceManager().getFileID(D->getLocation());
176 return canModifyFile(FID);
177 }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000178};
179
180}
181
182ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000183 StringRef migrateDir,
184 unsigned migrateAction)
Ted Kremenekf7639e12012-03-06 20:06:33 +0000185 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000186 ObjCMigAction(migrateAction),
Craig Topper8ae12032014-05-07 06:21:57 +0000187 CompInst(nullptr) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000188 if (MigrateDir.empty())
189 MigrateDir = "."; // user current directory if none is given.
190}
191
David Blaikie6beb6aa2014-08-10 19:56:51 +0000192std::unique_ptr<ASTConsumer>
193ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000194 PPConditionalDirectiveRecord *
195 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +0000196 CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000197 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
198 Consumers.push_back(WrapperFrontendAction::CreateASTConsumer(CI, InFile));
199 Consumers.push_back(llvm::make_unique<ObjCMigrateASTConsumer>(
200 MigrateDir, ObjCMigAction, Remapper, CompInst->getFileManager(), PPRec,
Craig Topper5fc8fc22014-08-27 06:28:36 +0000201 CompInst->getPreprocessor(), false, None));
David Blaikie6beb6aa2014-08-10 19:56:51 +0000202 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Ted Kremenekf7639e12012-03-06 20:06:33 +0000203}
204
205bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
206 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
207 /*ignoreIfFilesChanges=*/true);
208 CompInst = &CI;
209 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000210 return true;
211}
212
213namespace {
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000214 // FIXME. This duplicates one in RewriteObjCFoundationAPI.cpp
215 bool subscriptOperatorNeedsParens(const Expr *FullExpr) {
216 const Expr* Expr = FullExpr->IgnoreImpCasts();
217 if (isa<ArraySubscriptExpr>(Expr) ||
218 isa<CallExpr>(Expr) ||
219 isa<DeclRefExpr>(Expr) ||
220 isa<CXXNamedCastExpr>(Expr) ||
221 isa<CXXConstructExpr>(Expr) ||
222 isa<CXXThisExpr>(Expr) ||
223 isa<CXXTypeidExpr>(Expr) ||
224 isa<CXXUnresolvedConstructExpr>(Expr) ||
225 isa<ObjCMessageExpr>(Expr) ||
226 isa<ObjCPropertyRefExpr>(Expr) ||
227 isa<ObjCProtocolExpr>(Expr) ||
228 isa<MemberExpr>(Expr) ||
229 isa<ObjCIvarRefExpr>(Expr) ||
230 isa<ParenExpr>(FullExpr) ||
231 isa<ParenListExpr>(Expr) ||
232 isa<SizeOfPackExpr>(Expr))
233 return false;
234
235 return true;
236 }
237
238 /// \brief - Rewrite message expression for Objective-C setter and getters into
239 /// property-dot syntax.
240 bool rewriteToPropertyDotSyntax(const ObjCMessageExpr *Msg,
241 Preprocessor &PP,
242 const NSAPI &NS, edit::Commit &commit,
243 const ParentMap *PMap) {
244 if (!Msg || Msg->isImplicit() ||
245 Msg->getReceiverKind() != ObjCMessageExpr::Instance)
246 return false;
247 const ObjCMethodDecl *Method = Msg->getMethodDecl();
248 if (!Method)
249 return false;
250 if (!Method->isPropertyAccessor())
251 return false;
252
253 const ObjCInterfaceDecl *IFace =
254 NS.getASTContext().getObjContainingInterface(Method);
255 if (!IFace)
256 return false;
257
258 const ObjCPropertyDecl *Prop = Method->findPropertyDecl();
259 if (!Prop)
260 return false;
261
262 SourceRange MsgRange = Msg->getSourceRange();
263 const Expr *receiver = Msg->getInstanceReceiver();
264 bool NeedsParen = subscriptOperatorNeedsParens(receiver);
265 bool IsGetter = (Msg->getNumArgs() == 0);
266 if (IsGetter) {
267 // Find space location range between receiver expression and getter method.
268 SourceLocation BegLoc = receiver->getLocEnd();
269 BegLoc = PP.getLocForEndOfToken(BegLoc);
270 SourceLocation EndLoc = Msg->getSelectorLoc(0);
271 SourceRange SpaceRange(BegLoc, EndLoc);
272 std::string PropertyDotString;
273 // rewrite getter method expression into: receiver.property or
274 // (receiver).property
275 if (NeedsParen) {
276 commit.insertBefore(receiver->getLocStart(), "(");
277 PropertyDotString = ").";
278 }
279 else
280 PropertyDotString = ".";
281 PropertyDotString += Prop->getName();
282 commit.replace(SpaceRange, PropertyDotString);
283
284 // remove '[' ']'
285 commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
286 commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
287 } else {
288 SourceRange ReceiverRange = receiver->getSourceRange();
289 if (NeedsParen)
290 commit.insertWrap("(", ReceiverRange, ")");
291 std::string PropertyDotString = ".";
292 PropertyDotString += Prop->getName();
293 PropertyDotString += " =";
294 const Expr*const* Args = Msg->getArgs();
295 const Expr *RHS = Args[0];
296 if (!RHS)
297 return false;
298 SourceLocation BegLoc = ReceiverRange.getEnd();
299 BegLoc = PP.getLocForEndOfToken(BegLoc);
300 SourceLocation EndLoc = RHS->getLocStart();
301 EndLoc = EndLoc.getLocWithOffset(-1);
302 SourceRange Range(BegLoc, EndLoc);
303 commit.replace(Range, PropertyDotString);
304 // remove '[' ']'
305 commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
306 commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
307 }
308 return true;
309 }
310
311
Ted Kremenekf7639e12012-03-06 20:06:33 +0000312class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
313 ObjCMigrateASTConsumer &Consumer;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000314 ParentMap &PMap;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000315
316public:
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000317 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
318 : Consumer(consumer), PMap(PMap) { }
Ted Kremenekf7639e12012-03-06 20:06:33 +0000319
320 bool shouldVisitTemplateInstantiations() const { return false; }
321 bool shouldWalkTypesOfTypeLocs() const { return false; }
322
323 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000324 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000325 edit::Commit commit(*Consumer.Editor);
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000326 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000327 Consumer.Editor->commit(commit);
328 }
329
Fariborz Jahanian182486c2013-10-02 17:08:12 +0000330 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
Ted Kremenekf7639e12012-03-06 20:06:33 +0000331 edit::Commit commit(*Consumer.Editor);
332 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
333 Consumer.Editor->commit(commit);
334 }
335
Fariborz Jahanianed6de562014-10-09 18:30:56 +0000336 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Property) {
337 edit::Commit commit(*Consumer.Editor);
338 rewriteToPropertyDotSyntax(E, Consumer.PP, *Consumer.NSAPIObj,
339 commit, &PMap);
340 Consumer.Editor->commit(commit);
341 }
342
Ted Kremenekf7639e12012-03-06 20:06:33 +0000343 return true;
344 }
345
346 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
347 // Do depth first; we want to rewrite the subexpressions first so that if
348 // we have to move expressions we will move them already rewritten.
349 for (Stmt::child_range range = E->children(); range; ++range)
350 if (!TraverseStmt(*range))
351 return false;
352
353 return WalkUpFromObjCMessageExpr(E);
354 }
355};
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000356
357class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
358 ObjCMigrateASTConsumer &Consumer;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000359 std::unique_ptr<ParentMap> PMap;
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000360
361public:
362 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
363
364 bool shouldVisitTemplateInstantiations() const { return false; }
365 bool shouldWalkTypesOfTypeLocs() const { return false; }
366
367 bool TraverseStmt(Stmt *S) {
368 PMap.reset(new ParentMap(S));
369 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
370 return true;
371 }
372};
Ted Kremenekf7639e12012-03-06 20:06:33 +0000373}
374
375void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
376 if (!D)
377 return;
378 if (isa<ObjCMethodDecl>(D))
379 return; // Wait for the ObjC container declaration.
380
Argyrios Kyrtzidis6b4f3412013-01-16 23:54:48 +0000381 BodyMigrator(*this).TraverseDecl(D);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000382}
383
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000384static void append_attr(std::string &PropertyString, const char *attr,
385 bool &LParenAdded) {
386 if (!LParenAdded) {
387 PropertyString += "(";
388 LParenAdded = true;
389 }
390 else
391 PropertyString += ", ";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000392 PropertyString += attr;
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000393}
394
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000395static
396void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
397 const std::string& TypeString,
398 const char *name) {
399 const char *argPtr = TypeString.c_str();
400 int paren = 0;
401 while (*argPtr) {
402 switch (*argPtr) {
403 case '(':
404 PropertyString += *argPtr;
405 paren++;
406 break;
407 case ')':
408 PropertyString += *argPtr;
409 paren--;
410 break;
411 case '^':
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000412 case '*':
413 PropertyString += (*argPtr);
414 if (paren == 1) {
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000415 PropertyString += name;
Fariborz Jahanian3c593d62013-10-08 21:32:16 +0000416 name = "";
417 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000418 break;
419 default:
420 PropertyString += *argPtr;
421 break;
422 }
423 argPtr++;
424 }
425}
426
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000427static const char *PropertyMemoryAttribute(ASTContext &Context, QualType ArgType) {
428 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
429 bool RetainableObject = ArgType->isObjCRetainableType();
Fariborz Jahanian49e69ee2013-12-12 01:02:00 +0000430 if (RetainableObject &&
431 (propertyLifetime == Qualifiers::OCL_Strong
432 || propertyLifetime == Qualifiers::OCL_None)) {
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000433 if (const ObjCObjectPointerType *ObjPtrTy =
434 ArgType->getAs<ObjCObjectPointerType>()) {
435 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
436 if (IDecl &&
437 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
438 return "copy";
439 else
Fariborz Jahanian54c8eaa2013-11-21 00:58:17 +0000440 return "strong";
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000441 }
442 else if (ArgType->isBlockPointerType())
443 return "copy";
444 } else if (propertyLifetime == Qualifiers::OCL_Weak)
445 // TODO. More precise determination of 'weak' attribute requires
446 // looking into setter's implementation for backing weak ivar.
447 return "weak";
448 else if (RetainableObject)
Fariborz Jahanian54c8eaa2013-11-21 00:58:17 +0000449 return ArgType->isBlockPointerType() ? "copy" : "strong";
Craig Topper8ae12032014-05-07 06:21:57 +0000450 return nullptr;
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000451}
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000452
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000453static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000454 const ObjCMethodDecl *Setter,
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000455 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +0000456 unsigned LengthOfPrefix,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +0000457 bool Atomic, bool UseNsIosOnlyMacro,
458 bool AvailabilityArgsMatch) {
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000459 ASTContext &Context = NS.getASTContext();
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000460 bool LParenAdded = false;
461 std::string PropertyString = "@property ";
Fariborz Jahanian2e793d62013-11-13 00:08:36 +0000462 if (UseNsIosOnlyMacro && Context.Idents.get("NS_NONATOMIC_IOSONLY").hasMacroDefinition()) {
Fariborz Jahanianbed1be92013-11-12 19:25:50 +0000463 PropertyString += "(NS_NONATOMIC_IOSONLY";
464 LParenAdded = true;
465 } else if (!Atomic) {
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000466 PropertyString += "(nonatomic";
467 LParenAdded = true;
468 }
469
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000470 std::string PropertyNameString = Getter->getNameAsString();
471 StringRef PropertyName(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000472 if (LengthOfPrefix > 0) {
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000473 if (!LParenAdded) {
474 PropertyString += "(getter=";
475 LParenAdded = true;
476 }
477 else
478 PropertyString += ", getter=";
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000479 PropertyString += PropertyNameString;
480 }
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000481 // Property with no setter may be suggested as a 'readonly' property.
Fariborz Jahaniand9aef7882013-11-21 17:49:34 +0000482 if (!Setter)
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000483 append_attr(PropertyString, "readonly", LParenAdded);
Fariborz Jahaniand9aef7882013-11-21 17:49:34 +0000484
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000485
Fariborz Jahanian33304e302013-10-16 18:52:17 +0000486 // Short circuit 'delegate' properties that contain the name "delegate" or
487 // "dataSource", or have exact name "target" to have 'assign' attribute.
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000488 if (PropertyName.equals("target") ||
489 (PropertyName.find("delegate") != StringRef::npos) ||
Fariborz Jahanian78bff052013-10-16 20:44:26 +0000490 (PropertyName.find("dataSource") != StringRef::npos)) {
Alp Toker314cc812014-01-25 16:55:45 +0000491 QualType QT = Getter->getReturnType();
Fariborz Jahanian78bff052013-10-16 20:44:26 +0000492 if (!QT->isRealType())
493 append_attr(PropertyString, "assign", LParenAdded);
Fariborz Jahaniand9aef7882013-11-21 17:49:34 +0000494 } else if (!Setter) {
Alp Toker314cc812014-01-25 16:55:45 +0000495 QualType ResType = Context.getCanonicalType(Getter->getReturnType());
Fariborz Jahaniand9aef7882013-11-21 17:49:34 +0000496 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ResType))
497 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
498 } else {
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000499 const ParmVarDecl *argDecl = *Setter->param_begin();
500 QualType ArgType = Context.getCanonicalType(argDecl->getType());
Fariborz Jahanianda267d02013-11-14 18:28:58 +0000501 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ArgType))
502 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
Fariborz Jahaniancf387c62013-08-06 18:06:23 +0000503 }
Fariborz Jahanian4a8865b2013-10-16 19:48:23 +0000504 if (LParenAdded)
505 PropertyString += ')';
Alp Toker314cc812014-01-25 16:55:45 +0000506 QualType RT = Getter->getReturnType();
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000507 if (!isa<TypedefType>(RT)) {
508 // strip off any ARC lifetime qualifier.
509 QualType CanResultTy = Context.getCanonicalType(RT);
510 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
511 Qualifiers Qs = CanResultTy.getQualifiers();
512 Qs.removeObjCLifetime();
513 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
514 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000515 }
516 PropertyString += " ";
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000517 PrintingPolicy SubPolicy(Context.getPrintingPolicy());
518 SubPolicy.SuppressStrongLifetime = true;
Fariborz Jahaniande557f82013-10-09 17:37:28 +0000519 SubPolicy.SuppressLifetimeQualifiers = true;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000520 std::string TypeString = RT.getAsString(SubPolicy);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000521 if (LengthOfPrefix > 0) {
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000522 // property name must strip off "is" and lower case the first character
523 // after that; e.g. isContinuous will become continuous.
524 StringRef PropertyNameStringRef(PropertyNameString);
Fariborz Jahanianca399602013-09-11 17:05:15 +0000525 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000526 PropertyNameString = PropertyNameStringRef;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000527 bool NoLowering = (isUppercase(PropertyNameString[0]) &&
528 PropertyNameString.size() > 1 &&
529 isUppercase(PropertyNameString[1]));
Fariborz Jahanian34fea362013-09-11 18:27:16 +0000530 if (!NoLowering)
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000531 PropertyNameString[0] = toLowercase(PropertyNameString[0]);
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000532 }
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000533 if (RT->isBlockPointerType() || RT->isFunctionPointerType())
534 MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
535 TypeString,
536 PropertyNameString.c_str());
537 else {
538 char LastChar = TypeString[TypeString.size()-1];
539 PropertyString += TypeString;
540 if (LastChar != '*')
541 PropertyString += ' ';
Fariborz Jahaniancf2ff9b2013-08-08 20:51:58 +0000542 PropertyString += PropertyNameString;
Fariborz Jahanian02461d02013-10-08 20:14:24 +0000543 }
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000544 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
545 Selector GetterSelector = Getter->getSelector();
546
547 SourceLocation EndGetterSelectorLoc =
548 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000549 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
Fariborz Jahanian215f96c2013-09-06 23:45:20 +0000550 EndGetterSelectorLoc),
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000551 PropertyString);
Fariborz Jahanian071b98e2013-11-01 00:26:48 +0000552 if (Setter && AvailabilityArgsMatch) {
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000553 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
554 // Get location past ';'
555 EndLoc = EndLoc.getLocWithOffset(1);
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000556 SourceLocation BeginOfSetterDclLoc = Setter->getLocStart();
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000557 // FIXME. This assumes that setter decl; is immediately preceded by eoln.
Fariborz Jahanian1b667872013-10-16 22:35:19 +0000558 // It is trying to remove the setter method decl. line entirely.
559 BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
560 commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
Fariborz Jahanian55d6e6c2013-08-28 23:22:46 +0000561 }
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000562}
563
Fariborz Jahanian48a44d42013-11-19 18:17:31 +0000564static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) {
565 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) {
566 StringRef Name = CatDecl->getName();
567 return Name.endswith("Deprecated");
568 }
569 return false;
570}
571
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000572void ObjCMigrateASTConsumer::migrateObjCInterfaceDecl(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +0000573 ObjCContainerDecl *D) {
Fariborz Jahanian48a44d42013-11-19 18:17:31 +0000574 if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D))
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000575 return;
Fariborz Jahanian48a44d42013-11-19 18:17:31 +0000576
Aaron Ballmanaff18c02014-03-13 19:03:34 +0000577 for (auto *Method : D->methods()) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000578 if (Method->isDeprecated())
579 continue;
Fariborz Jahanianec7cea92013-11-08 01:15:17 +0000580 bool PropertyInferred = migrateProperty(Ctx, D, Method);
581 // If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to
582 // the getter method as it ends up on the property itself which we don't want
583 // to do unless -objcmt-returns-innerpointer-property option is on.
584 if (!PropertyInferred ||
585 (ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
Fariborz Jahanian22626e72013-11-08 02:00:22 +0000586 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
587 migrateNsReturnsInnerPointer(Ctx, Method);
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000588 }
Fariborz Jahanian23417072013-11-05 22:28:30 +0000589 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
590 return;
591
Aaron Ballmand174edf2014-03-13 19:11:50 +0000592 for (auto *Prop : D->properties()) {
Fariborz Jahanian8c45e282013-10-02 22:49:59 +0000593 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000594 !Prop->isDeprecated())
Fariborz Jahanian10b74352013-09-24 20:20:52 +0000595 migratePropertyNsReturnsInnerPointer(Ctx, Prop);
Fariborz Jahaniana7437f02013-07-03 23:05:00 +0000596 }
597}
598
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +0000599static bool
Fariborz Jahanian9a3512b2013-07-13 17:16:41 +0000600ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000601 const ObjCImplementationDecl *ImpDecl,
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000602 const ObjCInterfaceDecl *IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000603 ObjCProtocolDecl *Protocol) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000604 // In auto-synthesis, protocol properties are not synthesized. So,
605 // a conforming protocol must have its required properties declared
606 // in class interface.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000607 bool HasAtleastOneRequiredProperty = false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000608 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
Aaron Ballmand174edf2014-03-13 19:11:50 +0000609 for (const auto *Property : PDecl->properties()) {
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000610 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
611 continue;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000612 HasAtleastOneRequiredProperty = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000613 DeclContext::lookup_const_result R = IDecl->lookup(Property->getDeclName());
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000614 if (R.size() == 0) {
615 // Relax the rule and look into class's implementation for a synthesize
616 // or dynamic declaration. Class is implementing a property coming from
617 // another protocol. This still makes the target protocol as conforming.
618 if (!ImpDecl->FindPropertyImplDecl(
619 Property->getDeclName().getAsIdentifierInfo()))
620 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000621 }
Fariborz Jahanian2bc3dda2013-07-16 21:59:42 +0000622 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
623 if ((ClassProperty->getPropertyAttributes()
624 != Property->getPropertyAttributes()) ||
625 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
626 return false;
627 }
628 else
629 return false;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000630 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000631
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000632 // At this point, all required properties in this protocol conform to those
633 // declared in the class.
634 // Check that class implements the required methods of the protocol too.
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000635 bool HasAtleastOneRequiredMethod = false;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000636 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
637 if (PDecl->meth_begin() == PDecl->meth_end())
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000638 return HasAtleastOneRequiredProperty;
Aaron Ballmanaff18c02014-03-13 19:03:34 +0000639 for (const auto *MD : PDecl->methods()) {
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000640 if (MD->isImplicit())
641 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000642 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
643 continue;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000644 DeclContext::lookup_const_result R = ImpDecl->lookup(MD->getDeclName());
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000645 if (R.size() == 0)
646 return false;
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000647 bool match = false;
648 HasAtleastOneRequiredMethod = true;
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000649 for (unsigned I = 0, N = R.size(); I != N; ++I)
650 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
651 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
652 match = true;
653 break;
654 }
655 if (!match)
656 return false;
657 }
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000658 }
Fariborz Jahanian9e543af2013-07-22 23:50:04 +0000659 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
660 return true;
661 return false;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000662}
663
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000664static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
665 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
666 const NSAPI &NS, edit::Commit &commit) {
667 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
668 std::string ClassString;
669 SourceLocation EndLoc =
670 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
671
672 if (Protocols.empty()) {
673 ClassString = '<';
674 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
675 ClassString += ConformingProtocols[i]->getNameAsString();
676 if (i != (e-1))
677 ClassString += ", ";
678 }
679 ClassString += "> ";
680 }
681 else {
682 ClassString = ", ";
683 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
684 ClassString += ConformingProtocols[i]->getNameAsString();
685 if (i != (e-1))
686 ClassString += ", ";
687 }
688 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
689 EndLoc = *PL;
690 }
691
692 commit.insertAfterToken(EndLoc, ClassString);
693 return true;
694}
695
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000696static StringRef GetUnsignedName(StringRef NSIntegerName) {
697 StringRef UnsignedName = llvm::StringSwitch<StringRef>(NSIntegerName)
698 .Case("int8_t", "uint8_t")
699 .Case("int16_t", "uint16_t")
700 .Case("int32_t", "uint32_t")
701 .Case("NSInteger", "NSUInteger")
702 .Case("int64_t", "uint64_t")
703 .Default(NSIntegerName);
704 return UnsignedName;
705}
706
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000707static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
708 const TypedefDecl *TypedefDcl,
Fariborz Jahanianb0057bb2013-07-19 01:05:49 +0000709 const NSAPI &NS, edit::Commit &commit,
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000710 StringRef NSIntegerName,
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000711 bool NSOptions) {
712 std::string ClassString;
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000713 if (NSOptions) {
714 ClassString = "typedef NS_OPTIONS(";
715 ClassString += GetUnsignedName(NSIntegerName);
716 }
717 else {
718 ClassString = "typedef NS_ENUM(";
719 ClassString += NSIntegerName;
720 }
721 ClassString += ", ";
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000722
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000723 ClassString += TypedefDcl->getIdentifier()->getName();
724 ClassString += ')';
725 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
726 commit.replace(R, ClassString);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000727 SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
728 EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
729 NS.getASTContext(), /*IsDecl*/true);
730 if (!EndOfEnumDclLoc.isInvalid()) {
731 SourceRange EnumDclRange(EnumDcl->getLocStart(), EndOfEnumDclLoc);
732 commit.insertFromRange(TypedefDcl->getLocStart(), EnumDclRange);
733 }
734 else
735 return false;
736
737 SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
738 EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
739 NS.getASTContext(), /*IsDecl*/true);
740 if (!EndTypedefDclLoc.isInvalid()) {
741 SourceRange TDRange(TypedefDcl->getLocStart(), EndTypedefDclLoc);
742 commit.remove(TDRange);
743 }
744 else
745 return false;
746
747 EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
Fariborz Jahanian1d27ffd2013-10-11 17:35:22 +0000748 /*IsDecl*/true);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000749 if (!EndOfEnumDclLoc.isInvalid()) {
750 SourceLocation BeginOfEnumDclLoc = EnumDcl->getLocStart();
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000751 // FIXME. This assumes that enum decl; is immediately preceded by eoln.
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000752 // It is trying to remove the enum decl. lines entirely.
753 BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
754 commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000755 return true;
756 }
757 return false;
758}
759
Fariborz Jahanian403425b2013-10-17 23:13:13 +0000760static void rewriteToNSMacroDecl(const EnumDecl *EnumDcl,
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000761 const TypedefDecl *TypedefDcl,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000762 const NSAPI &NS, edit::Commit &commit,
763 bool IsNSIntegerType) {
764 std::string ClassString =
765 IsNSIntegerType ? "NS_ENUM(NSInteger, " : "NS_OPTIONS(NSUInteger, ";
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000766 ClassString += TypedefDcl->getIdentifier()->getName();
767 ClassString += ')';
768 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
769 commit.replace(R, ClassString);
Fariborz Jahanian77a835b2014-10-01 20:46:32 +0000770 // This is to remove spaces between '}' and typedef name.
771 SourceLocation StartTypedefLoc = EnumDcl->getLocEnd();
772 StartTypedefLoc = StartTypedefLoc.getLocWithOffset(+1);
773 SourceLocation EndTypedefLoc = TypedefDcl->getLocEnd();
774
775 commit.remove(SourceRange(StartTypedefLoc, EndTypedefLoc));
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000776}
777
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000778static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000779 const EnumDecl *EnumDcl) {
780 bool PowerOfTwo = true;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000781 bool AllHexdecimalEnumerator = true;
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000782 uint64_t MaxPowerOfTwoVal = 0;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000783 for (auto Enumerator : EnumDcl->enumerators()) {
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000784 const Expr *InitExpr = Enumerator->getInitExpr();
785 if (!InitExpr) {
786 PowerOfTwo = false;
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000787 AllHexdecimalEnumerator = false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000788 continue;
789 }
Fariborz Jahanian6e1798e2013-09-17 23:32:51 +0000790 InitExpr = InitExpr->IgnoreParenCasts();
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000791 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
792 if (BO->isShiftOp() || BO->isBitwiseOp())
793 return true;
794
795 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
Fariborz Jahanianbe7bc112013-08-15 18:46:37 +0000796 if (PowerOfTwo && EnumVal) {
797 if (!llvm::isPowerOf2_64(EnumVal))
798 PowerOfTwo = false;
799 else if (EnumVal > MaxPowerOfTwoVal)
800 MaxPowerOfTwoVal = EnumVal;
801 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000802 if (AllHexdecimalEnumerator && EnumVal) {
803 bool FoundHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000804 SourceLocation EndLoc = Enumerator->getLocEnd();
805 Token Tok;
806 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
807 if (Tok.isLiteral() && Tok.getLength() > 2) {
808 if (const char *StringLit = Tok.getLiteralData())
809 FoundHexdecimalEnumerator =
810 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
811 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000812 if (!FoundHexdecimalEnumerator)
813 AllHexdecimalEnumerator = false;
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000814 }
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000815 }
Fariborz Jahanian02bdb162013-09-23 20:27:06 +0000816 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000817}
818
Fariborz Jahanian008ef722013-07-19 17:44:32 +0000819void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000820 const ObjCImplementationDecl *ImpDecl) {
821 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
Fariborz Jahanian75226d52013-09-17 21:56:04 +0000822 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000823 return;
824 // Find all implicit conforming protocols for this class
825 // and make them explicit.
826 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
827 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000828 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000829
Craig Topperc6914d02014-08-25 04:15:02 +0000830 for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls)
831 if (!ExplicitProtocols.count(ProtDecl))
832 PotentialImplicitProtocols.push_back(ProtDecl);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000833
834 if (PotentialImplicitProtocols.empty())
835 return;
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000836
837 // go through list of non-optional methods and properties in each protocol
838 // in the PotentialImplicitProtocols list. If class implements every one of the
839 // methods and properties, then this class conforms to this protocol.
840 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
841 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
Fariborz Jahaniand36150d2013-07-15 21:22:08 +0000842 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
Fariborz Jahanian9eabf452013-07-13 00:04:20 +0000843 PotentialImplicitProtocols[i]))
844 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000845
846 if (ConformingProtocols.empty())
847 return;
Fariborz Jahaniancb7b8de2013-07-17 00:02:22 +0000848
849 // Further reduce number of conforming protocols. If protocol P1 is in the list
850 // protocol P2 (P2<P1>), No need to include P1.
851 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
852 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
853 bool DropIt = false;
854 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
855 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
856 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
857 if (PDecl == TargetPDecl)
858 continue;
859 if (PDecl->lookupProtocolNamed(
860 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
861 DropIt = true;
862 break;
863 }
864 }
865 if (!DropIt)
866 MinimalConformingProtocols.push_back(TargetPDecl);
867 }
Fariborz Jahanian769c04e2013-12-17 01:01:33 +0000868 if (MinimalConformingProtocols.empty())
869 return;
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000870 edit::Commit commit(*Editor);
Fariborz Jahanian85e988b2013-07-18 22:17:33 +0000871 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
872 *NSAPIObj, commit);
Fariborz Jahanian5bd5aff2013-07-16 00:20:21 +0000873 Editor->commit(commit);
Fariborz Jahanian1be01532013-07-12 22:32:19 +0000874}
875
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000876void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
877 const TypedefDecl *TypedefDcl) {
878
879 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
880 if (NSAPIObj->isObjCNSIntegerType(qt))
881 NSIntegerTypedefed = TypedefDcl;
882 else if (NSAPIObj->isObjCNSUIntegerType(qt))
883 NSUIntegerTypedefed = TypedefDcl;
884}
885
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000886bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
Fariborz Jahanian92463272013-07-18 20:11:45 +0000887 const EnumDecl *EnumDcl,
888 const TypedefDecl *TypedefDcl) {
889 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
Fariborz Jahanian18625ee2014-09-15 16:41:47 +0000890 EnumDcl->isDeprecated() || EnumDcl->getIntegerTypeSourceInfo())
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000891 return false;
892 if (!TypedefDcl) {
893 if (NSIntegerTypedefed) {
894 TypedefDcl = NSIntegerTypedefed;
Craig Topper8ae12032014-05-07 06:21:57 +0000895 NSIntegerTypedefed = nullptr;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000896 }
897 else if (NSUIntegerTypedefed) {
898 TypedefDcl = NSUIntegerTypedefed;
Craig Topper8ae12032014-05-07 06:21:57 +0000899 NSUIntegerTypedefed = nullptr;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000900 }
901 else
902 return false;
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +0000903 FileID FileIdOfTypedefDcl =
904 PP.getSourceManager().getFileID(TypedefDcl->getLocation());
905 FileID FileIdOfEnumDcl =
906 PP.getSourceManager().getFileID(EnumDcl->getLocation());
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000907 if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
908 return false;
909 }
910 if (TypedefDcl->isDeprecated())
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000911 return false;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000912
913 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000914 StringRef NSIntegerName = NSAPIObj->GetNSIntegralKind(qt);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000915
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000916 if (NSIntegerName.empty()) {
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000917 // Also check for typedef enum {...} TD;
918 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
919 if (EnumTy->getDecl() == EnumDcl) {
Fariborz Jahaniana23f4fb2013-08-30 00:10:37 +0000920 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +0000921 if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition() &&
922 !InsertFoundation(Ctx, TypedefDcl->getLocStart()))
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000923 return false;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000924 edit::Commit commit(*Editor);
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000925 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000926 Editor->commit(commit);
Fariborz Jahaniande79e812013-10-17 22:23:32 +0000927 return true;
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000928 }
Fariborz Jahanianc1c44f62013-07-19 20:18:36 +0000929 }
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000930 return false;
Fariborz Jahaniand0f6f792013-07-22 18:53:45 +0000931 }
Fariborz Jahanian92463272013-07-18 20:11:45 +0000932
Fariborz Jahanianff3476e2013-08-30 17:46:01 +0000933 // We may still use NS_OPTIONS based on what we find in the enumertor list.
934 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000935 // For sanity check, see if macro NS_ENUM can be seen.
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +0000936 if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition()
937 && !InsertFoundation(Ctx, TypedefDcl->getLocStart()))
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +0000938 return false;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000939 edit::Commit commit(*Editor);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000940 bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
Fariborz Jahanian35ee87d2014-10-06 23:50:37 +0000941 commit, NSIntegerName, NSOptions);
Fariborz Jahanian92463272013-07-18 20:11:45 +0000942 Editor->commit(commit);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +0000943 return Res;
Fariborz Jahanian92463272013-07-18 20:11:45 +0000944}
945
Argyrios Kyrtzidisc02a0db2014-05-21 00:24:20 +0000946static void ReplaceWithInstancetype(ASTContext &Ctx,
947 const ObjCMigrateASTConsumer &ASTC,
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000948 ObjCMethodDecl *OM) {
Argyrios Kyrtzidisc02a0db2014-05-21 00:24:20 +0000949 if (OM->getReturnType() == Ctx.getObjCInstanceType())
950 return; // already has instancetype.
951
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000952 SourceRange R;
953 std::string ClassString;
Alp Toker314cc812014-01-25 16:55:45 +0000954 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
Fariborz Jahanianc4291852013-08-02 18:00:53 +0000955 TypeLoc TL = TSInfo->getTypeLoc();
956 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
957 ClassString = "instancetype";
958 }
959 else {
960 R = SourceRange(OM->getLocStart(), OM->getLocStart());
961 ClassString = OM->isInstanceMethod() ? '-' : '+';
962 ClassString += " (instancetype)";
963 }
964 edit::Commit commit(*ASTC.Editor);
965 commit.replace(R, ClassString);
966 ASTC.Editor->commit(commit);
967}
968
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000969static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
970 ObjCMethodDecl *OM) {
971 ObjCInterfaceDecl *IDecl = OM->getClassInterface();
972 SourceRange R;
973 std::string ClassString;
Alp Toker314cc812014-01-25 16:55:45 +0000974 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
Fariborz Jahanian7c87b432013-10-10 18:23:13 +0000975 TypeLoc TL = TSInfo->getTypeLoc();
976 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
977 ClassString = IDecl->getName();
978 ClassString += "*";
979 }
980 }
981 else {
982 R = SourceRange(OM->getLocStart(), OM->getLocStart());
983 ClassString = "+ (";
984 ClassString += IDecl->getName(); ClassString += "*)";
985 }
986 edit::Commit commit(*ASTC.Editor);
987 commit.replace(R, ClassString);
988 ASTC.Editor->commit(commit);
989}
990
Fariborz Jahanian670ef262013-07-23 23:34:42 +0000991void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
992 ObjCContainerDecl *CDecl,
993 ObjCMethodDecl *OM) {
Fariborz Jahanian71221352013-07-23 22:42:28 +0000994 ObjCInstanceTypeFamily OIT_Family =
995 Selector::getInstTypeMethodFamily(OM->getSelector());
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000996
Fariborz Jahanian267bae32013-07-24 19:18:37 +0000997 std::string ClassName;
Fariborz Jahanian631925f2013-07-23 23:55:55 +0000998 switch (OIT_Family) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +0000999 case OIT_None:
1000 migrateFactoryMethod(Ctx, CDecl, OM);
1001 return;
Fariborz Jahanian7dd71432013-08-28 21:23:00 +00001002 case OIT_Array:
1003 ClassName = "NSArray";
1004 break;
1005 case OIT_Dictionary:
1006 ClassName = "NSDictionary";
1007 break;
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001008 case OIT_Singleton:
1009 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
Fariborz Jahanian631925f2013-07-23 23:55:55 +00001010 return;
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +00001011 case OIT_Init:
Alp Toker314cc812014-01-25 16:55:45 +00001012 if (OM->getReturnType()->isObjCIdType())
Argyrios Kyrtzidisc02a0db2014-05-21 00:24:20 +00001013 ReplaceWithInstancetype(Ctx, *this, OM);
Fariborz Jahanian1c900bc2013-09-18 20:35:47 +00001014 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001015 case OIT_ReturnsSelf:
1016 migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
1017 return;
Fariborz Jahanian631925f2013-07-23 23:55:55 +00001018 }
Alp Toker314cc812014-01-25 16:55:45 +00001019 if (!OM->getReturnType()->isObjCIdType())
Fariborz Jahanian71221352013-07-23 22:42:28 +00001020 return;
1021
1022 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1023 if (!IDecl) {
1024 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1025 IDecl = CatDecl->getClassInterface();
1026 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1027 IDecl = ImpDecl->getClassInterface();
1028 }
Fariborz Jahanian267bae32013-07-24 19:18:37 +00001029 if (!IDecl ||
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001030 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
1031 migrateFactoryMethod(Ctx, CDecl, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +00001032 return;
Fariborz Jahanian280954a2013-07-24 18:31:42 +00001033 }
Argyrios Kyrtzidisc02a0db2014-05-21 00:24:20 +00001034 ReplaceWithInstancetype(Ctx, *this, OM);
Fariborz Jahanian71221352013-07-23 22:42:28 +00001035}
1036
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001037static bool TypeIsInnerPointer(QualType T) {
1038 if (!T->isAnyPointerType())
1039 return false;
1040 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
Fariborz Jahanian73466ca2013-09-26 21:43:47 +00001041 T->isBlockPointerType() || T->isFunctionPointerType() ||
1042 ento::coreFoundation::isCFObjectRef(T))
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001043 return false;
Fariborz Jahanian9d5fffb2013-09-09 23:56:14 +00001044 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
1045 // is not an innter pointer type.
1046 QualType OrigT = T;
1047 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
1048 T = TD->getDecl()->getUnderlyingType();
1049 if (OrigT == T || !T->isPointerType())
1050 return true;
1051 const PointerType* PT = T->getAs<PointerType>();
1052 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
1053 if (UPointeeT->isRecordType()) {
1054 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
1055 if (!RecordTy->getDecl()->isCompleteDefinition())
1056 return false;
1057 }
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001058 return true;
1059}
1060
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001061/// \brief Check whether the two versions match.
1062static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) {
1063 return (X == Y);
1064}
1065
1066/// AvailabilityAttrsMatch - This routine checks that if comparing two
1067/// availability attributes, all their components match. It returns
1068/// true, if not dealing with availability or when all components of
1069/// availability attributes match. This routine is only called when
1070/// the attributes are of the same kind.
1071static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) {
1072 const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1);
1073 if (!AA1)
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001074 return true;
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001075 const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2);
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001076
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001077 VersionTuple Introduced1 = AA1->getIntroduced();
1078 VersionTuple Deprecated1 = AA1->getDeprecated();
1079 VersionTuple Obsoleted1 = AA1->getObsoleted();
1080 bool IsUnavailable1 = AA1->getUnavailable();
1081 VersionTuple Introduced2 = AA2->getIntroduced();
1082 VersionTuple Deprecated2 = AA2->getDeprecated();
1083 VersionTuple Obsoleted2 = AA2->getObsoleted();
1084 bool IsUnavailable2 = AA2->getUnavailable();
1085 return (versionsMatch(Introduced1, Introduced2) &&
1086 versionsMatch(Deprecated1, Deprecated2) &&
1087 versionsMatch(Obsoleted1, Obsoleted2) &&
1088 IsUnavailable1 == IsUnavailable2);
1089
1090}
1091
1092static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2,
1093 bool &AvailabilityArgsMatch) {
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001094 // This list is very small, so this need not be optimized.
1095 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
1096 bool match = false;
1097 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001098 // Matching attribute kind only. Except for Availabilty attributes,
1099 // we are not getting into details of the attributes. For all practical purposes
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001100 // this is sufficient.
1101 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001102 if (AvailabilityArgsMatch)
1103 AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]);
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001104 match = true;
1105 break;
1106 }
1107 }
1108 if (!match)
1109 return false;
1110 }
1111 return true;
1112}
1113
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001114/// AttributesMatch - This routine checks list of attributes for two
1115/// decls. It returns false, if there is a mismatch in kind of
1116/// attributes seen in the decls. It returns true if the two decls
1117/// have list of same kind of attributes. Furthermore, when there
1118/// are availability attributes in the two decls, it sets the
1119/// AvailabilityArgsMatch to false if availability attributes have
1120/// different versions, etc.
1121static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2,
1122 bool &AvailabilityArgsMatch) {
1123 if (!Decl1->hasAttrs() || !Decl2->hasAttrs()) {
1124 AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs());
1125 return true;
1126 }
1127 AvailabilityArgsMatch = true;
1128 const AttrVec &Attrs1 = Decl1->getAttrs();
1129 const AttrVec &Attrs2 = Decl2->getAttrs();
1130 bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch);
1131 if (match && (Attrs2.size() > Attrs1.size()))
1132 return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch);
1133 return match;
1134}
1135
Fariborz Jahanian5d783df2013-09-27 22:55:54 +00001136static bool IsValidIdentifier(ASTContext &Ctx,
1137 const char *Name) {
1138 if (!isIdentifierHead(Name[0]))
1139 return false;
1140 std::string NameString = Name;
1141 NameString[0] = toLowercase(NameString[0]);
1142 IdentifierInfo *II = &Ctx.Idents.get(NameString);
1143 return II->getTokenID() == tok::identifier;
1144}
1145
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001146bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001147 ObjCContainerDecl *D,
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001148 ObjCMethodDecl *Method) {
1149 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
1150 Method->param_size() != 0)
1151 return false;
1152 // Is this method candidate to be a getter?
Alp Toker314cc812014-01-25 16:55:45 +00001153 QualType GRT = Method->getReturnType();
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001154 if (GRT->isVoidType())
1155 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001156
1157 Selector GetterSelector = Method->getSelector();
Fariborz Jahanian7391a7b5a2013-09-25 00:17:07 +00001158 ObjCInstanceTypeFamily OIT_Family =
1159 Selector::getInstTypeMethodFamily(GetterSelector);
1160
1161 if (OIT_Family != OIT_None)
1162 return false;
1163
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001164 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
1165 Selector SetterSelector =
1166 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1167 PP.getSelectorTable(),
1168 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001169 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanianca399602013-09-11 17:05:15 +00001170 unsigned LengthOfPrefix = 0;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001171 if (!SetterMethod) {
1172 // try a different naming convention for getter: isXxxxx
1173 StringRef getterNameString = getterName->getName();
Fariborz Jahanianca399602013-09-11 17:05:15 +00001174 bool IsPrefix = getterNameString.startswith("is");
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +00001175 // Note that we don't want to change an isXXX method of retainable object
1176 // type to property (readonly or otherwise).
1177 if (IsPrefix && GRT->isObjCRetainableType())
1178 return false;
1179 if (IsPrefix || getterNameString.startswith("get")) {
Fariborz Jahanianca399602013-09-11 17:05:15 +00001180 LengthOfPrefix = (IsPrefix ? 2 : 3);
1181 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
1182 // Make sure that first character after "is" or "get" prefix can
1183 // start an identifier.
Fariborz Jahanian5d783df2013-09-27 22:55:54 +00001184 if (!IsValidIdentifier(Ctx, CGetterName))
Fariborz Jahanianca399602013-09-11 17:05:15 +00001185 return false;
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001186 if (CGetterName[0] && isUppercase(CGetterName[0])) {
1187 getterName = &Ctx.Idents.get(CGetterName);
1188 SetterSelector =
1189 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1190 PP.getSelectorTable(),
1191 getterName);
Fariborz Jahanian92f72422013-09-17 19:00:30 +00001192 SetterMethod = D->getInstanceMethod(SetterSelector);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001193 }
1194 }
1195 }
Fariborz Jahanian4c3d9c52013-09-17 19:38:55 +00001196
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001197 if (SetterMethod) {
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001198 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
1199 return false;
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001200 bool AvailabilityArgsMatch;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001201 if (SetterMethod->isDeprecated() ||
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001202 !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch))
Fariborz Jahanianf6c65052013-09-17 22:41:25 +00001203 return false;
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001204
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001205 // Is this a valid setter, matching the target getter?
Alp Toker314cc812014-01-25 16:55:45 +00001206 QualType SRT = SetterMethod->getReturnType();
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001207 if (!SRT->isVoidType())
1208 return false;
1209 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
1210 QualType ArgType = argDecl->getType();
Fariborz Jahanian2ba62a72013-09-18 17:22:25 +00001211 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001212 return false;
1213 edit::Commit commit(*Editor);
1214 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001215 LengthOfPrefix,
1216 (ASTMigrateActions &
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001217 FrontendOptions::ObjCMT_AtomicProperty) != 0,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001218 (ASTMigrateActions &
1219 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001220 AvailabilityArgsMatch);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001221 Editor->commit(commit);
1222 return true;
1223 }
Fariborz Jahanian182486c2013-10-02 17:08:12 +00001224 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001225 // Try a non-void method with no argument (and no setter or property of same name
1226 // as a 'readonly' property.
1227 edit::Commit commit(*Editor);
Craig Topper8ae12032014-05-07 06:21:57 +00001228 rewriteToObjCProperty(Method, nullptr /*SetterMethod*/, *NSAPIObj, commit,
Fariborz Jahanian20a11242013-10-09 19:06:08 +00001229 LengthOfPrefix,
1230 (ASTMigrateActions &
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001231 FrontendOptions::ObjCMT_AtomicProperty) != 0,
Fariborz Jahanian2e793d62013-11-13 00:08:36 +00001232 (ASTMigrateActions &
1233 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
Fariborz Jahanian071b98e2013-11-01 00:26:48 +00001234 /*AvailabilityArgsMatch*/false);
Fariborz Jahanian215f96c2013-09-06 23:45:20 +00001235 Editor->commit(commit);
1236 return true;
1237 }
1238 return false;
1239}
1240
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001241void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
1242 ObjCMethodDecl *OM) {
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001243 if (OM->isImplicit() ||
Fariborz Jahanian7c1a4452013-09-26 22:43:41 +00001244 !OM->isInstanceMethod() ||
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001245 OM->hasAttr<ObjCReturnsInnerPointerAttr>())
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001246 return;
Alp Toker314cc812014-01-25 16:55:45 +00001247
1248 QualType RT = OM->getReturnType();
Fariborz Jahaniand0fbf6c2013-08-30 23:52:08 +00001249 if (!TypeIsInnerPointer(RT) ||
1250 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
1251 return;
1252
1253 edit::Commit commit(*Editor);
1254 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
1255 Editor->commit(commit);
1256}
1257
Fariborz Jahanian10b74352013-09-24 20:20:52 +00001258void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
1259 ObjCPropertyDecl *P) {
1260 QualType T = P->getType();
1261
1262 if (!TypeIsInnerPointer(T) ||
1263 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition())
1264 return;
1265 edit::Commit commit(*Editor);
1266 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
1267 Editor->commit(commit);
1268}
1269
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001270void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
Fariborz Jahanian71221352013-07-23 22:42:28 +00001271 ObjCContainerDecl *CDecl) {
Fariborz Jahanian48a44d42013-11-19 18:17:31 +00001272 if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl))
Fariborz Jahaniane47a14a2013-09-18 15:43:52 +00001273 return;
1274
Fariborz Jahanian71221352013-07-23 22:42:28 +00001275 // migrate methods which can have instancetype as their result type.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001276 for (auto *Method : CDecl->methods()) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001277 if (Method->isDeprecated())
1278 continue;
Fariborz Jahanian71221352013-07-23 22:42:28 +00001279 migrateMethodInstanceType(Ctx, CDecl, Method);
1280 }
1281}
1282
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001283void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
1284 ObjCContainerDecl *CDecl,
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001285 ObjCMethodDecl *OM,
1286 ObjCInstanceTypeFamily OIT_Family) {
Fariborz Jahanian3bfc35e2013-08-02 22:34:18 +00001287 if (OM->isInstanceMethod() ||
Alp Toker314cc812014-01-25 16:55:45 +00001288 OM->getReturnType() == Ctx.getObjCInstanceType() ||
1289 !OM->getReturnType()->isObjCIdType())
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001290 return;
1291
1292 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1293 // NSYYYNamE with matching names be at least 3 characters long.
1294 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1295 if (!IDecl) {
1296 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1297 IDecl = CatDecl->getClassInterface();
1298 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1299 IDecl = ImpDecl->getClassInterface();
1300 }
1301 if (!IDecl)
1302 return;
1303
1304 std::string StringClassName = IDecl->getName();
1305 StringRef LoweredClassName(StringClassName);
1306 std::string StringLoweredClassName = LoweredClassName.lower();
1307 LoweredClassName = StringLoweredClassName;
1308
1309 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001310 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1311 if (!MethodIdName)
1312 return;
1313
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001314 std::string MethodName = MethodIdName->getName();
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001315 if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
Fariborz Jahanian9275c682013-08-02 20:54:18 +00001316 StringRef STRefMethodName(MethodName);
1317 size_t len = 0;
1318 if (STRefMethodName.startswith("standard"))
1319 len = strlen("standard");
1320 else if (STRefMethodName.startswith("shared"))
1321 len = strlen("shared");
1322 else if (STRefMethodName.startswith("default"))
1323 len = strlen("default");
1324 else
1325 return;
1326 MethodName = STRefMethodName.substr(len);
1327 }
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001328 std::string MethodNameSubStr = MethodName.substr(0, 3);
1329 StringRef MethodNamePrefix(MethodNameSubStr);
1330 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1331 MethodNamePrefix = StringLoweredMethodNamePrefix;
1332 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1333 if (Ix == StringRef::npos)
1334 return;
1335 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1336 StringRef LoweredMethodName(MethodName);
1337 std::string StringLoweredMethodName = LoweredMethodName.lower();
1338 LoweredMethodName = StringLoweredMethodName;
1339 if (!LoweredMethodName.startswith(ClassNamePostfix))
1340 return;
Fariborz Jahanian7c87b432013-10-10 18:23:13 +00001341 if (OIT_Family == OIT_ReturnsSelf)
1342 ReplaceWithClasstype(*this, OM);
1343 else
Argyrios Kyrtzidisc02a0db2014-05-21 00:24:20 +00001344 ReplaceWithInstancetype(Ctx, *this, OM);
Fariborz Jahanianc4291852013-08-02 18:00:53 +00001345}
1346
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001347static bool IsVoidStarType(QualType Ty) {
1348 if (!Ty->isPointerType())
1349 return false;
1350
1351 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1352 Ty = TD->getDecl()->getUnderlyingType();
1353
1354 // Is the type void*?
1355 const PointerType* PT = Ty->getAs<PointerType>();
1356 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1357 return true;
1358 return IsVoidStarType(PT->getPointeeType());
1359}
1360
Fariborz Jahanian94279392013-08-20 18:54:39 +00001361/// AuditedType - This routine audits the type AT and returns false if it is one of known
1362/// CF object types or of the "void *" variety. It returns true if we don't care about the type
1363/// such as a non-pointer or pointers which have no ownership issues (such as "int *").
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001364static bool AuditedType (QualType AT) {
1365 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001366 return true;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001367 // FIXME. There isn't much we can say about CF pointer type; or is there?
Fariborz Jahanian94279392013-08-20 18:54:39 +00001368 if (ento::coreFoundation::isCFObjectRef(AT) ||
1369 IsVoidStarType(AT) ||
1370 // If an ObjC object is type, assuming that it is not a CF function and
1371 // that it is an un-audited function.
Fariborz Jahanian2e9c19c2013-08-22 22:27:36 +00001372 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001373 return false;
Fariborz Jahanian94279392013-08-20 18:54:39 +00001374 // All other pointers are assumed audited as harmless.
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001375 return true;
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001376}
1377
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001378void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001379 if (CFFunctionIBCandidates.empty())
1380 return;
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001381 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) {
1382 CFFunctionIBCandidates.clear();
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001383 FileId = FileID();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001384 return;
1385 }
1386 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001387 const Decl *FirstFD = CFFunctionIBCandidates[0];
1388 const Decl *LastFD =
1389 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001390 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1391 edit::Commit commit(*Editor);
1392 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
1393 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1394 SourceLocation EndLoc = LastFD->getLocEnd();
1395 // get location just past end of function location.
1396 EndLoc = PP.getLocForEndOfToken(EndLoc);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001397 if (isa<FunctionDecl>(LastFD)) {
1398 // For Methods, EndLoc points to the ending semcolon. So,
1399 // not of these extra work is needed.
1400 Token Tok;
1401 // get locaiton of token that comes after end of function.
1402 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1403 if (!Failed)
1404 EndLoc = Tok.getLocation();
1405 }
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001406 commit.insertAfterToken(EndLoc, PragmaString);
1407 Editor->commit(commit);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001408 FileId = FileID();
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001409 CFFunctionIBCandidates.clear();
1410}
1411
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001412void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001413 if (Decl->isDeprecated())
1414 return;
1415
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001416 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001417 assert(CFFunctionIBCandidates.empty() &&
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001418 "Cannot have audited functions/methods inside user "
Fariborz Jahanianc6dfd3f2013-08-19 22:00:50 +00001419 "provided CF_IMPLICIT_BRIDGING_ENABLE");
1420 return;
1421 }
1422
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001423 // Finction must be annotated first.
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001424 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1425 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1426 if (AuditKind == CF_BRIDGING_ENABLE) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001427 CFFunctionIBCandidates.push_back(Decl);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001428 if (FileId.isInvalid())
1429 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001430 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001431 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1432 if (!CFFunctionIBCandidates.empty()) {
1433 CFFunctionIBCandidates.push_back(Decl);
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001434 if (FileId.isInvalid())
1435 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001436 }
1437 }
1438 else
1439 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001440 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001441 else {
1442 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001443 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001444 }
Fariborz Jahanian2ec4d7b2013-08-16 23:35:05 +00001445}
1446
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001447void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1448 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001449 const FunctionDecl *FuncDecl,
1450 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001451 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001452 if (!ResultAnnotated) {
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001453 RetEffect Ret = CE.getReturnValue();
Craig Topper8ae12032014-05-07 06:21:57 +00001454 const char *AnnotationString = nullptr;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001455 if (Ret.getObjKind() == RetEffect::CF) {
1456 if (Ret.isOwned() &&
1457 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001458 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001459 else if (Ret.notOwned() &&
1460 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001461 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1462 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001463 else if (Ret.getObjKind() == RetEffect::ObjC) {
1464 if (Ret.isOwned() &&
1465 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1466 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001467 }
1468
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001469 if (AnnotationString) {
1470 edit::Commit commit(*Editor);
1471 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1472 Editor->commit(commit);
1473 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001474 }
Craig Topper00bbdcf2014-06-28 23:22:23 +00001475 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001476 unsigned i = 0;
1477 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1478 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
Fariborz Jahanianb918d7a2013-08-21 19:37:47 +00001479 const ParmVarDecl *pd = *pi;
Fariborz Jahanian9ef4a262013-08-19 19:13:34 +00001480 ArgEffect AE = AEArgs[i];
Aaron Ballman9ead1242013-12-19 02:39:40 +00001481 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001482 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1483 edit::Commit commit(*Editor);
1484 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1485 Editor->commit(commit);
Fariborz Jahanian94279392013-08-20 18:54:39 +00001486 }
Aaron Ballman9ead1242013-12-19 02:39:40 +00001487 else if (AE == DecRefMsg && !pd->hasAttr<NSConsumedAttr>() &&
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001488 Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) {
1489 edit::Commit commit(*Editor);
1490 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1491 Editor->commit(commit);
1492 }
Fariborz Jahanian84ac1de2013-08-15 21:44:38 +00001493 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001494}
1495
1496
1497ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1498 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1499 ASTContext &Ctx,
1500 const FunctionDecl *FuncDecl) {
1501 if (FuncDecl->hasBody())
1502 return CF_BRIDGING_NONE;
1503
1504 CallEffects CE = CallEffects::getEffect(FuncDecl);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001505 bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() ||
1506 FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1507 FuncDecl->hasAttr<NSReturnsRetainedAttr>() ||
1508 FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1509 FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>());
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001510
1511 // Trivial case of when funciton is annotated and has no argument.
1512 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1513 return CF_BRIDGING_NONE;
1514
1515 bool ReturnCFAudited = false;
1516 if (!FuncIsReturnAnnotated) {
1517 RetEffect Ret = CE.getReturnValue();
1518 if (Ret.getObjKind() == RetEffect::CF &&
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001519 (Ret.isOwned() || Ret.notOwned()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001520 ReturnCFAudited = true;
Alp Toker314cc812014-01-25 16:55:45 +00001521 else if (!AuditedType(FuncDecl->getReturnType()))
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001522 return CF_BRIDGING_NONE;
1523 }
1524
1525 // At this point result type is audited for potential inclusion.
1526 // Now, how about argument types.
Craig Topper00bbdcf2014-06-28 23:22:23 +00001527 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001528 unsigned i = 0;
1529 bool ArgCFAudited = false;
1530 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1531 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1532 const ParmVarDecl *pd = *pi;
1533 ArgEffect AE = AEArgs[i];
1534 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
Aaron Ballman9ead1242013-12-19 02:39:40 +00001535 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>())
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001536 ArgCFAudited = true;
1537 else if (AE == IncRef)
1538 ArgCFAudited = true;
1539 }
1540 else {
1541 QualType AT = pd->getType();
1542 if (!AuditedType(AT)) {
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001543 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001544 return CF_BRIDGING_NONE;
1545 }
1546 }
1547 }
1548 if (ReturnCFAudited || ArgCFAudited)
1549 return CF_BRIDGING_ENABLE;
1550
1551 return CF_BRIDGING_MAY_INCLUDE;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001552}
1553
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001554void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1555 ObjCContainerDecl *CDecl) {
Fariborz Jahanian75226d52013-09-17 21:56:04 +00001556 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001557 return;
1558
1559 // migrate methods which can have instancetype as their result type.
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001560 for (const auto *Method : CDecl->methods())
Fariborz Jahanian4f64dd22013-08-22 21:40:15 +00001561 migrateCFAnnotation(Ctx, Method);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001562}
1563
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001564void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1565 const CallEffects &CE,
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001566 const ObjCMethodDecl *MethodDecl,
1567 bool ResultAnnotated) {
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001568 // Annotate function.
Fariborz Jahanian7ca1d302013-08-27 23:56:54 +00001569 if (!ResultAnnotated) {
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001570 RetEffect Ret = CE.getReturnValue();
Craig Topper8ae12032014-05-07 06:21:57 +00001571 const char *AnnotationString = nullptr;
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001572 if (Ret.getObjKind() == RetEffect::CF) {
1573 if (Ret.isOwned() &&
1574 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001575 AnnotationString = " CF_RETURNS_RETAINED";
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001576 else if (Ret.notOwned() &&
1577 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition())
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001578 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1579 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001580 else if (Ret.getObjKind() == RetEffect::ObjC) {
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001581 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1582 switch (OMF) {
1583 case clang::OMF_alloc:
1584 case clang::OMF_new:
1585 case clang::OMF_copy:
1586 case clang::OMF_init:
1587 case clang::OMF_mutableCopy:
1588 break;
1589
1590 default:
1591 if (Ret.isOwned() &&
1592 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition())
1593 AnnotationString = " NS_RETURNS_RETAINED";
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001594 break;
1595 }
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001596 }
1597
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001598 if (AnnotationString) {
1599 edit::Commit commit(*Editor);
1600 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1601 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001602 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001603 }
Craig Topper00bbdcf2014-06-28 23:22:23 +00001604 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001605 unsigned i = 0;
1606 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1607 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1608 const ParmVarDecl *pd = *pi;
1609 ArgEffect AE = AEArgs[i];
Aaron Ballman9ead1242013-12-19 02:39:40 +00001610 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001611 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) {
1612 edit::Commit commit(*Editor);
1613 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1614 Editor->commit(commit);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001615 }
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001616 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001617}
1618
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001619void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001620 ASTContext &Ctx,
1621 const ObjCMethodDecl *MethodDecl) {
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001622 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001623 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001624
1625 CallEffects CE = CallEffects::getEffect(MethodDecl);
Aaron Ballman9ead1242013-12-19 02:39:40 +00001626 bool MethodIsReturnAnnotated = (MethodDecl->hasAttr<CFReturnsRetainedAttr>() ||
1627 MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1628 MethodDecl->hasAttr<NSReturnsRetainedAttr>() ||
1629 MethodDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1630 MethodDecl->hasAttr<NSReturnsAutoreleasedAttr>());
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001631
1632 if (CE.getReceiver() == DecRefMsg &&
Aaron Ballman9ead1242013-12-19 02:39:40 +00001633 !MethodDecl->hasAttr<NSConsumesSelfAttr>() &&
Fariborz Jahanianc24879e2013-09-05 23:04:33 +00001634 MethodDecl->getMethodFamily() != OMF_init &&
1635 MethodDecl->getMethodFamily() != OMF_release &&
1636 Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) {
1637 edit::Commit commit(*Editor);
1638 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1639 Editor->commit(commit);
1640 }
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001641
1642 // Trivial case of when funciton is annotated and has no argument.
1643 if (MethodIsReturnAnnotated &&
1644 (MethodDecl->param_begin() == MethodDecl->param_end()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001645 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001646
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001647 if (!MethodIsReturnAnnotated) {
1648 RetEffect Ret = CE.getReturnValue();
Fariborz Jahanian1a269272013-09-04 22:49:19 +00001649 if ((Ret.getObjKind() == RetEffect::CF ||
1650 Ret.getObjKind() == RetEffect::ObjC) &&
1651 (Ret.isOwned() || Ret.notOwned())) {
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001652 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1653 return;
Alp Toker314cc812014-01-25 16:55:45 +00001654 } else if (!AuditedType(MethodDecl->getReturnType()))
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001655 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001656 }
1657
1658 // At this point result type is either annotated or audited.
1659 // Now, how about argument types.
Craig Topper00bbdcf2014-06-28 23:22:23 +00001660 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001661 unsigned i = 0;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001662 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1663 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1664 const ParmVarDecl *pd = *pi;
1665 ArgEffect AE = AEArgs[i];
Aaron Ballman9ead1242013-12-19 02:39:40 +00001666 if ((AE == DecRef && !pd->hasAttr<CFConsumedAttr>()) || AE == IncRef ||
Fariborz Jahanian8b102302013-09-04 16:43:57 +00001667 !AuditedType(pd->getType())) {
1668 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1669 return;
Fariborz Jahanian63ffce22013-08-27 22:42:30 +00001670 }
1671 }
Fariborz Jahanian89f6d102013-09-04 00:10:06 +00001672 return;
Fariborz Jahaniandfe6ed92013-08-12 23:17:13 +00001673}
1674
Ted Kremenekf7639e12012-03-06 20:06:33 +00001675namespace {
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001676class SuperInitChecker : public RecursiveASTVisitor<SuperInitChecker> {
1677public:
1678 bool shouldVisitTemplateInstantiations() const { return false; }
1679 bool shouldWalkTypesOfTypeLocs() const { return false; }
1680
1681 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
1682 if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
1683 if (E->getMethodFamily() == OMF_init)
1684 return false;
1685 }
1686 return true;
1687 }
1688};
1689} // anonymous namespace
1690
1691static bool hasSuperInitCall(const ObjCMethodDecl *MD) {
1692 return !SuperInitChecker().TraverseStmt(MD->getBody());
1693}
1694
1695void ObjCMigrateASTConsumer::inferDesignatedInitializers(
1696 ASTContext &Ctx,
1697 const ObjCImplementationDecl *ImplD) {
1698
1699 const ObjCInterfaceDecl *IFace = ImplD->getClassInterface();
1700 if (!IFace || IFace->hasDesignatedInitializers())
1701 return;
1702 if (!Ctx.Idents.get("NS_DESIGNATED_INITIALIZER").hasMacroDefinition())
1703 return;
1704
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001705 for (const auto *MD : ImplD->instance_methods()) {
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001706 if (MD->isDeprecated() ||
1707 MD->getMethodFamily() != OMF_init ||
1708 MD->isDesignatedInitializerForTheInterface())
1709 continue;
1710 const ObjCMethodDecl *IFaceM = IFace->getMethod(MD->getSelector(),
1711 /*isInstance=*/true);
1712 if (!IFaceM)
1713 continue;
1714 if (hasSuperInitCall(MD)) {
1715 edit::Commit commit(*Editor);
1716 commit.insert(IFaceM->getLocEnd(), " NS_DESIGNATED_INITIALIZER");
1717 Editor->commit(commit);
1718 }
1719 }
1720}
1721
Fariborz Jahanian80ebf8d2014-10-07 19:01:46 +00001722bool ObjCMigrateASTConsumer::InsertFoundation(ASTContext &Ctx,
1723 SourceLocation Loc) {
1724 if (FoundationIncluded)
1725 return true;
1726 if (Loc.isInvalid())
1727 return false;
1728 edit::Commit commit(*Editor);
1729 if (Ctx.getLangOpts().Modules)
1730 commit.insert(Loc, "@import Foundation;\n");
1731 else
1732 commit.insert(Loc, "#import <Foundation/Foundation.h>\n");
1733 Editor->commit(commit);
1734 FoundationIncluded = true;
1735 return true;
1736}
1737
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001738namespace {
Ted Kremenekf7639e12012-03-06 20:06:33 +00001739
1740class RewritesReceiver : public edit::EditsReceiver {
1741 Rewriter &Rewrite;
1742
1743public:
1744 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1745
Craig Topperb45acb82014-03-14 06:02:07 +00001746 void insert(SourceLocation loc, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +00001747 Rewrite.InsertText(loc, text);
1748 }
Craig Topperb45acb82014-03-14 06:02:07 +00001749 void replace(CharSourceRange range, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +00001750 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1751 }
1752};
1753
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001754class JSONEditWriter : public edit::EditsReceiver {
1755 SourceManager &SourceMgr;
1756 llvm::raw_ostream &OS;
1757
1758public:
1759 JSONEditWriter(SourceManager &SM, llvm::raw_ostream &OS)
1760 : SourceMgr(SM), OS(OS) {
1761 OS << "[\n";
1762 }
1763 ~JSONEditWriter() {
1764 OS << "]\n";
1765 }
1766
1767private:
1768 struct EntryWriter {
1769 SourceManager &SourceMgr;
1770 llvm::raw_ostream &OS;
1771
1772 EntryWriter(SourceManager &SM, llvm::raw_ostream &OS)
1773 : SourceMgr(SM), OS(OS) {
1774 OS << " {\n";
1775 }
1776 ~EntryWriter() {
1777 OS << " },\n";
1778 }
1779
1780 void writeLoc(SourceLocation Loc) {
1781 FileID FID;
1782 unsigned Offset;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00001783 std::tie(FID, Offset) = SourceMgr.getDecomposedLoc(Loc);
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001784 assert(!FID.isInvalid());
1785 SmallString<200> Path =
1786 StringRef(SourceMgr.getFileEntryForID(FID)->getName());
1787 llvm::sys::fs::make_absolute(Path);
1788 OS << " \"file\": \"";
1789 OS.write_escaped(Path.str()) << "\",\n";
1790 OS << " \"offset\": " << Offset << ",\n";
1791 }
1792
1793 void writeRemove(CharSourceRange Range) {
1794 assert(Range.isCharRange());
1795 std::pair<FileID, unsigned> Begin =
1796 SourceMgr.getDecomposedLoc(Range.getBegin());
1797 std::pair<FileID, unsigned> End =
1798 SourceMgr.getDecomposedLoc(Range.getEnd());
1799 assert(Begin.first == End.first);
1800 assert(Begin.second <= End.second);
1801 unsigned Length = End.second - Begin.second;
1802
1803 OS << " \"remove\": " << Length << ",\n";
1804 }
1805
1806 void writeText(StringRef Text) {
1807 OS << " \"text\": \"";
1808 OS.write_escaped(Text) << "\",\n";
1809 }
1810 };
1811
Craig Topperb45acb82014-03-14 06:02:07 +00001812 void insert(SourceLocation Loc, StringRef Text) override {
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001813 EntryWriter Writer(SourceMgr, OS);
1814 Writer.writeLoc(Loc);
1815 Writer.writeText(Text);
1816 }
1817
Craig Topperb45acb82014-03-14 06:02:07 +00001818 void replace(CharSourceRange Range, StringRef Text) override {
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001819 EntryWriter Writer(SourceMgr, OS);
1820 Writer.writeLoc(Range.getBegin());
1821 Writer.writeRemove(Range);
1822 Writer.writeText(Text);
1823 }
1824
Craig Topperb45acb82014-03-14 06:02:07 +00001825 void remove(CharSourceRange Range) override {
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001826 EntryWriter Writer(SourceMgr, OS);
1827 Writer.writeLoc(Range.getBegin());
1828 Writer.writeRemove(Range);
1829 }
1830};
1831
Ted Kremenekf7639e12012-03-06 20:06:33 +00001832}
1833
1834void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001835
1836 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
Fariborz Jahanianc1213862013-10-02 21:32:39 +00001837 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001838 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1839 D != DEnd; ++D) {
Argyrios Kyrtzidis3e8547a2013-11-13 18:20:31 +00001840 FileID FID = PP.getSourceManager().getFileID((*D)->getLocation());
1841 if (!FID.isInvalid())
1842 if (!FileId.isInvalid() && FileId != FID) {
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001843 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1844 AnnotateImplicitBridging(Ctx);
1845 }
1846
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001847 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001848 if (canModify(CDecl))
1849 migrateObjCInterfaceDecl(Ctx, CDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001850 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001851 if (canModify(CatDecl))
1852 migrateObjCInterfaceDecl(Ctx, CatDecl);
Fariborz Jahanian9d2ffea2013-10-31 00:06:58 +00001853 }
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001854 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D))
Fariborz Jahanian769c04e2013-12-17 01:01:33 +00001855 ObjCProtocolDecls.insert(PDecl->getCanonicalDecl());
Fariborz Jahanian1be01532013-07-12 22:32:19 +00001856 else if (const ObjCImplementationDecl *ImpDecl =
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001857 dyn_cast<ObjCImplementationDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001858 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) &&
1859 canModify(ImpDecl))
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001860 migrateProtocolConformance(Ctx, ImpDecl);
1861 }
Fariborz Jahanian92463272013-07-18 20:11:45 +00001862 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001863 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1864 continue;
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001865 if (!canModify(ED))
1866 continue;
Fariborz Jahanian92463272013-07-18 20:11:45 +00001867 DeclContext::decl_iterator N = D;
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001868 if (++N != DEnd) {
1869 const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
1870 if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
1871 D++;
1872 }
1873 else
Craig Topper8ae12032014-05-07 06:21:57 +00001874 migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */nullptr);
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001875 }
1876 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001877 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1878 continue;
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001879 if (!canModify(TD))
1880 continue;
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001881 DeclContext::decl_iterator N = D;
1882 if (++N == DEnd)
1883 continue;
1884 if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001885 if (++N != DEnd)
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001886 if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) {
1887 // prefer typedef-follows-enum to enum-follows-typedef pattern.
1888 if (migrateNSEnumDecl(Ctx, ED, TDF)) {
1889 ++D; ++D;
1890 CacheObjCNSIntegerTypedefed(TD);
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001891 continue;
1892 }
Fariborz Jahanian11dd4b12013-10-11 21:34:56 +00001893 }
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001894 if (migrateNSEnumDecl(Ctx, ED, TD)) {
1895 ++D;
1896 continue;
1897 }
Fariborz Jahanian059e05e2013-10-15 00:00:28 +00001898 }
Fariborz Jahanian403425b2013-10-17 23:13:13 +00001899 CacheObjCNSIntegerTypedefed(TD);
Fariborz Jahanian92463272013-07-18 20:11:45 +00001900 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001901 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001902 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1903 canModify(FD))
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001904 migrateCFAnnotation(Ctx, FD);
1905 }
Fariborz Jahanianc13c1b02013-08-13 18:01:42 +00001906
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001907 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001908 bool CanModify = canModify(CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001909 // migrate methods which can have instancetype as their result type.
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001910 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) &&
1911 CanModify)
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001912 migrateAllMethodInstaceType(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001913 // annotate methods with CF annotations.
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001914 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1915 CanModify)
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001916 migrateARCSafeAnnotation(Ctx, CDecl);
Fariborz Jahanian926fafb2013-08-22 18:35:27 +00001917 }
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001918
1919 if (const ObjCImplementationDecl *
1920 ImplD = dyn_cast<ObjCImplementationDecl>(*D)) {
Argyrios Kyrtzidis3f729342013-12-11 21:39:00 +00001921 if ((ASTMigrateActions & FrontendOptions::ObjCMT_DesignatedInitializer) &&
1922 canModify(ImplD))
Argyrios Kyrtzidis4f2ecc62013-12-10 18:36:49 +00001923 inferDesignatedInitializers(Ctx, ImplD);
1924 }
Fariborz Jahaniand83ef842013-07-09 16:59:14 +00001925 }
Fariborz Jahanian8c45e282013-10-02 22:49:59 +00001926 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1927 AnnotateImplicitBridging(Ctx);
Fariborz Jahanian301b5212013-08-20 22:42:13 +00001928 }
Fariborz Jahaniana7437f02013-07-03 23:05:00 +00001929
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001930 if (IsOutputFile) {
Rafael Espindoladae941a2014-08-25 18:17:04 +00001931 std::error_code EC;
1932 llvm::raw_fd_ostream OS(MigrateDir, EC, llvm::sys::fs::F_None);
1933 if (EC) {
Alp Toker29cb66b2014-01-26 06:17:37 +00001934 DiagnosticsEngine &Diags = Ctx.getDiagnostics();
1935 Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
Rafael Espindoladae941a2014-08-25 18:17:04 +00001936 << EC.message();
Hans Wennborgbf6dda52013-12-12 02:24:20 +00001937 return;
1938 }
1939
1940 JSONEditWriter Writer(Ctx.getSourceManager(), OS);
1941 Editor->applyRewrites(Writer);
1942 return;
1943 }
1944
David Blaikiebbafb8a2012-03-11 07:00:24 +00001945 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001946 RewritesReceiver Rec(rewriter);
1947 Editor->applyRewrites(Rec);
1948
1949 for (Rewriter::buffer_iterator
1950 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1951 FileID FID = I->first;
1952 RewriteBuffer &buf = I->second;
1953 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1954 assert(file);
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001955 SmallString<512> newText;
Ted Kremenekf7639e12012-03-06 20:06:33 +00001956 llvm::raw_svector_ostream vecOS(newText);
1957 buf.write(vecOS);
1958 vecOS.flush();
Rafael Espindola1a1b1562014-08-17 23:12:27 +00001959 std::unique_ptr<llvm::MemoryBuffer> memBuf(
1960 llvm::MemoryBuffer::getMemBufferCopy(
1961 StringRef(newText.data(), newText.size()), file->getName()));
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001962 SmallString<64> filePath(file->getName());
Ted Kremenekf7639e12012-03-06 20:06:33 +00001963 FileMgr.FixupRelativePath(filePath);
Rafael Espindola1a1b1562014-08-17 23:12:27 +00001964 Remapper.remap(filePath.str(), std::move(memBuf));
Ted Kremenekf7639e12012-03-06 20:06:33 +00001965 }
1966
1967 if (IsOutputFile) {
1968 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1969 } else {
1970 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1971 }
1972}
1973
1974bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
Argyrios Kyrtzidisb4822602012-05-24 16:48:23 +00001975 CI.getDiagnostics().setIgnoreAllWarnings(true);
Ted Kremenekf7639e12012-03-06 20:06:33 +00001976 return true;
1977}
1978
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00001979static std::vector<std::string> getWhiteListFilenames(StringRef DirPath) {
1980 using namespace llvm::sys::fs;
1981 using namespace llvm::sys::path;
1982
1983 std::vector<std::string> Filenames;
1984 if (DirPath.empty() || !is_directory(DirPath))
1985 return Filenames;
Rafael Espindolac0809172014-06-12 14:02:15 +00001986
1987 std::error_code EC;
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00001988 directory_iterator DI = directory_iterator(DirPath, EC);
1989 directory_iterator DE;
1990 for (; !EC && DI != DE; DI = DI.increment(EC)) {
1991 if (is_regular_file(DI->path()))
1992 Filenames.push_back(filename(DI->path()));
1993 }
1994
1995 return Filenames;
1996}
1997
David Blaikie6beb6aa2014-08-10 19:56:51 +00001998std::unique_ptr<ASTConsumer>
1999MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00002000 PPConditionalDirectiveRecord *
2001 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
Argyrios Kyrtzidisee02a8a2013-11-13 23:38:22 +00002002 unsigned ObjCMTAction = CI.getFrontendOpts().ObjCMTAction;
Argyrios Kyrtzidisc47c63b2013-11-14 16:33:20 +00002003 unsigned ObjCMTOpts = ObjCMTAction;
2004 // These are companion flags, they do not enable transformations.
2005 ObjCMTOpts &= ~(FrontendOptions::ObjCMT_AtomicProperty |
2006 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty);
2007 if (ObjCMTOpts == FrontendOptions::ObjCMT_None) {
Argyrios Kyrtzidisee02a8a2013-11-13 23:38:22 +00002008 // If no specific option was given, enable literals+subscripting transforms
2009 // by default.
Argyrios Kyrtzidisc47c63b2013-11-14 16:33:20 +00002010 ObjCMTAction |= FrontendOptions::ObjCMT_Literals |
2011 FrontendOptions::ObjCMT_Subscripting;
Argyrios Kyrtzidisee02a8a2013-11-13 23:38:22 +00002012 }
Craig Topperb8a70532014-09-10 04:53:53 +00002013 CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
Argyrios Kyrtzidis61f20322013-11-14 16:33:29 +00002014 std::vector<std::string> WhiteList =
2015 getWhiteListFilenames(CI.getFrontendOpts().ObjCMTWhiteListPath);
David Blaikie6beb6aa2014-08-10 19:56:51 +00002016 return llvm::make_unique<ObjCMigrateASTConsumer>(
2017 CI.getFrontendOpts().OutputFile, ObjCMTAction, Remapper,
2018 CI.getFileManager(), PPRec, CI.getPreprocessor(),
2019 /*isOutputFile=*/true, WhiteList);
Ted Kremenekf7639e12012-03-06 20:06:33 +00002020}
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002021
2022namespace {
2023struct EditEntry {
2024 const FileEntry *File;
2025 unsigned Offset;
2026 unsigned RemoveLen;
2027 std::string Text;
2028
2029 EditEntry() : File(), Offset(), RemoveLen() {}
2030};
2031}
2032
2033namespace llvm {
2034template<> struct DenseMapInfo<EditEntry> {
2035 static inline EditEntry getEmptyKey() {
2036 EditEntry Entry;
2037 Entry.Offset = unsigned(-1);
2038 return Entry;
2039 }
2040 static inline EditEntry getTombstoneKey() {
2041 EditEntry Entry;
2042 Entry.Offset = unsigned(-2);
2043 return Entry;
2044 }
2045 static unsigned getHashValue(const EditEntry& Val) {
2046 llvm::FoldingSetNodeID ID;
2047 ID.AddPointer(Val.File);
2048 ID.AddInteger(Val.Offset);
2049 ID.AddInteger(Val.RemoveLen);
2050 ID.AddString(Val.Text);
2051 return ID.ComputeHash();
2052 }
2053 static bool isEqual(const EditEntry &LHS, const EditEntry &RHS) {
2054 return LHS.File == RHS.File &&
2055 LHS.Offset == RHS.Offset &&
2056 LHS.RemoveLen == RHS.RemoveLen &&
2057 LHS.Text == RHS.Text;
2058 }
2059};
2060}
2061
2062namespace {
2063class RemapFileParser {
2064 FileManager &FileMgr;
2065
2066public:
2067 RemapFileParser(FileManager &FileMgr) : FileMgr(FileMgr) { }
2068
2069 bool parse(StringRef File, SmallVectorImpl<EditEntry> &Entries) {
2070 using namespace llvm::yaml;
2071
Rafael Espindola2d2b4202014-07-06 17:43:24 +00002072 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
2073 llvm::MemoryBuffer::getFile(File);
2074 if (!FileBufOrErr)
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002075 return true;
2076
2077 llvm::SourceMgr SM;
Rafael Espindola85d78922014-08-27 19:03:27 +00002078 Stream YAMLStream(FileBufOrErr.get()->getMemBufferRef(), SM);
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002079 document_iterator I = YAMLStream.begin();
2080 if (I == YAMLStream.end())
2081 return true;
2082 Node *Root = I->getRoot();
2083 if (!Root)
2084 return true;
2085
2086 SequenceNode *SeqNode = dyn_cast<SequenceNode>(Root);
2087 if (!SeqNode)
2088 return true;
2089
2090 for (SequenceNode::iterator
2091 AI = SeqNode->begin(), AE = SeqNode->end(); AI != AE; ++AI) {
2092 MappingNode *MapNode = dyn_cast<MappingNode>(&*AI);
2093 if (!MapNode)
2094 continue;
2095 parseEdit(MapNode, Entries);
2096 }
2097
2098 return false;
2099 }
2100
2101private:
2102 void parseEdit(llvm::yaml::MappingNode *Node,
2103 SmallVectorImpl<EditEntry> &Entries) {
2104 using namespace llvm::yaml;
2105 EditEntry Entry;
2106 bool Ignore = false;
2107
2108 for (MappingNode::iterator
2109 KVI = Node->begin(), KVE = Node->end(); KVI != KVE; ++KVI) {
2110 ScalarNode *KeyString = dyn_cast<ScalarNode>((*KVI).getKey());
2111 if (!KeyString)
2112 continue;
2113 SmallString<10> KeyStorage;
2114 StringRef Key = KeyString->getValue(KeyStorage);
2115
2116 ScalarNode *ValueString = dyn_cast<ScalarNode>((*KVI).getValue());
2117 if (!ValueString)
2118 continue;
2119 SmallString<64> ValueStorage;
2120 StringRef Val = ValueString->getValue(ValueStorage);
2121
2122 if (Key == "file") {
2123 const FileEntry *FE = FileMgr.getFile(Val);
2124 if (!FE)
2125 Ignore = true;
2126 Entry.File = FE;
2127 } else if (Key == "offset") {
2128 if (Val.getAsInteger(10, Entry.Offset))
2129 Ignore = true;
2130 } else if (Key == "remove") {
2131 if (Val.getAsInteger(10, Entry.RemoveLen))
2132 Ignore = true;
2133 } else if (Key == "text") {
2134 Entry.Text = Val;
2135 }
2136 }
2137
2138 if (!Ignore)
2139 Entries.push_back(Entry);
2140 }
2141};
2142}
2143
2144static bool reportDiag(const Twine &Err, DiagnosticsEngine &Diag) {
Alp Toker29cb66b2014-01-26 06:17:37 +00002145 Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
2146 << Err.str();
Hans Wennborgbf6dda52013-12-12 02:24:20 +00002147 return true;
2148}
2149
2150static std::string applyEditsToTemp(const FileEntry *FE,
2151 ArrayRef<EditEntry> Edits,
2152 FileManager &FileMgr,
2153 DiagnosticsEngine &Diag) {
2154 using namespace llvm::sys;
2155
2156 SourceManager SM(Diag, FileMgr);
2157 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
2158 LangOptions LangOpts;
2159 edit::EditedSource Editor(SM, LangOpts);
2160 for (ArrayRef<EditEntry>::iterator
2161 I = Edits.begin(), E = Edits.end(); I != E; ++I) {
2162 const EditEntry &Entry = *I;
2163 assert(Entry.File == FE);
2164 SourceLocation Loc =
2165 SM.getLocForStartOfFile(FID).getLocWithOffset(Entry.Offset);
2166 CharSourceRange Range;
2167 if (Entry.RemoveLen != 0) {
2168 Range = CharSourceRange::getCharRange(Loc,
2169 Loc.getLocWithOffset(Entry.RemoveLen));
2170 }
2171
2172 edit::Commit commit(Editor);
2173 if (Range.isInvalid()) {
2174 commit.insert(Loc, Entry.Text);
2175 } else if (Entry.Text.empty()) {
2176 commit.remove(Range);
2177 } else {
2178 commit.replace(Range, Entry.Text);
2179 }
2180 Editor.commit(commit);
2181 }
2182
2183 Rewriter rewriter(SM, LangOpts);
2184 RewritesReceiver Rec(rewriter);
2185 Editor.applyRewrites(Rec);
2186
2187 const RewriteBuffer *Buf = rewriter.getRewriteBufferFor(FID);
2188 SmallString<512> NewText;
2189 llvm::raw_svector_ostream OS(NewText);
2190 Buf->write(OS);
2191 OS.flush();
2192
2193 SmallString<64> TempPath;
2194 int FD;
2195 if (fs::createTemporaryFile(path::filename(FE->getName()),
2196 path::extension(FE->getName()), FD,
2197 TempPath)) {
2198 reportDiag("Could not create file: " + TempPath.str(), Diag);
2199 return std::string();
2200 }
2201
2202 llvm::raw_fd_ostream TmpOut(FD, /*shouldClose=*/true);
2203 TmpOut.write(NewText.data(), NewText.size());
2204 TmpOut.close();
2205
2206 return TempPath.str();
2207}
2208
2209bool arcmt::getFileRemappingsFromFileList(
2210 std::vector<std::pair<std::string,std::string> > &remap,
2211 ArrayRef<StringRef> remapFiles,
2212 DiagnosticConsumer *DiagClient) {
2213 bool hasErrorOccurred = false;
2214
2215 FileSystemOptions FSOpts;
2216 FileManager FileMgr(FSOpts);
2217 RemapFileParser Parser(FileMgr);
2218
2219 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
2220 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
2221 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
2222 DiagClient, /*ShouldOwnClient=*/false));
2223
2224 typedef llvm::DenseMap<const FileEntry *, std::vector<EditEntry> >
2225 FileEditEntriesTy;
2226 FileEditEntriesTy FileEditEntries;
2227
2228 llvm::DenseSet<EditEntry> EntriesSet;
2229
2230 for (ArrayRef<StringRef>::iterator
2231 I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
2232 SmallVector<EditEntry, 16> Entries;
2233 if (Parser.parse(*I, Entries))
2234 continue;
2235
2236 for (SmallVectorImpl<EditEntry>::iterator
2237 EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) {
2238 EditEntry &Entry = *EI;
2239 if (!Entry.File)
2240 continue;
2241 std::pair<llvm::DenseSet<EditEntry>::iterator, bool>
2242 Insert = EntriesSet.insert(Entry);
2243 if (!Insert.second)
2244 continue;
2245
2246 FileEditEntries[Entry.File].push_back(Entry);
2247 }
2248 }
2249
2250 for (FileEditEntriesTy::iterator
2251 I = FileEditEntries.begin(), E = FileEditEntries.end(); I != E; ++I) {
2252 std::string TempFile = applyEditsToTemp(I->first, I->second,
2253 FileMgr, *Diags);
2254 if (TempFile.empty()) {
2255 hasErrorOccurred = true;
2256 continue;
2257 }
2258
2259 remap.push_back(std::make_pair(I->first->getName(), TempFile));
2260 }
2261
2262 return hasErrorOccurred;
2263}