/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/ARCMigrate/ObjCMT.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===// |
2 | | // |
3 | | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | | // See https://llvm.org/LICENSE.txt for license information. |
5 | | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | | // |
7 | | //===----------------------------------------------------------------------===// |
8 | | |
9 | | #include "Transforms.h" |
10 | | #include "clang/Analysis/RetainSummaryManager.h" |
11 | | #include "clang/ARCMigrate/ARCMT.h" |
12 | | #include "clang/ARCMigrate/ARCMTActions.h" |
13 | | #include "clang/AST/ASTConsumer.h" |
14 | | #include "clang/AST/ASTContext.h" |
15 | | #include "clang/AST/Attr.h" |
16 | | #include "clang/AST/NSAPI.h" |
17 | | #include "clang/AST/ParentMap.h" |
18 | | #include "clang/AST/RecursiveASTVisitor.h" |
19 | | #include "clang/Analysis/DomainSpecific/CocoaConventions.h" |
20 | | #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" |
25 | | #include "clang/Frontend/CompilerInstance.h" |
26 | | #include "clang/Frontend/MultiplexConsumer.h" |
27 | | #include "clang/Lex/PPConditionalDirectiveRecord.h" |
28 | | #include "clang/Lex/Preprocessor.h" |
29 | | #include "clang/Rewrite/Core/Rewriter.h" |
30 | | #include "llvm/ADT/SmallString.h" |
31 | | #include "llvm/ADT/StringSet.h" |
32 | | #include "llvm/Support/Path.h" |
33 | | #include "llvm/Support/SourceMgr.h" |
34 | | #include "llvm/Support/YAMLParser.h" |
35 | | |
36 | | using namespace clang; |
37 | | using namespace arcmt; |
38 | | using namespace ento; |
39 | | |
40 | | namespace { |
41 | | |
42 | | class ObjCMigrateASTConsumer : public ASTConsumer { |
43 | | enum CF_BRIDGING_KIND { |
44 | | CF_BRIDGING_NONE, |
45 | | CF_BRIDGING_ENABLE, |
46 | | CF_BRIDGING_MAY_INCLUDE |
47 | | }; |
48 | | |
49 | | void migrateDecl(Decl *D); |
50 | | void migrateObjCContainerDecl(ASTContext &Ctx, ObjCContainerDecl *D); |
51 | | void migrateProtocolConformance(ASTContext &Ctx, |
52 | | const ObjCImplementationDecl *ImpDecl); |
53 | | void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl); |
54 | | bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl, |
55 | | const TypedefDecl *TypedefDcl); |
56 | | void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl); |
57 | | void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl, |
58 | | ObjCMethodDecl *OM); |
59 | | bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM); |
60 | | void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM); |
61 | | void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P); |
62 | | void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl, |
63 | | ObjCMethodDecl *OM, |
64 | | ObjCInstanceTypeFamily OIT_Family = OIT_None); |
65 | | |
66 | | void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl); |
67 | | void AddCFAnnotations(ASTContext &Ctx, |
68 | | const RetainSummary *RS, |
69 | | const FunctionDecl *FuncDecl, bool ResultAnnotated); |
70 | | void AddCFAnnotations(ASTContext &Ctx, |
71 | | const RetainSummary *RS, |
72 | | const ObjCMethodDecl *MethodDecl, bool ResultAnnotated); |
73 | | |
74 | | void AnnotateImplicitBridging(ASTContext &Ctx); |
75 | | |
76 | | CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx, |
77 | | const FunctionDecl *FuncDecl); |
78 | | |
79 | | void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl); |
80 | | |
81 | | void migrateAddMethodAnnotation(ASTContext &Ctx, |
82 | | const ObjCMethodDecl *MethodDecl); |
83 | | |
84 | | void inferDesignatedInitializers(ASTContext &Ctx, |
85 | | const ObjCImplementationDecl *ImplD); |
86 | | |
87 | | bool InsertFoundation(ASTContext &Ctx, SourceLocation Loc); |
88 | | |
89 | | std::unique_ptr<RetainSummaryManager> Summaries; |
90 | | |
91 | | public: |
92 | | std::string MigrateDir; |
93 | | unsigned ASTMigrateActions; |
94 | | FileID FileId; |
95 | | const TypedefDecl *NSIntegerTypedefed; |
96 | | const TypedefDecl *NSUIntegerTypedefed; |
97 | | std::unique_ptr<NSAPI> NSAPIObj; |
98 | | std::unique_ptr<edit::EditedSource> Editor; |
99 | | FileRemapper &Remapper; |
100 | | FileManager &FileMgr; |
101 | | const PPConditionalDirectiveRecord *PPRec; |
102 | | Preprocessor &PP; |
103 | | bool IsOutputFile; |
104 | | bool FoundationIncluded; |
105 | | llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls; |
106 | | llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates; |
107 | | llvm::StringSet<> AllowListFilenames; |
108 | | |
109 | 184 | RetainSummaryManager &getSummaryManager(ASTContext &Ctx) { |
110 | 184 | if (!Summaries) |
111 | 3 | Summaries.reset(new RetainSummaryManager(Ctx, |
112 | 3 | /*TrackNSCFObjects=*/true, |
113 | 3 | /*trackOSObjects=*/false)); |
114 | 184 | return *Summaries; |
115 | 184 | } |
116 | | |
117 | | ObjCMigrateASTConsumer(StringRef migrateDir, unsigned astMigrateActions, |
118 | | FileRemapper &remapper, FileManager &fileMgr, |
119 | | const PPConditionalDirectiveRecord *PPRec, |
120 | | Preprocessor &PP, bool isOutputFile, |
121 | | ArrayRef<std::string> AllowList) |
122 | | : MigrateDir(migrateDir), ASTMigrateActions(astMigrateActions), |
123 | | NSIntegerTypedefed(nullptr), NSUIntegerTypedefed(nullptr), |
124 | | Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP), |
125 | 29 | IsOutputFile(isOutputFile), FoundationIncluded(false) { |
126 | | // FIXME: StringSet should have insert(iter, iter) to use here. |
127 | 29 | for (const std::string &Val : AllowList) |
128 | 2 | AllowListFilenames.insert(Val); |
129 | 29 | } |
130 | | |
131 | | protected: |
132 | 29 | void Initialize(ASTContext &Context) override { |
133 | 29 | NSAPIObj.reset(new NSAPI(Context)); |
134 | 29 | Editor.reset(new edit::EditedSource(Context.getSourceManager(), |
135 | 29 | Context.getLangOpts(), |
136 | 29 | PPRec)); |
137 | 29 | } |
138 | | |
139 | 828 | bool HandleTopLevelDecl(DeclGroupRef DG) override { |
140 | 1.84k | for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I1.02k ) |
141 | 1.02k | migrateDecl(*I); |
142 | 828 | return true; |
143 | 828 | } |
144 | 3 | void HandleInterestingDecl(DeclGroupRef DG) override { |
145 | | // Ignore decls from the PCH. |
146 | 3 | } |
147 | 1 | void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) override { |
148 | 1 | ObjCMigrateASTConsumer::HandleTopLevelDecl(DG); |
149 | 1 | } |
150 | | |
151 | | void HandleTranslationUnit(ASTContext &Ctx) override; |
152 | | |
153 | 860 | bool canModifyFile(StringRef Path) { |
154 | 860 | if (AllowListFilenames.empty()) |
155 | 841 | return true; |
156 | 19 | return AllowListFilenames.find(llvm::sys::path::filename(Path)) != |
157 | 19 | AllowListFilenames.end(); |
158 | 860 | } |
159 | 866 | bool canModifyFile(Optional<FileEntryRef> FE) { |
160 | 866 | if (!FE) |
161 | 6 | return false; |
162 | 860 | return canModifyFile(FE->getName()); |
163 | 866 | } |
164 | 954 | bool canModifyFile(FileID FID) { |
165 | 954 | if (FID.isInvalid()) |
166 | 88 | return false; |
167 | 866 | return canModifyFile(PP.getSourceManager().getFileEntryRefForID(FID)); |
168 | 954 | } |
169 | | |
170 | 1.00k | bool canModify(const Decl *D) { |
171 | 1.00k | if (!D) |
172 | 0 | return false; |
173 | 1.00k | if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(D)) |
174 | 3 | return canModify(CatImpl->getCategoryDecl()); |
175 | 1.00k | if (const ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) |
176 | 48 | return canModify(Impl->getClassInterface()); |
177 | 954 | if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) |
178 | 0 | return canModify(cast<Decl>(MD->getDeclContext())); |
179 | | |
180 | 954 | FileID FID = PP.getSourceManager().getFileID(D->getLocation()); |
181 | 954 | return canModifyFile(FID); |
182 | 954 | } |
183 | | }; |
184 | | |
185 | | } // end anonymous namespace |
186 | | |
187 | | ObjCMigrateAction::ObjCMigrateAction( |
188 | | std::unique_ptr<FrontendAction> WrappedAction, StringRef migrateDir, |
189 | | unsigned migrateAction) |
190 | | : WrapperFrontendAction(std::move(WrappedAction)), MigrateDir(migrateDir), |
191 | 21 | ObjCMigAction(migrateAction), CompInst(nullptr) { |
192 | 21 | if (MigrateDir.empty()) |
193 | 0 | MigrateDir = "."; // user current directory if none is given. |
194 | 21 | } |
195 | | |
196 | | std::unique_ptr<ASTConsumer> |
197 | 21 | ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
198 | 21 | PPConditionalDirectiveRecord * |
199 | 21 | PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager()); |
200 | 21 | CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec)); |
201 | 21 | std::vector<std::unique_ptr<ASTConsumer>> Consumers; |
202 | 21 | Consumers.push_back(WrapperFrontendAction::CreateASTConsumer(CI, InFile)); |
203 | 21 | Consumers.push_back(std::make_unique<ObjCMigrateASTConsumer>( |
204 | 21 | MigrateDir, ObjCMigAction, Remapper, CompInst->getFileManager(), PPRec, |
205 | 21 | CompInst->getPreprocessor(), false, None)); |
206 | 21 | return std::make_unique<MultiplexConsumer>(std::move(Consumers)); |
207 | 21 | } |
208 | | |
209 | 21 | bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) { |
210 | 21 | Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(), |
211 | 21 | /*ignoreIfFilesChanged=*/true); |
212 | 21 | CompInst = &CI; |
213 | 21 | CI.getDiagnostics().setIgnoreAllWarnings(true); |
214 | 21 | return true; |
215 | 21 | } |
216 | | |
217 | | namespace { |
218 | | // FIXME. This duplicates one in RewriteObjCFoundationAPI.cpp |
219 | 33 | bool subscriptOperatorNeedsParens(const Expr *FullExpr) { |
220 | 33 | const Expr* Expr = FullExpr->IgnoreImpCasts(); |
221 | 33 | return !(isa<ArraySubscriptExpr>(Expr) || isa<CallExpr>(Expr) || |
222 | 33 | isa<DeclRefExpr>(Expr)31 || isa<CXXNamedCastExpr>(Expr)22 || |
223 | 33 | isa<CXXConstructExpr>(Expr)22 || isa<CXXThisExpr>(Expr)22 || |
224 | 33 | isa<CXXTypeidExpr>(Expr)22 || |
225 | 33 | isa<CXXUnresolvedConstructExpr>(Expr)22 || |
226 | 33 | isa<ObjCMessageExpr>(Expr)22 || isa<ObjCPropertyRefExpr>(Expr)18 || |
227 | 33 | isa<ObjCProtocolExpr>(Expr)18 || isa<MemberExpr>(Expr)18 || |
228 | 33 | isa<ObjCIvarRefExpr>(Expr)18 || isa<ParenExpr>(FullExpr)3 || |
229 | 33 | isa<ParenListExpr>(Expr)3 || isa<SizeOfPackExpr>(Expr)3 ); |
230 | 33 | } |
231 | | |
232 | | /// - Rewrite message expression for Objective-C setter and getters into |
233 | | /// property-dot syntax. |
234 | | bool rewriteToPropertyDotSyntax(const ObjCMessageExpr *Msg, |
235 | | Preprocessor &PP, |
236 | | const NSAPI &NS, edit::Commit &commit, |
237 | 42 | const ParentMap *PMap) { |
238 | 42 | if (!Msg || Msg->isImplicit() || |
239 | 42 | (Msg->getReceiverKind() != ObjCMessageExpr::Instance && |
240 | 42 | Msg->getReceiverKind() != ObjCMessageExpr::SuperInstance7 )) |
241 | 0 | return false; |
242 | 42 | if (const Expr *Receiver = Msg->getInstanceReceiver()) |
243 | 35 | if (Receiver->getType()->isObjCBuiltinType()) |
244 | 2 | return false; |
245 | | |
246 | 40 | const ObjCMethodDecl *Method = Msg->getMethodDecl(); |
247 | 40 | if (!Method) |
248 | 0 | return false; |
249 | 40 | if (!Method->isPropertyAccessor()) |
250 | 0 | return false; |
251 | | |
252 | 40 | const ObjCPropertyDecl *Prop = Method->findPropertyDecl(); |
253 | 40 | if (!Prop) |
254 | 0 | return false; |
255 | | |
256 | 40 | SourceRange MsgRange = Msg->getSourceRange(); |
257 | 40 | bool ReceiverIsSuper = |
258 | 40 | (Msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); |
259 | | // for 'super' receiver is nullptr. |
260 | 40 | const Expr *receiver = Msg->getInstanceReceiver(); |
261 | 40 | bool NeedsParen = |
262 | 40 | ReceiverIsSuper ? false7 : subscriptOperatorNeedsParens(receiver)33 ; |
263 | 40 | bool IsGetter = (Msg->getNumArgs() == 0); |
264 | 40 | if (IsGetter) { |
265 | | // Find space location range between receiver expression and getter method. |
266 | 23 | SourceLocation BegLoc = |
267 | 23 | ReceiverIsSuper ? Msg->getSuperLoc()4 : receiver->getEndLoc()19 ; |
268 | 23 | BegLoc = PP.getLocForEndOfToken(BegLoc); |
269 | 23 | SourceLocation EndLoc = Msg->getSelectorLoc(0); |
270 | 23 | SourceRange SpaceRange(BegLoc, EndLoc); |
271 | 23 | std::string PropertyDotString; |
272 | | // rewrite getter method expression into: receiver.property or |
273 | | // (receiver).property |
274 | 23 | if (NeedsParen) { |
275 | 2 | commit.insertBefore(receiver->getBeginLoc(), "("); |
276 | 2 | PropertyDotString = ")."; |
277 | 2 | } |
278 | 21 | else |
279 | 21 | PropertyDotString = "."; |
280 | 23 | PropertyDotString += Prop->getName(); |
281 | 23 | commit.replace(SpaceRange, PropertyDotString); |
282 | | |
283 | | // remove '[' ']' |
284 | 23 | commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), ""); |
285 | 23 | commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), ""); |
286 | 23 | } else { |
287 | 17 | if (NeedsParen) |
288 | 1 | commit.insertWrap("(", receiver->getSourceRange(), ")"); |
289 | 17 | std::string PropertyDotString = "."; |
290 | 17 | PropertyDotString += Prop->getName(); |
291 | 17 | PropertyDotString += " ="; |
292 | 17 | const Expr*const* Args = Msg->getArgs(); |
293 | 17 | const Expr *RHS = Args[0]; |
294 | 17 | if (!RHS) |
295 | 0 | return false; |
296 | 17 | SourceLocation BegLoc = |
297 | 17 | ReceiverIsSuper ? Msg->getSuperLoc()3 : receiver->getEndLoc()14 ; |
298 | 17 | BegLoc = PP.getLocForEndOfToken(BegLoc); |
299 | 17 | SourceLocation EndLoc = RHS->getBeginLoc(); |
300 | 17 | EndLoc = EndLoc.getLocWithOffset(-1); |
301 | 17 | const char *colon = PP.getSourceManager().getCharacterData(EndLoc); |
302 | | // Add a space after '=' if there is no space between RHS and '=' |
303 | 17 | if (colon && colon[0] == ':') |
304 | 3 | PropertyDotString += " "; |
305 | 17 | SourceRange Range(BegLoc, EndLoc); |
306 | 17 | commit.replace(Range, PropertyDotString); |
307 | | // remove '[' ']' |
308 | 17 | commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), ""); |
309 | 17 | commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), ""); |
310 | 17 | } |
311 | 40 | return true; |
312 | 40 | } |
313 | | |
314 | | class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> { |
315 | | ObjCMigrateASTConsumer &Consumer; |
316 | | ParentMap &PMap; |
317 | | |
318 | | public: |
319 | | ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap) |
320 | 520 | : Consumer(consumer), PMap(PMap) { } |
321 | | |
322 | 0 | bool shouldVisitTemplateInstantiations() const { return false; } |
323 | 457 | bool shouldWalkTypesOfTypeLocs() const { return false; } |
324 | | |
325 | 862 | bool VisitObjCMessageExpr(ObjCMessageExpr *E) { |
326 | 862 | if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) { |
327 | 538 | edit::Commit commit(*Consumer.Editor); |
328 | 538 | edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap); |
329 | 538 | Consumer.Editor->commit(commit); |
330 | 538 | } |
331 | | |
332 | 862 | if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) { |
333 | 538 | edit::Commit commit(*Consumer.Editor); |
334 | 538 | edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit); |
335 | 538 | Consumer.Editor->commit(commit); |
336 | 538 | } |
337 | | |
338 | 862 | if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_PropertyDotSyntax) { |
339 | 42 | edit::Commit commit(*Consumer.Editor); |
340 | 42 | rewriteToPropertyDotSyntax(E, Consumer.PP, *Consumer.NSAPIObj, |
341 | 42 | commit, &PMap); |
342 | 42 | Consumer.Editor->commit(commit); |
343 | 42 | } |
344 | | |
345 | 862 | return true; |
346 | 862 | } |
347 | | |
348 | 862 | bool TraverseObjCMessageExpr(ObjCMessageExpr *E) { |
349 | | // Do depth first; we want to rewrite the subexpressions first so that if |
350 | | // we have to move expressions we will move them already rewritten. |
351 | 862 | for (Stmt *SubStmt : E->children()) |
352 | 953 | if (!TraverseStmt(SubStmt)) |
353 | 0 | return false; |
354 | | |
355 | 862 | return WalkUpFromObjCMessageExpr(E); |
356 | 862 | } |
357 | | }; |
358 | | |
359 | | class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> { |
360 | | ObjCMigrateASTConsumer &Consumer; |
361 | | std::unique_ptr<ParentMap> PMap; |
362 | | |
363 | | public: |
364 | 949 | BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { } |
365 | | |
366 | 0 | bool shouldVisitTemplateInstantiations() const { return false; } |
367 | 3.43k | bool shouldWalkTypesOfTypeLocs() const { return false; } |
368 | | |
369 | 520 | bool TraverseStmt(Stmt *S) { |
370 | 520 | PMap.reset(new ParentMap(S)); |
371 | 520 | ObjCMigrator(Consumer, *PMap).TraverseStmt(S); |
372 | 520 | return true; |
373 | 520 | } |
374 | | }; |
375 | | } // end anonymous namespace |
376 | | |
377 | 1.02k | void ObjCMigrateASTConsumer::migrateDecl(Decl *D) { |
378 | 1.02k | if (!D) |
379 | 0 | return; |
380 | 1.02k | if (isa<ObjCMethodDecl>(D)) |
381 | 71 | return; // Wait for the ObjC container declaration. |
382 | | |
383 | 949 | BodyMigrator(*this).TraverseDecl(D); |
384 | 949 | } |
385 | | |
386 | | static void append_attr(std::string &PropertyString, const char *attr, |
387 | 190 | bool &LParenAdded) { |
388 | 190 | if (!LParenAdded) { |
389 | 34 | PropertyString += "("; |
390 | 34 | LParenAdded = true; |
391 | 34 | } |
392 | 156 | else |
393 | 156 | PropertyString += ", "; |
394 | 190 | PropertyString += attr; |
395 | 190 | } |
396 | | |
397 | | static |
398 | | void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString, |
399 | | const std::string& TypeString, |
400 | 12 | const char *name) { |
401 | 12 | const char *argPtr = TypeString.c_str(); |
402 | 12 | int paren = 0; |
403 | 540 | while (*argPtr) { |
404 | 528 | switch (*argPtr) { |
405 | 24 | case '(': |
406 | 24 | PropertyString += *argPtr; |
407 | 24 | paren++; |
408 | 24 | break; |
409 | 24 | case ')': |
410 | 24 | PropertyString += *argPtr; |
411 | 24 | paren--; |
412 | 24 | break; |
413 | 6 | case '^': |
414 | 36 | case '*': |
415 | 36 | PropertyString += (*argPtr); |
416 | 36 | if (paren == 1) { |
417 | 36 | PropertyString += name; |
418 | 36 | name = ""; |
419 | 36 | } |
420 | 36 | break; |
421 | 444 | default: |
422 | 444 | PropertyString += *argPtr; |
423 | 444 | break; |
424 | 528 | } |
425 | 528 | argPtr++; |
426 | 528 | } |
427 | 12 | } |
428 | | |
429 | 176 | static const char *PropertyMemoryAttribute(ASTContext &Context, QualType ArgType) { |
430 | 176 | Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime(); |
431 | 176 | bool RetainableObject = ArgType->isObjCRetainableType(); |
432 | 176 | if (RetainableObject && |
433 | 176 | (85 propertyLifetime == Qualifiers::OCL_Strong85 |
434 | 85 | || propertyLifetime == Qualifiers::OCL_None19 )) { |
435 | 82 | if (const ObjCObjectPointerType *ObjPtrTy = |
436 | 82 | ArgType->getAs<ObjCObjectPointerType>()) { |
437 | 76 | ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface(); |
438 | 76 | if (IDecl && |
439 | 76 | IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying"))50 ) |
440 | 6 | return "copy"; |
441 | 70 | else |
442 | 70 | return "strong"; |
443 | 76 | } |
444 | 6 | else if (ArgType->isBlockPointerType()) |
445 | 6 | return "copy"; |
446 | 94 | } else if (propertyLifetime == Qualifiers::OCL_Weak) |
447 | | // TODO. More precise determination of 'weak' attribute requires |
448 | | // looking into setter's implementation for backing weak ivar. |
449 | 3 | return "weak"; |
450 | 91 | else if (RetainableObject) |
451 | 0 | return ArgType->isBlockPointerType() ? "copy" : "strong"; |
452 | 91 | return nullptr; |
453 | 176 | } |
454 | | |
455 | | static void rewriteToObjCProperty(const ObjCMethodDecl *Getter, |
456 | | const ObjCMethodDecl *Setter, |
457 | | const NSAPI &NS, edit::Commit &commit, |
458 | | unsigned LengthOfPrefix, |
459 | | bool Atomic, bool UseNsIosOnlyMacro, |
460 | 196 | bool AvailabilityArgsMatch) { |
461 | 196 | ASTContext &Context = NS.getASTContext(); |
462 | 196 | bool LParenAdded = false; |
463 | 196 | std::string PropertyString = "@property "; |
464 | 196 | if (UseNsIosOnlyMacro && NS.isMacroDefined("NS_NONATOMIC_IOSONLY")68 ) { |
465 | 56 | PropertyString += "(NS_NONATOMIC_IOSONLY"; |
466 | 56 | LParenAdded = true; |
467 | 140 | } else if (!Atomic) { |
468 | 84 | PropertyString += "(nonatomic"; |
469 | 84 | LParenAdded = true; |
470 | 84 | } |
471 | | |
472 | 196 | std::string PropertyNameString = Getter->getNameAsString(); |
473 | 196 | StringRef PropertyName(PropertyNameString); |
474 | 196 | if (LengthOfPrefix > 0) { |
475 | 57 | if (!LParenAdded) { |
476 | 19 | PropertyString += "(getter="; |
477 | 19 | LParenAdded = true; |
478 | 19 | } |
479 | 38 | else |
480 | 38 | PropertyString += ", getter="; |
481 | 57 | PropertyString += PropertyNameString; |
482 | 57 | } |
483 | | // Property with no setter may be suggested as a 'readonly' property. |
484 | 196 | if (!Setter) |
485 | 85 | append_attr(PropertyString, "readonly", LParenAdded); |
486 | | |
487 | | |
488 | | // Short circuit 'delegate' properties that contain the name "delegate" or |
489 | | // "dataSource", or have exact name "target" to have 'assign' attribute. |
490 | 196 | if (PropertyName.equals("target") || PropertyName.contains("delegate")189 || |
491 | 196 | PropertyName.contains("dataSource")182 ) { |
492 | 20 | QualType QT = Getter->getReturnType(); |
493 | 20 | if (!QT->isRealType()) |
494 | 20 | append_attr(PropertyString, "assign", LParenAdded); |
495 | 176 | } else if (!Setter) { |
496 | 84 | QualType ResType = Context.getCanonicalType(Getter->getReturnType()); |
497 | 84 | if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ResType)) |
498 | 16 | append_attr(PropertyString, MemoryManagementAttr, LParenAdded); |
499 | 92 | } else { |
500 | 92 | const ParmVarDecl *argDecl = *Setter->param_begin(); |
501 | 92 | QualType ArgType = Context.getCanonicalType(argDecl->getType()); |
502 | 92 | if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ArgType)) |
503 | 69 | append_attr(PropertyString, MemoryManagementAttr, LParenAdded); |
504 | 92 | } |
505 | 196 | if (LParenAdded) |
506 | 193 | PropertyString += ')'; |
507 | 196 | QualType RT = Getter->getReturnType(); |
508 | 196 | if (!isa<TypedefType>(RT)) { |
509 | | // strip off any ARC lifetime qualifier. |
510 | 94 | QualType CanResultTy = Context.getCanonicalType(RT); |
511 | 94 | if (CanResultTy.getQualifiers().hasObjCLifetime()) { |
512 | 6 | Qualifiers Qs = CanResultTy.getQualifiers(); |
513 | 6 | Qs.removeObjCLifetime(); |
514 | 6 | RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs); |
515 | 6 | } |
516 | 94 | } |
517 | 196 | PropertyString += " "; |
518 | 196 | PrintingPolicy SubPolicy(Context.getPrintingPolicy()); |
519 | 196 | SubPolicy.SuppressStrongLifetime = true; |
520 | 196 | SubPolicy.SuppressLifetimeQualifiers = true; |
521 | 196 | std::string TypeString = RT.getAsString(SubPolicy); |
522 | 196 | if (LengthOfPrefix > 0) { |
523 | | // property name must strip off "is" and lower case the first character |
524 | | // after that; e.g. isContinuous will become continuous. |
525 | 57 | StringRef PropertyNameStringRef(PropertyNameString); |
526 | 57 | PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix); |
527 | 57 | PropertyNameString = std::string(PropertyNameStringRef); |
528 | 57 | bool NoLowering = (isUppercase(PropertyNameString[0]) && |
529 | 57 | PropertyNameString.size() > 148 && |
530 | 57 | isUppercase(PropertyNameString[1])42 ); |
531 | 57 | if (!NoLowering) |
532 | 39 | PropertyNameString[0] = toLowercase(PropertyNameString[0]); |
533 | 57 | } |
534 | 196 | if (RT->isBlockPointerType() || RT->isFunctionPointerType()190 ) |
535 | 12 | MigrateBlockOrFunctionPointerTypeVariable(PropertyString, |
536 | 12 | TypeString, |
537 | 12 | PropertyNameString.c_str()); |
538 | 184 | else { |
539 | 184 | char LastChar = TypeString[TypeString.size()-1]; |
540 | 184 | PropertyString += TypeString; |
541 | 184 | if (LastChar != '*') |
542 | 120 | PropertyString += ' '; |
543 | 184 | PropertyString += PropertyNameString; |
544 | 184 | } |
545 | 196 | SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc(); |
546 | 196 | Selector GetterSelector = Getter->getSelector(); |
547 | | |
548 | 196 | SourceLocation EndGetterSelectorLoc = |
549 | 196 | StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size()); |
550 | 196 | commit.replace(CharSourceRange::getCharRange(Getter->getBeginLoc(), |
551 | 196 | EndGetterSelectorLoc), |
552 | 196 | PropertyString); |
553 | 196 | if (Setter && AvailabilityArgsMatch111 ) { |
554 | 94 | SourceLocation EndLoc = Setter->getDeclaratorEndLoc(); |
555 | | // Get location past ';' |
556 | 94 | EndLoc = EndLoc.getLocWithOffset(1); |
557 | 94 | SourceLocation BeginOfSetterDclLoc = Setter->getBeginLoc(); |
558 | | // FIXME. This assumes that setter decl; is immediately preceded by eoln. |
559 | | // It is trying to remove the setter method decl. line entirely. |
560 | 94 | BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1); |
561 | 94 | commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc)); |
562 | 94 | } |
563 | 196 | } |
564 | | |
565 | 441 | static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) { |
566 | 441 | if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) { |
567 | 26 | StringRef Name = CatDecl->getName(); |
568 | 26 | return Name.endswith("Deprecated"); |
569 | 26 | } |
570 | 415 | return false; |
571 | 441 | } |
572 | | |
573 | | void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx, |
574 | 251 | ObjCContainerDecl *D) { |
575 | 251 | if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D)248 ) |
576 | 4 | return; |
577 | | |
578 | 616 | for (auto *Method : D->methods())247 { |
579 | 616 | if (Method->isDeprecated()) |
580 | 15 | continue; |
581 | 601 | bool PropertyInferred = migrateProperty(Ctx, D, Method); |
582 | | // If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to |
583 | | // the getter method as it ends up on the property itself which we don't want |
584 | | // to do unless -objcmt-returns-innerpointer-property option is on. |
585 | 601 | if (!PropertyInferred || |
586 | 601 | (ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty)196 ) |
587 | 405 | if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) |
588 | 132 | migrateNsReturnsInnerPointer(Ctx, Method); |
589 | 601 | } |
590 | 247 | if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty)) |
591 | 241 | return; |
592 | | |
593 | 6 | for (auto *Prop : D->instance_properties()) { |
594 | 5 | if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) && |
595 | 5 | !Prop->isDeprecated()) |
596 | 5 | migratePropertyNsReturnsInnerPointer(Ctx, Prop); |
597 | 5 | } |
598 | 6 | } |
599 | | |
600 | | static bool |
601 | | ClassImplementsAllMethodsAndProperties(ASTContext &Ctx, |
602 | | const ObjCImplementationDecl *ImpDecl, |
603 | | const ObjCInterfaceDecl *IDecl, |
604 | 40 | ObjCProtocolDecl *Protocol) { |
605 | | // In auto-synthesis, protocol properties are not synthesized. So, |
606 | | // a conforming protocol must have its required properties declared |
607 | | // in class interface. |
608 | 40 | bool HasAtleastOneRequiredProperty = false; |
609 | 40 | if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) |
610 | 40 | for (const auto *Property : PDecl->instance_properties()) { |
611 | 17 | if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional) |
612 | 4 | continue; |
613 | 13 | HasAtleastOneRequiredProperty = true; |
614 | 13 | DeclContext::lookup_result R = IDecl->lookup(Property->getDeclName()); |
615 | 13 | if (R.empty()) { |
616 | | // Relax the rule and look into class's implementation for a synthesize |
617 | | // or dynamic declaration. Class is implementing a property coming from |
618 | | // another protocol. This still makes the target protocol as conforming. |
619 | 9 | if (!ImpDecl->FindPropertyImplDecl( |
620 | 9 | Property->getDeclName().getAsIdentifierInfo(), |
621 | 9 | Property->getQueryKind())) |
622 | 8 | return false; |
623 | 9 | } else if (auto *4 ClassProperty4 = R.find_first<ObjCPropertyDecl>()) { |
624 | 4 | if ((ClassProperty->getPropertyAttributes() != |
625 | 4 | Property->getPropertyAttributes()) || |
626 | 4 | !Ctx.hasSameType(ClassProperty->getType(), Property->getType())) |
627 | 0 | return false; |
628 | 4 | } else |
629 | 0 | return false; |
630 | 13 | } |
631 | | |
632 | | // 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. |
635 | 32 | bool HasAtleastOneRequiredMethod = false; |
636 | 32 | if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) { |
637 | 32 | if (PDecl->meth_begin() == PDecl->meth_end()) |
638 | 13 | return HasAtleastOneRequiredProperty; |
639 | 34 | for (const auto *MD : PDecl->methods())19 { |
640 | 34 | if (MD->isImplicit()) |
641 | 18 | continue; |
642 | 16 | if (MD->getImplementationControl() == ObjCMethodDecl::Optional) |
643 | 8 | continue; |
644 | 8 | DeclContext::lookup_result R = ImpDecl->lookup(MD->getDeclName()); |
645 | 8 | if (R.empty()) |
646 | 4 | return false; |
647 | 4 | bool match = false; |
648 | 4 | HasAtleastOneRequiredMethod = true; |
649 | 4 | for (NamedDecl *ND : R) |
650 | 4 | if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(ND)) |
651 | 4 | if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) { |
652 | 4 | match = true; |
653 | 4 | break; |
654 | 4 | } |
655 | 4 | if (!match) |
656 | 0 | return false; |
657 | 4 | } |
658 | 19 | } |
659 | 15 | return HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod10 ; |
660 | 32 | } |
661 | | |
662 | | static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl, |
663 | | llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols, |
664 | 6 | const NSAPI &NS, edit::Commit &commit) { |
665 | 6 | const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols(); |
666 | 6 | std::string ClassString; |
667 | 6 | SourceLocation EndLoc = |
668 | 6 | IDecl->getSuperClass() ? IDecl->getSuperClassLoc()4 : IDecl->getLocation()2 ; |
669 | | |
670 | 6 | if (Protocols.empty()) { |
671 | 3 | ClassString = '<'; |
672 | 6 | for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++3 ) { |
673 | 3 | ClassString += ConformingProtocols[i]->getNameAsString(); |
674 | 3 | if (i != (e-1)) |
675 | 0 | ClassString += ", "; |
676 | 3 | } |
677 | 3 | ClassString += "> "; |
678 | 3 | } |
679 | 3 | else { |
680 | 3 | ClassString = ", "; |
681 | 6 | for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++3 ) { |
682 | 3 | ClassString += ConformingProtocols[i]->getNameAsString(); |
683 | 3 | if (i != (e-1)) |
684 | 0 | ClassString += ", "; |
685 | 3 | } |
686 | 3 | ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1; |
687 | 3 | EndLoc = *PL; |
688 | 3 | } |
689 | | |
690 | 6 | commit.insertAfterToken(EndLoc, ClassString); |
691 | 6 | return true; |
692 | 6 | } |
693 | | |
694 | 11 | static StringRef GetUnsignedName(StringRef NSIntegerName) { |
695 | 11 | StringRef UnsignedName = llvm::StringSwitch<StringRef>(NSIntegerName) |
696 | 11 | .Case("int8_t", "uint8_t") |
697 | 11 | .Case("int16_t", "uint16_t") |
698 | 11 | .Case("int32_t", "uint32_t") |
699 | 11 | .Case("NSInteger", "NSUInteger") |
700 | 11 | .Case("int64_t", "uint64_t") |
701 | 11 | .Default(NSIntegerName); |
702 | 11 | return UnsignedName; |
703 | 11 | } |
704 | | |
705 | | static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl, |
706 | | const TypedefDecl *TypedefDcl, |
707 | | const NSAPI &NS, edit::Commit &commit, |
708 | | StringRef NSIntegerName, |
709 | 22 | bool NSOptions) { |
710 | 22 | std::string ClassString; |
711 | 22 | if (NSOptions) { |
712 | 11 | ClassString = "typedef NS_OPTIONS("; |
713 | 11 | ClassString += GetUnsignedName(NSIntegerName); |
714 | 11 | } |
715 | 11 | else { |
716 | 11 | ClassString = "typedef NS_ENUM("; |
717 | 11 | ClassString += NSIntegerName; |
718 | 11 | } |
719 | 22 | ClassString += ", "; |
720 | | |
721 | 22 | ClassString += TypedefDcl->getIdentifier()->getName(); |
722 | 22 | ClassString += ')'; |
723 | 22 | SourceRange R(EnumDcl->getBeginLoc(), EnumDcl->getBeginLoc()); |
724 | 22 | commit.replace(R, ClassString); |
725 | 22 | SourceLocation EndOfEnumDclLoc = EnumDcl->getEndLoc(); |
726 | 22 | EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc, |
727 | 22 | NS.getASTContext(), /*IsDecl*/true); |
728 | 22 | if (EndOfEnumDclLoc.isValid()) { |
729 | 22 | SourceRange EnumDclRange(EnumDcl->getBeginLoc(), EndOfEnumDclLoc); |
730 | 22 | commit.insertFromRange(TypedefDcl->getBeginLoc(), EnumDclRange); |
731 | 22 | } |
732 | 0 | else |
733 | 0 | return false; |
734 | | |
735 | 22 | SourceLocation EndTypedefDclLoc = TypedefDcl->getEndLoc(); |
736 | 22 | EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc, |
737 | 22 | NS.getASTContext(), /*IsDecl*/true); |
738 | 22 | if (EndTypedefDclLoc.isValid()) { |
739 | 22 | SourceRange TDRange(TypedefDcl->getBeginLoc(), EndTypedefDclLoc); |
740 | 22 | commit.remove(TDRange); |
741 | 22 | } |
742 | 0 | else |
743 | 0 | return false; |
744 | | |
745 | 22 | EndOfEnumDclLoc = |
746 | 22 | trans::findLocationAfterSemi(EnumDcl->getEndLoc(), NS.getASTContext(), |
747 | 22 | /*IsDecl*/ true); |
748 | 22 | if (EndOfEnumDclLoc.isValid()) { |
749 | 22 | SourceLocation BeginOfEnumDclLoc = EnumDcl->getBeginLoc(); |
750 | | // FIXME. This assumes that enum decl; is immediately preceded by eoln. |
751 | | // It is trying to remove the enum decl. lines entirely. |
752 | 22 | BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1); |
753 | 22 | commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc)); |
754 | 22 | return true; |
755 | 22 | } |
756 | 0 | return false; |
757 | 22 | } |
758 | | |
759 | | static void rewriteToNSMacroDecl(ASTContext &Ctx, |
760 | | const EnumDecl *EnumDcl, |
761 | | const TypedefDecl *TypedefDcl, |
762 | | const NSAPI &NS, edit::Commit &commit, |
763 | 28 | bool IsNSIntegerType) { |
764 | 28 | QualType DesignatedEnumType = EnumDcl->getIntegerType(); |
765 | 28 | assert(!DesignatedEnumType.isNull() |
766 | 28 | && "rewriteToNSMacroDecl - underlying enum type is null"); |
767 | | |
768 | 0 | PrintingPolicy Policy(Ctx.getPrintingPolicy()); |
769 | 28 | std::string TypeString = DesignatedEnumType.getAsString(Policy); |
770 | 28 | std::string ClassString = IsNSIntegerType ? "NS_ENUM("23 : "NS_OPTIONS("5 ; |
771 | 28 | ClassString += TypeString; |
772 | 28 | ClassString += ", "; |
773 | | |
774 | 28 | ClassString += TypedefDcl->getIdentifier()->getName(); |
775 | 28 | ClassString += ") "; |
776 | 28 | SourceLocation EndLoc = EnumDcl->getBraceRange().getBegin(); |
777 | 28 | if (EndLoc.isInvalid()) |
778 | 0 | return; |
779 | 28 | CharSourceRange R = |
780 | 28 | CharSourceRange::getCharRange(EnumDcl->getBeginLoc(), EndLoc); |
781 | 28 | commit.replace(R, ClassString); |
782 | | // This is to remove spaces between '}' and typedef name. |
783 | 28 | SourceLocation StartTypedefLoc = EnumDcl->getEndLoc(); |
784 | 28 | StartTypedefLoc = StartTypedefLoc.getLocWithOffset(+1); |
785 | 28 | SourceLocation EndTypedefLoc = TypedefDcl->getEndLoc(); |
786 | | |
787 | 28 | commit.remove(SourceRange(StartTypedefLoc, EndTypedefLoc)); |
788 | 28 | } |
789 | | |
790 | | static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx, |
791 | 50 | const EnumDecl *EnumDcl) { |
792 | 50 | bool PowerOfTwo = true; |
793 | 50 | bool AllHexdecimalEnumerator = true; |
794 | 50 | uint64_t MaxPowerOfTwoVal = 0; |
795 | 152 | for (auto Enumerator : EnumDcl->enumerators()) { |
796 | 152 | const Expr *InitExpr = Enumerator->getInitExpr(); |
797 | 152 | if (!InitExpr) { |
798 | 49 | PowerOfTwo = false; |
799 | 49 | AllHexdecimalEnumerator = false; |
800 | 49 | continue; |
801 | 49 | } |
802 | 103 | InitExpr = InitExpr->IgnoreParenCasts(); |
803 | 103 | if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) |
804 | 7 | if (BO->isShiftOp() || BO->isBitwiseOp()1 ) |
805 | 7 | return true; |
806 | | |
807 | 96 | uint64_t EnumVal = Enumerator->getInitVal().getZExtValue(); |
808 | 96 | if (PowerOfTwo && EnumVal85 ) { |
809 | 65 | if (!llvm::isPowerOf2_64(EnumVal)) |
810 | 11 | PowerOfTwo = false; |
811 | 54 | else if (EnumVal > MaxPowerOfTwoVal) |
812 | 53 | MaxPowerOfTwoVal = EnumVal; |
813 | 65 | } |
814 | 96 | if (AllHexdecimalEnumerator && EnumVal78 ) { |
815 | 59 | bool FoundHexdecimalEnumerator = false; |
816 | 59 | SourceLocation EndLoc = Enumerator->getEndLoc(); |
817 | 59 | Token Tok; |
818 | 59 | if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true)) |
819 | 59 | if (Tok.isLiteral() && Tok.getLength() > 258 ) { |
820 | 42 | if (const char *StringLit = Tok.getLiteralData()) |
821 | 42 | FoundHexdecimalEnumerator = |
822 | 42 | (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x')41 ); |
823 | 42 | } |
824 | 59 | if (!FoundHexdecimalEnumerator) |
825 | 18 | AllHexdecimalEnumerator = false; |
826 | 59 | } |
827 | 96 | } |
828 | 43 | return AllHexdecimalEnumerator || (35 PowerOfTwo35 && (MaxPowerOfTwoVal > 2)11 ); |
829 | 50 | } |
830 | | |
831 | | void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, |
832 | 8 | const ObjCImplementationDecl *ImpDecl) { |
833 | 8 | const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface(); |
834 | 8 | if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated()) |
835 | 0 | return; |
836 | | // Find all implicit conforming protocols for this class |
837 | | // and make them explicit. |
838 | 8 | llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols; |
839 | 8 | Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols); |
840 | 8 | llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols; |
841 | | |
842 | 8 | for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls) |
843 | 47 | if (!ExplicitProtocols.count(ProtDecl)) |
844 | 40 | PotentialImplicitProtocols.push_back(ProtDecl); |
845 | | |
846 | 8 | if (PotentialImplicitProtocols.empty()) |
847 | 0 | return; |
848 | | |
849 | | // go through list of non-optional methods and properties in each protocol |
850 | | // in the PotentialImplicitProtocols list. If class implements every one of the |
851 | | // methods and properties, then this class conforms to this protocol. |
852 | 8 | llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols; |
853 | 48 | for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++40 ) |
854 | 40 | if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl, |
855 | 40 | PotentialImplicitProtocols[i])) |
856 | 9 | ConformingProtocols.push_back(PotentialImplicitProtocols[i]); |
857 | | |
858 | 8 | if (ConformingProtocols.empty()) |
859 | 2 | return; |
860 | | |
861 | | // Further reduce number of conforming protocols. If protocol P1 is in the list |
862 | | // protocol P2 (P2<P1>), No need to include P1. |
863 | 6 | llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols; |
864 | 15 | for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++9 ) { |
865 | 9 | bool DropIt = false; |
866 | 9 | ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i]; |
867 | 25 | for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++16 ) { |
868 | 19 | ObjCProtocolDecl *PDecl = ConformingProtocols[i1]; |
869 | 19 | if (PDecl == TargetPDecl) |
870 | 9 | continue; |
871 | 10 | if (PDecl->lookupProtocolNamed( |
872 | 10 | TargetPDecl->getDeclName().getAsIdentifierInfo())) { |
873 | 3 | DropIt = true; |
874 | 3 | break; |
875 | 3 | } |
876 | 10 | } |
877 | 9 | if (!DropIt) |
878 | 6 | MinimalConformingProtocols.push_back(TargetPDecl); |
879 | 9 | } |
880 | 6 | if (MinimalConformingProtocols.empty()) |
881 | 0 | return; |
882 | 6 | edit::Commit commit(*Editor); |
883 | 6 | rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols, |
884 | 6 | *NSAPIObj, commit); |
885 | 6 | Editor->commit(commit); |
886 | 6 | } |
887 | | |
888 | | void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed( |
889 | 42 | const TypedefDecl *TypedefDcl) { |
890 | | |
891 | 42 | QualType qt = TypedefDcl->getTypeSourceInfo()->getType(); |
892 | 42 | if (NSAPIObj->isObjCNSIntegerType(qt)) |
893 | 0 | NSIntegerTypedefed = TypedefDcl; |
894 | 42 | else if (NSAPIObj->isObjCNSUIntegerType(qt)) |
895 | 4 | NSUIntegerTypedefed = TypedefDcl; |
896 | 42 | } |
897 | | |
898 | | bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx, |
899 | | const EnumDecl *EnumDcl, |
900 | 62 | const TypedefDecl *TypedefDcl) { |
901 | 62 | if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier()59 || |
902 | 62 | EnumDcl->isDeprecated()56 ) |
903 | 6 | return false; |
904 | 56 | if (!TypedefDcl) { |
905 | 4 | if (NSIntegerTypedefed) { |
906 | 0 | TypedefDcl = NSIntegerTypedefed; |
907 | 0 | NSIntegerTypedefed = nullptr; |
908 | 0 | } |
909 | 4 | else if (NSUIntegerTypedefed) { |
910 | 2 | TypedefDcl = NSUIntegerTypedefed; |
911 | 2 | NSUIntegerTypedefed = nullptr; |
912 | 2 | } |
913 | 2 | else |
914 | 2 | return false; |
915 | 2 | FileID FileIdOfTypedefDcl = |
916 | 2 | PP.getSourceManager().getFileID(TypedefDcl->getLocation()); |
917 | 2 | FileID FileIdOfEnumDcl = |
918 | 2 | PP.getSourceManager().getFileID(EnumDcl->getLocation()); |
919 | 2 | if (FileIdOfTypedefDcl != FileIdOfEnumDcl) |
920 | 0 | return false; |
921 | 2 | } |
922 | 54 | if (TypedefDcl->isDeprecated()) |
923 | 4 | return false; |
924 | | |
925 | 50 | QualType qt = TypedefDcl->getTypeSourceInfo()->getType(); |
926 | 50 | StringRef NSIntegerName = NSAPIObj->GetNSIntegralKind(qt); |
927 | | |
928 | 50 | if (NSIntegerName.empty()) { |
929 | | // Also check for typedef enum {...} TD; |
930 | 28 | if (const EnumType *EnumTy = qt->getAs<EnumType>()) { |
931 | 28 | if (EnumTy->getDecl() == EnumDcl) { |
932 | 28 | bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl); |
933 | 28 | if (!InsertFoundation(Ctx, TypedefDcl->getBeginLoc())) |
934 | 0 | return false; |
935 | 28 | edit::Commit commit(*Editor); |
936 | 28 | rewriteToNSMacroDecl(Ctx, EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions); |
937 | 28 | Editor->commit(commit); |
938 | 28 | return true; |
939 | 28 | } |
940 | 28 | } |
941 | 0 | return false; |
942 | 28 | } |
943 | | |
944 | | // We may still use NS_OPTIONS based on what we find in the enumertor list. |
945 | 22 | bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl); |
946 | 22 | if (!InsertFoundation(Ctx, TypedefDcl->getBeginLoc())) |
947 | 0 | return false; |
948 | 22 | edit::Commit commit(*Editor); |
949 | 22 | bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, |
950 | 22 | commit, NSIntegerName, NSOptions); |
951 | 22 | Editor->commit(commit); |
952 | 22 | return Res; |
953 | 22 | } |
954 | | |
955 | | static void ReplaceWithInstancetype(ASTContext &Ctx, |
956 | | const ObjCMigrateASTConsumer &ASTC, |
957 | 86 | ObjCMethodDecl *OM) { |
958 | 86 | if (OM->getReturnType() == Ctx.getObjCInstanceType()) |
959 | 2 | return; // already has instancetype. |
960 | | |
961 | 84 | SourceRange R; |
962 | 84 | std::string ClassString; |
963 | 84 | if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) { |
964 | 81 | TypeLoc TL = TSInfo->getTypeLoc(); |
965 | 81 | R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); |
966 | 81 | ClassString = "instancetype"; |
967 | 81 | } |
968 | 3 | else { |
969 | 3 | R = SourceRange(OM->getBeginLoc(), OM->getBeginLoc()); |
970 | 3 | ClassString = OM->isInstanceMethod() ? '-'0 : '+'; |
971 | 3 | ClassString += " (instancetype)"; |
972 | 3 | } |
973 | 84 | edit::Commit commit(*ASTC.Editor); |
974 | 84 | commit.replace(R, ClassString); |
975 | 84 | ASTC.Editor->commit(commit); |
976 | 84 | } |
977 | | |
978 | | static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC, |
979 | 4 | ObjCMethodDecl *OM) { |
980 | 4 | ObjCInterfaceDecl *IDecl = OM->getClassInterface(); |
981 | 4 | SourceRange R; |
982 | 4 | std::string ClassString; |
983 | 4 | if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) { |
984 | 2 | TypeLoc TL = TSInfo->getTypeLoc(); |
985 | 2 | R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); { |
986 | 2 | ClassString = std::string(IDecl->getName()); |
987 | 2 | ClassString += "*"; |
988 | 2 | } |
989 | 2 | } |
990 | 2 | else { |
991 | 2 | R = SourceRange(OM->getBeginLoc(), OM->getBeginLoc()); |
992 | 2 | ClassString = "+ ("; |
993 | 2 | ClassString += IDecl->getName(); ClassString += "*)"; |
994 | 2 | } |
995 | 4 | edit::Commit commit(*ASTC.Editor); |
996 | 4 | commit.replace(R, ClassString); |
997 | 4 | ASTC.Editor->commit(commit); |
998 | 4 | } |
999 | | |
1000 | | void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx, |
1001 | | ObjCContainerDecl *CDecl, |
1002 | 260 | ObjCMethodDecl *OM) { |
1003 | 260 | ObjCInstanceTypeFamily OIT_Family = |
1004 | 260 | Selector::getInstTypeMethodFamily(OM->getSelector()); |
1005 | | |
1006 | 260 | std::string ClassName; |
1007 | 260 | switch (OIT_Family) { |
1008 | 197 | case OIT_None: |
1009 | 197 | migrateFactoryMethod(Ctx, CDecl, OM); |
1010 | 197 | return; |
1011 | 15 | case OIT_Array: |
1012 | 15 | ClassName = "NSArray"; |
1013 | 15 | break; |
1014 | 11 | case OIT_Dictionary: |
1015 | 11 | ClassName = "NSDictionary"; |
1016 | 11 | break; |
1017 | 1 | case OIT_Singleton: |
1018 | 1 | migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton); |
1019 | 1 | return; |
1020 | 32 | case OIT_Init: |
1021 | 32 | if (OM->getReturnType()->isObjCIdType()) |
1022 | 32 | ReplaceWithInstancetype(Ctx, *this, OM); |
1023 | 32 | return; |
1024 | 4 | case OIT_ReturnsSelf: |
1025 | 4 | migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf); |
1026 | 4 | return; |
1027 | 260 | } |
1028 | 26 | if (!OM->getReturnType()->isObjCIdType()) |
1029 | 0 | return; |
1030 | | |
1031 | 26 | ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); |
1032 | 26 | if (!IDecl) { |
1033 | 19 | if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) |
1034 | 14 | IDecl = CatDecl->getClassInterface(); |
1035 | 5 | else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl)) |
1036 | 5 | IDecl = ImpDecl->getClassInterface(); |
1037 | 19 | } |
1038 | 26 | if (!IDecl || |
1039 | 26 | !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) { |
1040 | 2 | migrateFactoryMethod(Ctx, CDecl, OM); |
1041 | 2 | return; |
1042 | 2 | } |
1043 | 24 | ReplaceWithInstancetype(Ctx, *this, OM); |
1044 | 24 | } |
1045 | | |
1046 | 101 | static bool TypeIsInnerPointer(QualType T) { |
1047 | 101 | if (!T->isAnyPointerType()) |
1048 | 30 | return false; |
1049 | 71 | if (T->isObjCObjectPointerType() || T->isObjCBuiltinType()27 || |
1050 | 71 | T->isBlockPointerType()26 || T->isFunctionPointerType()26 || |
1051 | 71 | ento::coreFoundation::isCFObjectRef(T)25 ) |
1052 | 56 | return false; |
1053 | | // Also, typedef-of-pointer-to-incomplete-struct is something that we assume |
1054 | | // is not an innter pointer type. |
1055 | 15 | QualType OrigT = T; |
1056 | 22 | while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) |
1057 | 7 | T = TD->getDecl()->getUnderlyingType(); |
1058 | 15 | if (OrigT == T || !T->isPointerType()6 ) |
1059 | 9 | return true; |
1060 | 6 | const PointerType* PT = T->getAs<PointerType>(); |
1061 | 6 | QualType UPointeeT = PT->getPointeeType().getUnqualifiedType(); |
1062 | 6 | if (UPointeeT->isRecordType()) { |
1063 | 3 | const RecordType *RecordTy = UPointeeT->getAs<RecordType>(); |
1064 | 3 | if (!RecordTy->getDecl()->isCompleteDefinition()) |
1065 | 3 | return false; |
1066 | 3 | } |
1067 | 3 | return true; |
1068 | 6 | } |
1069 | | |
1070 | | /// Check whether the two versions match. |
1071 | 28 | static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) { |
1072 | 28 | return (X == Y); |
1073 | 28 | } |
1074 | | |
1075 | | /// AvailabilityAttrsMatch - This routine checks that if comparing two |
1076 | | /// availability attributes, all their components match. It returns |
1077 | | /// true, if not dealing with availability or when all components of |
1078 | | /// availability attributes match. This routine is only called when |
1079 | | /// the attributes are of the same kind. |
1080 | 19 | static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) { |
1081 | 19 | const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1); |
1082 | 19 | if (!AA1) |
1083 | 9 | return true; |
1084 | 10 | const AvailabilityAttr *AA2 = cast<AvailabilityAttr>(At2); |
1085 | | |
1086 | 10 | VersionTuple Introduced1 = AA1->getIntroduced(); |
1087 | 10 | VersionTuple Deprecated1 = AA1->getDeprecated(); |
1088 | 10 | VersionTuple Obsoleted1 = AA1->getObsoleted(); |
1089 | 10 | bool IsUnavailable1 = AA1->getUnavailable(); |
1090 | 10 | VersionTuple Introduced2 = AA2->getIntroduced(); |
1091 | 10 | VersionTuple Deprecated2 = AA2->getDeprecated(); |
1092 | 10 | VersionTuple Obsoleted2 = AA2->getObsoleted(); |
1093 | 10 | bool IsUnavailable2 = AA2->getUnavailable(); |
1094 | 10 | return (versionsMatch(Introduced1, Introduced2) && |
1095 | 10 | versionsMatch(Deprecated1, Deprecated2)9 && |
1096 | 10 | versionsMatch(Obsoleted1, Obsoleted2)9 && |
1097 | 10 | IsUnavailable1 == IsUnavailable29 ); |
1098 | 19 | } |
1099 | | |
1100 | | static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2, |
1101 | 20 | bool &AvailabilityArgsMatch) { |
1102 | | // This list is very small, so this need not be optimized. |
1103 | 39 | for (unsigned i = 0, e = Attrs1.size(); i != e; i++19 ) { |
1104 | 25 | bool match = false; |
1105 | 36 | for (unsigned j = 0, f = Attrs2.size(); j != f; j++11 ) { |
1106 | | // Matching attribute kind only. Except for Availability attributes, |
1107 | | // we are not getting into details of the attributes. For all practical purposes |
1108 | | // this is sufficient. |
1109 | 30 | if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) { |
1110 | 19 | if (AvailabilityArgsMatch) |
1111 | 19 | AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]); |
1112 | 19 | match = true; |
1113 | 19 | break; |
1114 | 19 | } |
1115 | 30 | } |
1116 | 25 | if (!match) |
1117 | 6 | return false; |
1118 | 25 | } |
1119 | 14 | return true; |
1120 | 20 | } |
1121 | | |
1122 | | /// AttributesMatch - This routine checks list of attributes for two |
1123 | | /// decls. It returns false, if there is a mismatch in kind of |
1124 | | /// attributes seen in the decls. It returns true if the two decls |
1125 | | /// have list of same kind of attributes. Furthermore, when there |
1126 | | /// are availability attributes in the two decls, it sets the |
1127 | | /// AvailabilityArgsMatch to false if availability attributes have |
1128 | | /// different versions, etc. |
1129 | | static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2, |
1130 | 117 | bool &AvailabilityArgsMatch) { |
1131 | 117 | if (!Decl1->hasAttrs() || !Decl2->hasAttrs()25 ) { |
1132 | 99 | AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs()); |
1133 | 99 | return true; |
1134 | 99 | } |
1135 | 18 | AvailabilityArgsMatch = true; |
1136 | 18 | const AttrVec &Attrs1 = Decl1->getAttrs(); |
1137 | 18 | const AttrVec &Attrs2 = Decl2->getAttrs(); |
1138 | 18 | bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch); |
1139 | 18 | if (match && (Attrs2.size() > Attrs1.size())14 ) |
1140 | 2 | return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch); |
1141 | 16 | return match; |
1142 | 18 | } |
1143 | | |
1144 | | static bool IsValidIdentifier(ASTContext &Ctx, |
1145 | 75 | const char *Name) { |
1146 | 75 | if (!isAsciiIdentifierStart(Name[0])) |
1147 | 15 | return false; |
1148 | 60 | std::string NameString = Name; |
1149 | 60 | NameString[0] = toLowercase(NameString[0]); |
1150 | 60 | IdentifierInfo *II = &Ctx.Idents.get(NameString); |
1151 | 60 | return II->getTokenID() == tok::identifier; |
1152 | 75 | } |
1153 | | |
1154 | | bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx, |
1155 | | ObjCContainerDecl *D, |
1156 | 601 | ObjCMethodDecl *Method) { |
1157 | 601 | if (Method->isPropertyAccessor() || !Method->isInstanceMethod()567 || |
1158 | 601 | Method->param_size() != 0495 ) |
1159 | 295 | return false; |
1160 | | // Is this method candidate to be a getter? |
1161 | 306 | QualType GRT = Method->getReturnType(); |
1162 | 306 | if (GRT->isVoidType()) |
1163 | 12 | return false; |
1164 | | |
1165 | 294 | Selector GetterSelector = Method->getSelector(); |
1166 | 294 | ObjCInstanceTypeFamily OIT_Family = |
1167 | 294 | Selector::getInstTypeMethodFamily(GetterSelector); |
1168 | | |
1169 | 294 | if (OIT_Family != OIT_None) |
1170 | 13 | return false; |
1171 | | |
1172 | 281 | IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0); |
1173 | 281 | Selector SetterSelector = |
1174 | 281 | SelectorTable::constructSetterSelector(PP.getIdentifierTable(), |
1175 | 281 | PP.getSelectorTable(), |
1176 | 281 | getterName); |
1177 | 281 | ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector); |
1178 | 281 | unsigned LengthOfPrefix = 0; |
1179 | 281 | if (!SetterMethod) { |
1180 | | // try a different naming convention for getter: isXxxxx |
1181 | 170 | StringRef getterNameString = getterName->getName(); |
1182 | 170 | bool IsPrefix = getterNameString.startswith("is"); |
1183 | | // Note that we don't want to change an isXXX method of retainable object |
1184 | | // type to property (readonly or otherwise). |
1185 | 170 | if (IsPrefix && GRT->isObjCRetainableType()36 ) |
1186 | 6 | return false; |
1187 | 164 | if (IsPrefix || getterNameString.startswith("get")134 ) { |
1188 | 75 | LengthOfPrefix = (IsPrefix ? 230 : 345 ); |
1189 | 75 | const char *CGetterName = getterNameString.data() + LengthOfPrefix; |
1190 | | // Make sure that first character after "is" or "get" prefix can |
1191 | | // start an identifier. |
1192 | 75 | if (!IsValidIdentifier(Ctx, CGetterName)) |
1193 | 18 | return false; |
1194 | 57 | if (CGetterName[0] && isUppercase(CGetterName[0])) { |
1195 | 48 | getterName = &Ctx.Idents.get(CGetterName); |
1196 | 48 | SetterSelector = |
1197 | 48 | SelectorTable::constructSetterSelector(PP.getIdentifierTable(), |
1198 | 48 | PP.getSelectorTable(), |
1199 | 48 | getterName); |
1200 | 48 | SetterMethod = D->getInstanceMethod(SetterSelector); |
1201 | 48 | } |
1202 | 57 | } |
1203 | 164 | } |
1204 | | |
1205 | 257 | if (SetterMethod) { |
1206 | 120 | if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0) |
1207 | 0 | return false; |
1208 | 120 | bool AvailabilityArgsMatch; |
1209 | 120 | if (SetterMethod->isDeprecated() || |
1210 | 120 | !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch)117 ) |
1211 | 9 | return false; |
1212 | | |
1213 | | // Is this a valid setter, matching the target getter? |
1214 | 111 | QualType SRT = SetterMethod->getReturnType(); |
1215 | 111 | if (!SRT->isVoidType()) |
1216 | 0 | return false; |
1217 | 111 | const ParmVarDecl *argDecl = *SetterMethod->param_begin(); |
1218 | 111 | QualType ArgType = argDecl->getType(); |
1219 | 111 | if (!Ctx.hasSameUnqualifiedType(ArgType, GRT)) |
1220 | 0 | return false; |
1221 | 111 | edit::Commit commit(*Editor); |
1222 | 111 | rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit, |
1223 | 111 | LengthOfPrefix, |
1224 | 111 | (ASTMigrateActions & |
1225 | 111 | FrontendOptions::ObjCMT_AtomicProperty) != 0, |
1226 | 111 | (ASTMigrateActions & |
1227 | 111 | FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0, |
1228 | 111 | AvailabilityArgsMatch); |
1229 | 111 | Editor->commit(commit); |
1230 | 111 | return true; |
1231 | 111 | } |
1232 | 137 | else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) { |
1233 | | // Try a non-void method with no argument (and no setter or property of same name |
1234 | | // as a 'readonly' property. |
1235 | 85 | edit::Commit commit(*Editor); |
1236 | 85 | rewriteToObjCProperty(Method, nullptr /*SetterMethod*/, *NSAPIObj, commit, |
1237 | 85 | LengthOfPrefix, |
1238 | 85 | (ASTMigrateActions & |
1239 | 85 | FrontendOptions::ObjCMT_AtomicProperty) != 0, |
1240 | 85 | (ASTMigrateActions & |
1241 | 85 | FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0, |
1242 | 85 | /*AvailabilityArgsMatch*/false); |
1243 | 85 | Editor->commit(commit); |
1244 | 85 | return true; |
1245 | 85 | } |
1246 | 52 | return false; |
1247 | 257 | } |
1248 | | |
1249 | | void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx, |
1250 | 132 | ObjCMethodDecl *OM) { |
1251 | 132 | if (OM->isImplicit() || |
1252 | 132 | !OM->isInstanceMethod()118 || |
1253 | 132 | OM->hasAttr<ObjCReturnsInnerPointerAttr>()97 ) |
1254 | 36 | return; |
1255 | | |
1256 | 96 | QualType RT = OM->getReturnType(); |
1257 | 96 | if (!TypeIsInnerPointer(RT) || |
1258 | 96 | !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER")8 ) |
1259 | 89 | return; |
1260 | | |
1261 | 7 | edit::Commit commit(*Editor); |
1262 | 7 | commit.insertBefore(OM->getEndLoc(), " NS_RETURNS_INNER_POINTER"); |
1263 | 7 | Editor->commit(commit); |
1264 | 7 | } |
1265 | | |
1266 | | void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, |
1267 | 5 | ObjCPropertyDecl *P) { |
1268 | 5 | QualType T = P->getType(); |
1269 | | |
1270 | 5 | if (!TypeIsInnerPointer(T) || |
1271 | 5 | !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER")4 ) |
1272 | 1 | return; |
1273 | 4 | edit::Commit commit(*Editor); |
1274 | 4 | commit.insertBefore(P->getEndLoc(), " NS_RETURNS_INNER_POINTER "); |
1275 | 4 | Editor->commit(commit); |
1276 | 4 | } |
1277 | | |
1278 | | void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx, |
1279 | 193 | ObjCContainerDecl *CDecl) { |
1280 | 193 | if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl)) |
1281 | 1 | return; |
1282 | | |
1283 | | // migrate methods which can have instancetype as their result type. |
1284 | 260 | for (auto *Method : CDecl->methods())192 { |
1285 | 260 | if (Method->isDeprecated()) |
1286 | 0 | continue; |
1287 | 260 | migrateMethodInstanceType(Ctx, CDecl, Method); |
1288 | 260 | } |
1289 | 192 | } |
1290 | | |
1291 | | void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx, |
1292 | | ObjCContainerDecl *CDecl, |
1293 | | ObjCMethodDecl *OM, |
1294 | 204 | ObjCInstanceTypeFamily OIT_Family) { |
1295 | 204 | if (OM->isInstanceMethod() || |
1296 | 204 | OM->getReturnType() == Ctx.getObjCInstanceType()51 || |
1297 | 204 | !OM->getReturnType()->isObjCIdType()51 ) |
1298 | 162 | return; |
1299 | | |
1300 | | // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class |
1301 | | // NSYYYNamE with matching names be at least 3 characters long. |
1302 | 42 | ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); |
1303 | 42 | if (!IDecl) { |
1304 | 8 | if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) |
1305 | 2 | IDecl = CatDecl->getClassInterface(); |
1306 | 6 | else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl)) |
1307 | 6 | IDecl = ImpDecl->getClassInterface(); |
1308 | 8 | } |
1309 | 42 | if (!IDecl) |
1310 | 0 | return; |
1311 | | |
1312 | 42 | std::string StringClassName = std::string(IDecl->getName()); |
1313 | 42 | StringRef LoweredClassName(StringClassName); |
1314 | 42 | std::string StringLoweredClassName = LoweredClassName.lower(); |
1315 | 42 | LoweredClassName = StringLoweredClassName; |
1316 | | |
1317 | 42 | IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0); |
1318 | | // Handle method with no name at its first selector slot; e.g. + (id):(int)x. |
1319 | 42 | if (!MethodIdName) |
1320 | 2 | return; |
1321 | | |
1322 | 40 | std::string MethodName = std::string(MethodIdName->getName()); |
1323 | 40 | if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf39 ) { |
1324 | 5 | StringRef STRefMethodName(MethodName); |
1325 | 5 | size_t len = 0; |
1326 | 5 | if (STRefMethodName.startswith("standard")) |
1327 | 1 | len = strlen("standard"); |
1328 | 4 | else if (STRefMethodName.startswith("shared")) |
1329 | 2 | len = strlen("shared"); |
1330 | 2 | else if (STRefMethodName.startswith("default")) |
1331 | 2 | len = strlen("default"); |
1332 | 0 | else |
1333 | 0 | return; |
1334 | 5 | MethodName = std::string(STRefMethodName.substr(len)); |
1335 | 5 | } |
1336 | 40 | std::string MethodNameSubStr = MethodName.substr(0, 3); |
1337 | 40 | StringRef MethodNamePrefix(MethodNameSubStr); |
1338 | 40 | std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower(); |
1339 | 40 | MethodNamePrefix = StringLoweredMethodNamePrefix; |
1340 | 40 | size_t Ix = LoweredClassName.rfind(MethodNamePrefix); |
1341 | 40 | if (Ix == StringRef::npos) |
1342 | 6 | return; |
1343 | 34 | std::string ClassNamePostfix = std::string(LoweredClassName.substr(Ix)); |
1344 | 34 | StringRef LoweredMethodName(MethodName); |
1345 | 34 | std::string StringLoweredMethodName = LoweredMethodName.lower(); |
1346 | 34 | LoweredMethodName = StringLoweredMethodName; |
1347 | 34 | if (!LoweredMethodName.startswith(ClassNamePostfix)) |
1348 | 0 | return; |
1349 | 34 | if (OIT_Family == OIT_ReturnsSelf) |
1350 | 4 | ReplaceWithClasstype(*this, OM); |
1351 | 30 | else |
1352 | 30 | ReplaceWithInstancetype(Ctx, *this, OM); |
1353 | 34 | } |
1354 | | |
1355 | 99 | static bool IsVoidStarType(QualType Ty) { |
1356 | 99 | if (!Ty->isPointerType()) |
1357 | 41 | return false; |
1358 | | |
1359 | 82 | while (const TypedefType *58 TD = dyn_cast<TypedefType>(Ty.getTypePtr())) |
1360 | 24 | Ty = TD->getDecl()->getUnderlyingType(); |
1361 | | |
1362 | | // Is the type void*? |
1363 | 58 | const PointerType* PT = Ty->castAs<PointerType>(); |
1364 | 58 | if (PT->getPointeeType().getUnqualifiedType()->isVoidType()) |
1365 | 29 | return true; |
1366 | 29 | return IsVoidStarType(PT->getPointeeType()); |
1367 | 58 | } |
1368 | | |
1369 | | /// AuditedType - This routine audits the type AT and returns false if it is one of known |
1370 | | /// CF object types or of the "void *" variety. It returns true if we don't care about the type |
1371 | | /// such as a non-pointer or pointers which have no ownership issues (such as "int *"). |
1372 | 167 | static bool AuditedType (QualType AT) { |
1373 | 167 | if (!AT->isAnyPointerType() && !AT->isBlockPointerType()67 ) |
1374 | 66 | return true; |
1375 | | // FIXME. There isn't much we can say about CF pointer type; or is there? |
1376 | 101 | if (ento::coreFoundation::isCFObjectRef(AT) || |
1377 | 101 | IsVoidStarType(AT)70 || |
1378 | | // If an ObjC object is type, assuming that it is not a CF function and |
1379 | | // that it is an un-audited function. |
1380 | 101 | AT->isObjCObjectPointerType()41 || AT->isObjCBuiltinType()25 ) |
1381 | 78 | return false; |
1382 | | // All other pointers are assumed audited as harmless. |
1383 | 23 | return true; |
1384 | 101 | } |
1385 | | |
1386 | 296 | void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) { |
1387 | 296 | if (CFFunctionIBCandidates.empty()) |
1388 | 288 | return; |
1389 | 8 | if (!NSAPIObj->isMacroDefined("CF_IMPLICIT_BRIDGING_ENABLED")) { |
1390 | 0 | CFFunctionIBCandidates.clear(); |
1391 | 0 | FileId = FileID(); |
1392 | 0 | return; |
1393 | 0 | } |
1394 | | // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED |
1395 | 8 | const Decl *FirstFD = CFFunctionIBCandidates[0]; |
1396 | 8 | const Decl *LastFD = |
1397 | 8 | CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1]; |
1398 | 8 | const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n"; |
1399 | 8 | edit::Commit commit(*Editor); |
1400 | 8 | commit.insertBefore(FirstFD->getBeginLoc(), PragmaString); |
1401 | 8 | PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n"; |
1402 | 8 | SourceLocation EndLoc = LastFD->getEndLoc(); |
1403 | | // get location just past end of function location. |
1404 | 8 | EndLoc = PP.getLocForEndOfToken(EndLoc); |
1405 | 8 | if (isa<FunctionDecl>(LastFD)) { |
1406 | | // For Methods, EndLoc points to the ending semcolon. So, |
1407 | | // not of these extra work is needed. |
1408 | 8 | Token Tok; |
1409 | | // get locaiton of token that comes after end of function. |
1410 | 8 | bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true); |
1411 | 8 | if (!Failed) |
1412 | 8 | EndLoc = Tok.getLocation(); |
1413 | 8 | } |
1414 | 8 | commit.insertAfterToken(EndLoc, PragmaString); |
1415 | 8 | Editor->commit(commit); |
1416 | 8 | FileId = FileID(); |
1417 | 8 | CFFunctionIBCandidates.clear(); |
1418 | 8 | } |
1419 | | |
1420 | 316 | void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) { |
1421 | 316 | if (Decl->isDeprecated()) |
1422 | 1 | return; |
1423 | | |
1424 | 315 | if (Decl->hasAttr<CFAuditedTransferAttr>()) { |
1425 | 1 | assert(CFFunctionIBCandidates.empty() && |
1426 | 1 | "Cannot have audited functions/methods inside user " |
1427 | 1 | "provided CF_IMPLICIT_BRIDGING_ENABLE"); |
1428 | 0 | return; |
1429 | 1 | } |
1430 | | |
1431 | | // Finction must be annotated first. |
1432 | 314 | if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) { |
1433 | 191 | CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl); |
1434 | 191 | if (AuditKind == CF_BRIDGING_ENABLE) { |
1435 | 13 | CFFunctionIBCandidates.push_back(Decl); |
1436 | 13 | if (FileId.isInvalid()) |
1437 | 8 | FileId = PP.getSourceManager().getFileID(Decl->getLocation()); |
1438 | 13 | } |
1439 | 178 | else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) { |
1440 | 8 | if (!CFFunctionIBCandidates.empty()) { |
1441 | 0 | CFFunctionIBCandidates.push_back(Decl); |
1442 | 0 | if (FileId.isInvalid()) |
1443 | 0 | FileId = PP.getSourceManager().getFileID(Decl->getLocation()); |
1444 | 0 | } |
1445 | 8 | } |
1446 | 170 | else |
1447 | 170 | AnnotateImplicitBridging(Ctx); |
1448 | 191 | } |
1449 | 123 | else { |
1450 | 123 | migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl)); |
1451 | 123 | AnnotateImplicitBridging(Ctx); |
1452 | 123 | } |
1453 | 314 | } |
1454 | | |
1455 | | void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx, |
1456 | | const RetainSummary *RS, |
1457 | | const FunctionDecl *FuncDecl, |
1458 | 41 | bool ResultAnnotated) { |
1459 | | // Annotate function. |
1460 | 41 | if (!ResultAnnotated) { |
1461 | 40 | RetEffect Ret = RS->getRetEffect(); |
1462 | 40 | const char *AnnotationString = nullptr; |
1463 | 40 | if (Ret.getObjKind() == ObjKind::CF) { |
1464 | 19 | if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED")17 ) |
1465 | 17 | AnnotationString = " CF_RETURNS_RETAINED"; |
1466 | 2 | else if (Ret.notOwned() && |
1467 | 2 | NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED")) |
1468 | 2 | AnnotationString = " CF_RETURNS_NOT_RETAINED"; |
1469 | 19 | } |
1470 | 21 | else if (Ret.getObjKind() == ObjKind::ObjC) { |
1471 | 0 | if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED")) |
1472 | 0 | AnnotationString = " NS_RETURNS_RETAINED"; |
1473 | 0 | } |
1474 | | |
1475 | 40 | if (AnnotationString) { |
1476 | 19 | edit::Commit commit(*Editor); |
1477 | 19 | commit.insertAfterToken(FuncDecl->getEndLoc(), AnnotationString); |
1478 | 19 | Editor->commit(commit); |
1479 | 19 | } |
1480 | 40 | } |
1481 | 41 | unsigned i = 0; |
1482 | 41 | for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(), |
1483 | 173 | pe = FuncDecl->param_end(); pi != pe; ++pi, ++i132 ) { |
1484 | 132 | const ParmVarDecl *pd = *pi; |
1485 | 132 | ArgEffect AE = RS->getArg(i); |
1486 | 132 | if (AE.getKind() == DecRef && AE.getObjKind() == ObjKind::CF4 && |
1487 | 132 | !pd->hasAttr<CFConsumedAttr>()2 && |
1488 | 132 | NSAPIObj->isMacroDefined("CF_CONSUMED")1 ) { |
1489 | 1 | edit::Commit commit(*Editor); |
1490 | 1 | commit.insertBefore(pd->getLocation(), "CF_CONSUMED "); |
1491 | 1 | Editor->commit(commit); |
1492 | 131 | } else if (AE.getKind() == DecRef && AE.getObjKind() == ObjKind::ObjC3 && |
1493 | 131 | !pd->hasAttr<NSConsumedAttr>()2 && |
1494 | 131 | NSAPIObj->isMacroDefined("NS_CONSUMED")0 ) { |
1495 | 0 | edit::Commit commit(*Editor); |
1496 | 0 | commit.insertBefore(pd->getLocation(), "NS_CONSUMED "); |
1497 | 0 | Editor->commit(commit); |
1498 | 0 | } |
1499 | 132 | } |
1500 | 41 | } |
1501 | | |
1502 | | ObjCMigrateASTConsumer::CF_BRIDGING_KIND |
1503 | | ObjCMigrateASTConsumer::migrateAddFunctionAnnotation( |
1504 | | ASTContext &Ctx, |
1505 | 191 | const FunctionDecl *FuncDecl) { |
1506 | 191 | if (FuncDecl->hasBody()) |
1507 | 116 | return CF_BRIDGING_NONE; |
1508 | | |
1509 | 75 | const RetainSummary *RS = |
1510 | 75 | getSummaryManager(Ctx).getSummary(AnyCall(FuncDecl)); |
1511 | 75 | bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() || |
1512 | 75 | FuncDecl->hasAttr<CFReturnsNotRetainedAttr>()72 || |
1513 | 75 | FuncDecl->hasAttr<NSReturnsRetainedAttr>()71 || |
1514 | 75 | FuncDecl->hasAttr<NSReturnsNotRetainedAttr>()70 || |
1515 | 75 | FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>()70 ); |
1516 | | |
1517 | | // Trivial case of when function is annotated and has no argument. |
1518 | 75 | if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 05 ) |
1519 | 3 | return CF_BRIDGING_NONE; |
1520 | | |
1521 | 72 | bool ReturnCFAudited = false; |
1522 | 72 | if (!FuncIsReturnAnnotated) { |
1523 | 70 | RetEffect Ret = RS->getRetEffect(); |
1524 | 70 | if (Ret.getObjKind() == ObjKind::CF && |
1525 | 70 | (28 Ret.isOwned()28 || Ret.notOwned()2 )) |
1526 | 28 | ReturnCFAudited = true; |
1527 | 42 | else if (!AuditedType(FuncDecl->getReturnType())) |
1528 | 10 | return CF_BRIDGING_NONE; |
1529 | 70 | } |
1530 | | |
1531 | | // At this point result type is audited for potential inclusion. |
1532 | 62 | unsigned i = 0; |
1533 | 62 | bool ArgCFAudited = false; |
1534 | 62 | for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(), |
1535 | 92 | pe = FuncDecl->param_end(); pi != pe; ++pi, ++i30 ) { |
1536 | 71 | const ParmVarDecl *pd = *pi; |
1537 | 71 | ArgEffect AE = RS->getArg(i); |
1538 | 71 | if ((AE.getKind() == DecRef /*CFConsumed annotated*/ || |
1539 | 71 | AE.getKind() == IncRef61 ) && AE.getObjKind() == ObjKind::CF10 ) { |
1540 | 8 | if (AE.getKind() == DecRef && !pd->hasAttr<CFConsumedAttr>()) |
1541 | 5 | ArgCFAudited = true; |
1542 | 3 | else if (AE.getKind() == IncRef) |
1543 | 0 | ArgCFAudited = true; |
1544 | 63 | } else { |
1545 | 63 | QualType AT = pd->getType(); |
1546 | 63 | if (!AuditedType(AT)) { |
1547 | 41 | AddCFAnnotations(Ctx, RS, FuncDecl, FuncIsReturnAnnotated); |
1548 | 41 | return CF_BRIDGING_NONE; |
1549 | 41 | } |
1550 | 63 | } |
1551 | 71 | } |
1552 | 21 | if (ReturnCFAudited || ArgCFAudited12 ) |
1553 | 13 | return CF_BRIDGING_ENABLE; |
1554 | | |
1555 | 8 | return CF_BRIDGING_MAY_INCLUDE; |
1556 | 21 | } |
1557 | | |
1558 | | void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx, |
1559 | 144 | ObjCContainerDecl *CDecl) { |
1560 | 144 | if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated()102 ) |
1561 | 42 | return; |
1562 | | |
1563 | | // migrate methods which can have instancetype as their result type. |
1564 | 102 | for (const auto *Method : CDecl->methods()) |
1565 | 123 | migrateCFAnnotation(Ctx, Method); |
1566 | 102 | } |
1567 | | |
1568 | | void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx, |
1569 | | const RetainSummary *RS, |
1570 | | const ObjCMethodDecl *MethodDecl, |
1571 | 59 | bool ResultAnnotated) { |
1572 | | // Annotate function. |
1573 | 59 | if (!ResultAnnotated) { |
1574 | 59 | RetEffect Ret = RS->getRetEffect(); |
1575 | 59 | const char *AnnotationString = nullptr; |
1576 | 59 | if (Ret.getObjKind() == ObjKind::CF) { |
1577 | 9 | if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED")6 ) |
1578 | 6 | AnnotationString = " CF_RETURNS_RETAINED"; |
1579 | 3 | else if (Ret.notOwned() && |
1580 | 3 | NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED")) |
1581 | 3 | AnnotationString = " CF_RETURNS_NOT_RETAINED"; |
1582 | 9 | } |
1583 | 50 | else if (Ret.getObjKind() == ObjKind::ObjC) { |
1584 | 38 | ObjCMethodFamily OMF = MethodDecl->getMethodFamily(); |
1585 | 38 | switch (OMF) { |
1586 | 2 | case clang::OMF_alloc: |
1587 | 6 | case clang::OMF_new: |
1588 | 6 | case clang::OMF_copy: |
1589 | 17 | case clang::OMF_init: |
1590 | 17 | case clang::OMF_mutableCopy: |
1591 | 17 | break; |
1592 | | |
1593 | 21 | default: |
1594 | 21 | if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED")2 ) |
1595 | 2 | AnnotationString = " NS_RETURNS_RETAINED"; |
1596 | 21 | break; |
1597 | 38 | } |
1598 | 38 | } |
1599 | | |
1600 | 59 | if (AnnotationString) { |
1601 | 11 | edit::Commit commit(*Editor); |
1602 | 11 | commit.insertBefore(MethodDecl->getEndLoc(), AnnotationString); |
1603 | 11 | Editor->commit(commit); |
1604 | 11 | } |
1605 | 59 | } |
1606 | 59 | unsigned i = 0; |
1607 | 59 | for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(), |
1608 | 114 | pe = MethodDecl->param_end(); pi != pe; ++pi, ++i55 ) { |
1609 | 55 | const ParmVarDecl *pd = *pi; |
1610 | 55 | ArgEffect AE = RS->getArg(i); |
1611 | 55 | if (AE.getKind() == DecRef |
1612 | 55 | && AE.getObjKind() == ObjKind::CF3 |
1613 | 55 | && !pd->hasAttr<CFConsumedAttr>()2 && |
1614 | 55 | NSAPIObj->isMacroDefined("CF_CONSUMED")0 ) { |
1615 | 0 | edit::Commit commit(*Editor); |
1616 | 0 | commit.insertBefore(pd->getLocation(), "CF_CONSUMED "); |
1617 | 0 | Editor->commit(commit); |
1618 | 0 | } |
1619 | 55 | } |
1620 | 59 | } |
1621 | | |
1622 | | void ObjCMigrateASTConsumer::migrateAddMethodAnnotation( |
1623 | | ASTContext &Ctx, |
1624 | 123 | const ObjCMethodDecl *MethodDecl) { |
1625 | 123 | if (MethodDecl->hasBody() || MethodDecl->isImplicit()) |
1626 | 14 | return; |
1627 | | |
1628 | 109 | const RetainSummary *RS = |
1629 | 109 | getSummaryManager(Ctx).getSummary(AnyCall(MethodDecl)); |
1630 | | |
1631 | 109 | bool MethodIsReturnAnnotated = |
1632 | 109 | (MethodDecl->hasAttr<CFReturnsRetainedAttr>() || |
1633 | 109 | MethodDecl->hasAttr<CFReturnsNotRetainedAttr>()106 || |
1634 | 109 | MethodDecl->hasAttr<NSReturnsRetainedAttr>()105 || |
1635 | 109 | MethodDecl->hasAttr<NSReturnsNotRetainedAttr>()101 || |
1636 | 109 | MethodDecl->hasAttr<NSReturnsAutoreleasedAttr>()99 ); |
1637 | | |
1638 | 109 | if (RS->getReceiverEffect().getKind() == DecRef && |
1639 | 109 | !MethodDecl->hasAttr<NSConsumesSelfAttr>()12 && |
1640 | 109 | MethodDecl->getMethodFamily() != OMF_init11 && |
1641 | 109 | MethodDecl->getMethodFamily() != OMF_release0 && |
1642 | 109 | NSAPIObj->isMacroDefined("NS_CONSUMES_SELF")0 ) { |
1643 | 0 | edit::Commit commit(*Editor); |
1644 | 0 | commit.insertBefore(MethodDecl->getEndLoc(), " NS_CONSUMES_SELF"); |
1645 | 0 | Editor->commit(commit); |
1646 | 0 | } |
1647 | | |
1648 | | // Trivial case of when function is annotated and has no argument. |
1649 | 109 | if (MethodIsReturnAnnotated && |
1650 | 109 | (MethodDecl->param_begin() == MethodDecl->param_end())11 ) |
1651 | 11 | return; |
1652 | | |
1653 | 98 | if (!MethodIsReturnAnnotated) { |
1654 | 98 | RetEffect Ret = RS->getRetEffect(); |
1655 | 98 | if ((Ret.getObjKind() == ObjKind::CF || |
1656 | 98 | Ret.getObjKind() == ObjKind::ObjC89 ) && |
1657 | 98 | (47 Ret.isOwned()47 || Ret.notOwned()22 )) { |
1658 | 47 | AddCFAnnotations(Ctx, RS, MethodDecl, false); |
1659 | 47 | return; |
1660 | 51 | } else if (!AuditedType(MethodDecl->getReturnType())) |
1661 | 16 | return; |
1662 | 98 | } |
1663 | | |
1664 | | // At this point result type is either annotated or audited. |
1665 | 35 | unsigned i = 0; |
1666 | 35 | for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(), |
1667 | 35 | pe = MethodDecl->param_end(); pi != pe; ++pi, ++i0 ) { |
1668 | 12 | const ParmVarDecl *pd = *pi; |
1669 | 12 | ArgEffect AE = RS->getArg(i); |
1670 | 12 | if ((AE.getKind() == DecRef && !pd->hasAttr<CFConsumedAttr>()2 ) || |
1671 | 12 | AE.getKind() == IncRef11 || !AuditedType(pd->getType())11 ) { |
1672 | 12 | AddCFAnnotations(Ctx, RS, MethodDecl, MethodIsReturnAnnotated); |
1673 | 12 | return; |
1674 | 12 | } |
1675 | 12 | } |
1676 | 35 | } |
1677 | | |
1678 | | namespace { |
1679 | | class SuperInitChecker : public RecursiveASTVisitor<SuperInitChecker> { |
1680 | | public: |
1681 | 0 | bool shouldVisitTemplateInstantiations() const { return false; } |
1682 | 0 | bool shouldWalkTypesOfTypeLocs() const { return false; } |
1683 | | |
1684 | 2 | bool VisitObjCMessageExpr(ObjCMessageExpr *E) { |
1685 | 2 | if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance) { |
1686 | 2 | if (E->getMethodFamily() == OMF_init) |
1687 | 2 | return false; |
1688 | 2 | } |
1689 | 0 | return true; |
1690 | 2 | } |
1691 | | }; |
1692 | | } // end anonymous namespace |
1693 | | |
1694 | 2 | static bool hasSuperInitCall(const ObjCMethodDecl *MD) { |
1695 | 2 | return !SuperInitChecker().TraverseStmt(MD->getBody()); |
1696 | 2 | } |
1697 | | |
1698 | | void ObjCMigrateASTConsumer::inferDesignatedInitializers( |
1699 | | ASTContext &Ctx, |
1700 | 3 | const ObjCImplementationDecl *ImplD) { |
1701 | | |
1702 | 3 | const ObjCInterfaceDecl *IFace = ImplD->getClassInterface(); |
1703 | 3 | if (!IFace || IFace->hasDesignatedInitializers()) |
1704 | 0 | return; |
1705 | 3 | if (!NSAPIObj->isMacroDefined("NS_DESIGNATED_INITIALIZER")) |
1706 | 0 | return; |
1707 | | |
1708 | 5 | for (const auto *MD : ImplD->instance_methods())3 { |
1709 | 5 | if (MD->isDeprecated() || |
1710 | 5 | MD->getMethodFamily() != OMF_init || |
1711 | 5 | MD->isDesignatedInitializerForTheInterface()3 ) |
1712 | 3 | continue; |
1713 | 2 | const ObjCMethodDecl *IFaceM = IFace->getMethod(MD->getSelector(), |
1714 | 2 | /*isInstance=*/true); |
1715 | 2 | if (!IFaceM) |
1716 | 0 | continue; |
1717 | 2 | if (hasSuperInitCall(MD)) { |
1718 | 2 | edit::Commit commit(*Editor); |
1719 | 2 | commit.insert(IFaceM->getEndLoc(), " NS_DESIGNATED_INITIALIZER"); |
1720 | 2 | Editor->commit(commit); |
1721 | 2 | } |
1722 | 2 | } |
1723 | 3 | } |
1724 | | |
1725 | | bool ObjCMigrateASTConsumer::InsertFoundation(ASTContext &Ctx, |
1726 | 50 | SourceLocation Loc) { |
1727 | 50 | if (FoundationIncluded) |
1728 | 46 | return true; |
1729 | 4 | if (Loc.isInvalid()) |
1730 | 0 | return false; |
1731 | 4 | auto *nsEnumId = &Ctx.Idents.get("NS_ENUM"); |
1732 | 4 | if (PP.getMacroDefinitionAtLoc(nsEnumId, Loc)) { |
1733 | 3 | FoundationIncluded = true; |
1734 | 3 | return true; |
1735 | 3 | } |
1736 | 1 | edit::Commit commit(*Editor); |
1737 | 1 | if (Ctx.getLangOpts().Modules) |
1738 | 1 | commit.insert(Loc, "#ifndef NS_ENUM\n@import Foundation;\n#endif\n"); |
1739 | 0 | else |
1740 | 0 | commit.insert(Loc, "#ifndef NS_ENUM\n#import <Foundation/Foundation.h>\n#endif\n"); |
1741 | 1 | Editor->commit(commit); |
1742 | 1 | FoundationIncluded = true; |
1743 | 1 | return true; |
1744 | 4 | } |
1745 | | |
1746 | | namespace { |
1747 | | |
1748 | | class RewritesReceiver : public edit::EditsReceiver { |
1749 | | Rewriter &Rewrite; |
1750 | | |
1751 | | public: |
1752 | 30 | RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { } |
1753 | | |
1754 | 74 | void insert(SourceLocation loc, StringRef text) override { |
1755 | 74 | Rewrite.InsertText(loc, text); |
1756 | 74 | } |
1757 | 1.03k | void replace(CharSourceRange range, StringRef text) override { |
1758 | 1.03k | Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text); |
1759 | 1.03k | } |
1760 | | }; |
1761 | | |
1762 | | class JSONEditWriter : public edit::EditsReceiver { |
1763 | | SourceManager &SourceMgr; |
1764 | | llvm::raw_ostream &OS; |
1765 | | |
1766 | | public: |
1767 | | JSONEditWriter(SourceManager &SM, llvm::raw_ostream &OS) |
1768 | 8 | : SourceMgr(SM), OS(OS) { |
1769 | 8 | OS << "[\n"; |
1770 | 8 | } |
1771 | 8 | ~JSONEditWriter() override { OS << "]\n"; } |
1772 | | |
1773 | | private: |
1774 | | struct EntryWriter { |
1775 | | SourceManager &SourceMgr; |
1776 | | llvm::raw_ostream &OS; |
1777 | | |
1778 | | EntryWriter(SourceManager &SM, llvm::raw_ostream &OS) |
1779 | 28 | : SourceMgr(SM), OS(OS) { |
1780 | 28 | OS << " {\n"; |
1781 | 28 | } |
1782 | 28 | ~EntryWriter() { |
1783 | 28 | OS << " },\n"; |
1784 | 28 | } |
1785 | | |
1786 | 28 | void writeLoc(SourceLocation Loc) { |
1787 | 28 | FileID FID; |
1788 | 28 | unsigned Offset; |
1789 | 28 | std::tie(FID, Offset) = SourceMgr.getDecomposedLoc(Loc); |
1790 | 28 | assert(FID.isValid()); |
1791 | 0 | SmallString<200> Path = |
1792 | 28 | StringRef(SourceMgr.getFileEntryForID(FID)->getName()); |
1793 | 28 | llvm::sys::fs::make_absolute(Path); |
1794 | 28 | OS << " \"file\": \""; |
1795 | 28 | OS.write_escaped(Path.str()) << "\",\n"; |
1796 | 28 | OS << " \"offset\": " << Offset << ",\n"; |
1797 | 28 | } |
1798 | | |
1799 | 26 | void writeRemove(CharSourceRange Range) { |
1800 | 26 | assert(Range.isCharRange()); |
1801 | 0 | std::pair<FileID, unsigned> Begin = |
1802 | 26 | SourceMgr.getDecomposedLoc(Range.getBegin()); |
1803 | 26 | std::pair<FileID, unsigned> End = |
1804 | 26 | SourceMgr.getDecomposedLoc(Range.getEnd()); |
1805 | 26 | assert(Begin.first == End.first); |
1806 | 0 | assert(Begin.second <= End.second); |
1807 | 0 | unsigned Length = End.second - Begin.second; |
1808 | | |
1809 | 26 | OS << " \"remove\": " << Length << ",\n"; |
1810 | 26 | } |
1811 | | |
1812 | 21 | void writeText(StringRef Text) { |
1813 | 21 | OS << " \"text\": \""; |
1814 | 21 | OS.write_escaped(Text) << "\",\n"; |
1815 | 21 | } |
1816 | | }; |
1817 | | |
1818 | 2 | void insert(SourceLocation Loc, StringRef Text) override { |
1819 | 2 | EntryWriter Writer(SourceMgr, OS); |
1820 | 2 | Writer.writeLoc(Loc); |
1821 | 2 | Writer.writeText(Text); |
1822 | 2 | } |
1823 | | |
1824 | 19 | void replace(CharSourceRange Range, StringRef Text) override { |
1825 | 19 | EntryWriter Writer(SourceMgr, OS); |
1826 | 19 | Writer.writeLoc(Range.getBegin()); |
1827 | 19 | Writer.writeRemove(Range); |
1828 | 19 | Writer.writeText(Text); |
1829 | 19 | } |
1830 | | |
1831 | 7 | void remove(CharSourceRange Range) override { |
1832 | 7 | EntryWriter Writer(SourceMgr, OS); |
1833 | 7 | Writer.writeLoc(Range.getBegin()); |
1834 | 7 | Writer.writeRemove(Range); |
1835 | 7 | } |
1836 | | }; |
1837 | | |
1838 | | } // end anonymous namespace |
1839 | | |
1840 | 29 | void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { |
1841 | | |
1842 | 29 | TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl(); |
1843 | 29 | if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) { |
1844 | 20 | for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end(); |
1845 | 987 | D != DEnd; ++D967 ) { |
1846 | 967 | FileID FID = PP.getSourceManager().getFileID((*D)->getLocation()); |
1847 | 967 | if (FID.isValid()) |
1848 | 787 | if (FileId.isValid() && FileId != FID18 ) { |
1849 | 0 | if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) |
1850 | 0 | AnnotateImplicitBridging(Ctx); |
1851 | 0 | } |
1852 | | |
1853 | 967 | if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D)) |
1854 | 225 | if (canModify(CDecl)) |
1855 | 201 | migrateObjCContainerDecl(Ctx, CDecl); |
1856 | 967 | if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) { |
1857 | 16 | if (canModify(CatDecl)) |
1858 | 15 | migrateObjCContainerDecl(Ctx, CatDecl); |
1859 | 16 | } |
1860 | 951 | else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D)) { |
1861 | 35 | ObjCProtocolDecls.insert(PDecl->getCanonicalDecl()); |
1862 | 35 | if (canModify(PDecl)) |
1863 | 35 | migrateObjCContainerDecl(Ctx, PDecl); |
1864 | 35 | } |
1865 | 916 | else if (const ObjCImplementationDecl *ImpDecl = |
1866 | 916 | dyn_cast<ObjCImplementationDecl>(*D)) { |
1867 | 37 | if ((ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) && |
1868 | 37 | canModify(ImpDecl)8 ) |
1869 | 8 | migrateProtocolConformance(Ctx, ImpDecl); |
1870 | 37 | } |
1871 | 879 | else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) { |
1872 | 62 | if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros)) |
1873 | 9 | continue; |
1874 | 53 | if (!canModify(ED)) |
1875 | 4 | continue; |
1876 | 49 | DeclContext::decl_iterator N = D; |
1877 | 49 | if (++N != DEnd) { |
1878 | 49 | const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N); |
1879 | 49 | if (migrateNSEnumDecl(Ctx, ED, TD) && TD43 ) |
1880 | 41 | D++; |
1881 | 49 | } |
1882 | 0 | else |
1883 | 0 | migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */nullptr); |
1884 | 49 | } |
1885 | 817 | else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) { |
1886 | 330 | if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros)) |
1887 | 237 | continue; |
1888 | 93 | if (!canModify(TD)) |
1889 | 51 | continue; |
1890 | 42 | DeclContext::decl_iterator N = D; |
1891 | 42 | if (++N == DEnd) |
1892 | 0 | continue; |
1893 | 42 | if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) { |
1894 | 12 | if (canModify(ED)) { |
1895 | 10 | if (++N != DEnd) |
1896 | 10 | if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) { |
1897 | | // prefer typedef-follows-enum to enum-follows-typedef pattern. |
1898 | 10 | if (migrateNSEnumDecl(Ctx, ED, TDF)) { |
1899 | 7 | ++D; ++D; |
1900 | 7 | CacheObjCNSIntegerTypedefed(TD); |
1901 | 7 | continue; |
1902 | 7 | } |
1903 | 10 | } |
1904 | 3 | if (migrateNSEnumDecl(Ctx, ED, TD)) { |
1905 | 0 | ++D; |
1906 | 0 | continue; |
1907 | 0 | } |
1908 | 3 | } |
1909 | 12 | } |
1910 | 35 | CacheObjCNSIntegerTypedefed(TD); |
1911 | 35 | } |
1912 | 487 | else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) { |
1913 | 194 | if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) && |
1914 | 194 | canModify(FD)193 ) |
1915 | 193 | migrateCFAnnotation(Ctx, FD); |
1916 | 194 | } |
1917 | | |
1918 | 659 | if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) { |
1919 | 316 | bool CanModify = canModify(CDecl); |
1920 | | // migrate methods which can have instancetype as their result type. |
1921 | 316 | if ((ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) && |
1922 | 316 | CanModify208 ) |
1923 | 193 | migrateAllMethodInstaceType(Ctx, CDecl); |
1924 | | // annotate methods with CF annotations. |
1925 | 316 | if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) && |
1926 | 316 | CanModify147 ) |
1927 | 144 | migrateARCSafeAnnotation(Ctx, CDecl); |
1928 | 316 | } |
1929 | | |
1930 | 659 | if (const ObjCImplementationDecl * |
1931 | 659 | ImplD = dyn_cast<ObjCImplementationDecl>(*D)) { |
1932 | 37 | if ((ASTMigrateActions & FrontendOptions::ObjCMT_DesignatedInitializer) && |
1933 | 37 | canModify(ImplD)3 ) |
1934 | 3 | inferDesignatedInitializers(Ctx, ImplD); |
1935 | 37 | } |
1936 | 659 | } |
1937 | 20 | if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) |
1938 | 3 | AnnotateImplicitBridging(Ctx); |
1939 | 20 | } |
1940 | | |
1941 | 29 | if (IsOutputFile) { |
1942 | 8 | std::error_code EC; |
1943 | 8 | llvm::raw_fd_ostream OS(MigrateDir, EC, llvm::sys::fs::OF_None); |
1944 | 8 | if (EC) { |
1945 | 0 | DiagnosticsEngine &Diags = Ctx.getDiagnostics(); |
1946 | 0 | Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0")) |
1947 | 0 | << EC.message(); |
1948 | 0 | return; |
1949 | 0 | } |
1950 | | |
1951 | 8 | JSONEditWriter Writer(Ctx.getSourceManager(), OS); |
1952 | 8 | Editor->applyRewrites(Writer); |
1953 | 8 | return; |
1954 | 8 | } |
1955 | | |
1956 | 21 | Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts()); |
1957 | 21 | RewritesReceiver Rec(rewriter); |
1958 | 21 | Editor->applyRewrites(Rec); |
1959 | | |
1960 | 21 | for (Rewriter::buffer_iterator |
1961 | 42 | I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I21 ) { |
1962 | 21 | FileID FID = I->first; |
1963 | 21 | RewriteBuffer &buf = I->second; |
1964 | 21 | Optional<FileEntryRef> file = Ctx.getSourceManager().getFileEntryRefForID(FID); |
1965 | 21 | assert(file); |
1966 | 0 | SmallString<512> newText; |
1967 | 21 | llvm::raw_svector_ostream vecOS(newText); |
1968 | 21 | buf.write(vecOS); |
1969 | 21 | std::unique_ptr<llvm::MemoryBuffer> memBuf( |
1970 | 21 | llvm::MemoryBuffer::getMemBufferCopy( |
1971 | 21 | StringRef(newText.data(), newText.size()), file->getName())); |
1972 | 21 | SmallString<64> filePath(file->getName()); |
1973 | 21 | FileMgr.FixupRelativePath(filePath); |
1974 | 21 | Remapper.remap(filePath.str(), std::move(memBuf)); |
1975 | 21 | } |
1976 | | |
1977 | 21 | if (IsOutputFile) { |
1978 | 0 | Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics()); |
1979 | 21 | } else { |
1980 | 21 | Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics()); |
1981 | 21 | } |
1982 | 21 | } |
1983 | | |
1984 | 8 | bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) { |
1985 | 8 | CI.getDiagnostics().setIgnoreAllWarnings(true); |
1986 | 8 | return true; |
1987 | 8 | } |
1988 | | |
1989 | 8 | static std::vector<std::string> getAllowListFilenames(StringRef DirPath) { |
1990 | 8 | using namespace llvm::sys::fs; |
1991 | 8 | using namespace llvm::sys::path; |
1992 | | |
1993 | 8 | std::vector<std::string> Filenames; |
1994 | 8 | if (DirPath.empty() || !is_directory(DirPath)2 ) |
1995 | 6 | return Filenames; |
1996 | | |
1997 | 2 | std::error_code EC; |
1998 | 2 | directory_iterator DI = directory_iterator(DirPath, EC); |
1999 | 2 | directory_iterator DE; |
2000 | 4 | for (; !EC && DI != DE; DI = DI.increment(EC)2 ) { |
2001 | 2 | if (is_regular_file(DI->path())) |
2002 | 2 | Filenames.push_back(std::string(filename(DI->path()))); |
2003 | 2 | } |
2004 | | |
2005 | 2 | return Filenames; |
2006 | 8 | } |
2007 | | |
2008 | | std::unique_ptr<ASTConsumer> |
2009 | 8 | MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { |
2010 | 8 | PPConditionalDirectiveRecord * |
2011 | 8 | PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager()); |
2012 | 8 | unsigned ObjCMTAction = CI.getFrontendOpts().ObjCMTAction; |
2013 | 8 | unsigned ObjCMTOpts = ObjCMTAction; |
2014 | | // These are companion flags, they do not enable transformations. |
2015 | 8 | ObjCMTOpts &= ~(FrontendOptions::ObjCMT_AtomicProperty | |
2016 | 8 | FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty); |
2017 | 8 | if (ObjCMTOpts == FrontendOptions::ObjCMT_None) { |
2018 | | // If no specific option was given, enable literals+subscripting transforms |
2019 | | // by default. |
2020 | 0 | ObjCMTAction |= |
2021 | 0 | FrontendOptions::ObjCMT_Literals | FrontendOptions::ObjCMT_Subscripting; |
2022 | 0 | } |
2023 | 8 | CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec)); |
2024 | 8 | std::vector<std::string> AllowList = |
2025 | 8 | getAllowListFilenames(CI.getFrontendOpts().ObjCMTAllowListPath); |
2026 | 8 | return std::make_unique<ObjCMigrateASTConsumer>( |
2027 | 8 | CI.getFrontendOpts().OutputFile, ObjCMTAction, Remapper, |
2028 | 8 | CI.getFileManager(), PPRec, CI.getPreprocessor(), |
2029 | 8 | /*isOutputFile=*/true, AllowList); |
2030 | 8 | } |
2031 | | |
2032 | | namespace { |
2033 | | struct EditEntry { |
2034 | | Optional<FileEntryRef> File; |
2035 | | unsigned Offset = 0; |
2036 | | unsigned RemoveLen = 0; |
2037 | | std::string Text; |
2038 | | }; |
2039 | | } // end anonymous namespace |
2040 | | |
2041 | | namespace llvm { |
2042 | | template<> struct DenseMapInfo<EditEntry> { |
2043 | 65 | static inline EditEntry getEmptyKey() { |
2044 | 65 | EditEntry Entry; |
2045 | 65 | Entry.Offset = unsigned(-1); |
2046 | 65 | return Entry; |
2047 | 65 | } |
2048 | 35 | static inline EditEntry getTombstoneKey() { |
2049 | 35 | EditEntry Entry; |
2050 | 35 | Entry.Offset = unsigned(-2); |
2051 | 35 | return Entry; |
2052 | 35 | } |
2053 | 29 | static unsigned getHashValue(const EditEntry& Val) { |
2054 | 29 | return (unsigned)llvm::hash_combine(Val.File, Val.Offset, Val.RemoveLen, |
2055 | 29 | Val.Text); |
2056 | 29 | } |
2057 | 546 | static bool isEqual(const EditEntry &LHS, const EditEntry &RHS) { |
2058 | 546 | return LHS.File == RHS.File && |
2059 | 546 | LHS.Offset == RHS.Offset413 && |
2060 | 546 | LHS.RemoveLen == RHS.RemoveLen413 && |
2061 | 546 | LHS.Text == RHS.Text413 ; |
2062 | 546 | } |
2063 | | }; |
2064 | | } // end namespace llvm |
2065 | | |
2066 | | namespace { |
2067 | | class RemapFileParser { |
2068 | | FileManager &FileMgr; |
2069 | | |
2070 | | public: |
2071 | 6 | RemapFileParser(FileManager &FileMgr) : FileMgr(FileMgr) { } |
2072 | | |
2073 | 7 | bool parse(StringRef File, SmallVectorImpl<EditEntry> &Entries) { |
2074 | 7 | using namespace llvm::yaml; |
2075 | | |
2076 | 7 | llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr = |
2077 | 7 | llvm::MemoryBuffer::getFile(File); |
2078 | 7 | if (!FileBufOrErr) |
2079 | 0 | return true; |
2080 | | |
2081 | 7 | llvm::SourceMgr SM; |
2082 | 7 | Stream YAMLStream(FileBufOrErr.get()->getMemBufferRef(), SM); |
2083 | 7 | document_iterator I = YAMLStream.begin(); |
2084 | 7 | if (I == YAMLStream.end()) |
2085 | 0 | return true; |
2086 | 7 | Node *Root = I->getRoot(); |
2087 | 7 | if (!Root) |
2088 | 0 | return true; |
2089 | | |
2090 | 7 | SequenceNode *SeqNode = dyn_cast<SequenceNode>(Root); |
2091 | 7 | if (!SeqNode) |
2092 | 0 | return true; |
2093 | | |
2094 | 7 | for (SequenceNode::iterator |
2095 | 36 | AI = SeqNode->begin(), AE = SeqNode->end(); AI != AE; ++AI29 ) { |
2096 | 29 | MappingNode *MapNode = dyn_cast<MappingNode>(&*AI); |
2097 | 29 | if (!MapNode) |
2098 | 0 | continue; |
2099 | 29 | parseEdit(MapNode, Entries); |
2100 | 29 | } |
2101 | | |
2102 | 7 | return false; |
2103 | 7 | } |
2104 | | |
2105 | | private: |
2106 | | void parseEdit(llvm::yaml::MappingNode *Node, |
2107 | 29 | SmallVectorImpl<EditEntry> &Entries) { |
2108 | 29 | using namespace llvm::yaml; |
2109 | 29 | EditEntry Entry; |
2110 | 29 | bool Ignore = false; |
2111 | | |
2112 | 29 | for (MappingNode::iterator |
2113 | 135 | KVI = Node->begin(), KVE = Node->end(); KVI != KVE; ++KVI106 ) { |
2114 | 106 | ScalarNode *KeyString = dyn_cast<ScalarNode>((*KVI).getKey()); |
2115 | 106 | if (!KeyString) |
2116 | 0 | continue; |
2117 | 106 | SmallString<10> KeyStorage; |
2118 | 106 | StringRef Key = KeyString->getValue(KeyStorage); |
2119 | | |
2120 | 106 | ScalarNode *ValueString = dyn_cast<ScalarNode>((*KVI).getValue()); |
2121 | 106 | if (!ValueString) |
2122 | 0 | continue; |
2123 | 106 | SmallString<64> ValueStorage; |
2124 | 106 | StringRef Val = ValueString->getValue(ValueStorage); |
2125 | | |
2126 | 106 | if (Key == "file") { |
2127 | 29 | if (auto File = FileMgr.getOptionalFileRef(Val)) |
2128 | 29 | Entry.File = File; |
2129 | 0 | else |
2130 | 0 | Ignore = true; |
2131 | 77 | } else if (Key == "offset") { |
2132 | 29 | if (Val.getAsInteger(10, Entry.Offset)) |
2133 | 0 | Ignore = true; |
2134 | 48 | } else if (Key == "remove") { |
2135 | 27 | if (Val.getAsInteger(10, Entry.RemoveLen)) |
2136 | 0 | Ignore = true; |
2137 | 27 | } else if (21 Key == "text"21 ) { |
2138 | 21 | Entry.Text = std::string(Val); |
2139 | 21 | } |
2140 | 106 | } |
2141 | | |
2142 | 29 | if (!Ignore) |
2143 | 29 | Entries.push_back(Entry); |
2144 | 29 | } |
2145 | | }; |
2146 | | } // end anonymous namespace |
2147 | | |
2148 | 0 | static bool reportDiag(const Twine &Err, DiagnosticsEngine &Diag) { |
2149 | 0 | Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0")) |
2150 | 0 | << Err.str(); |
2151 | 0 | return true; |
2152 | 0 | } |
2153 | | |
2154 | | static std::string applyEditsToTemp(FileEntryRef FE, |
2155 | | ArrayRef<EditEntry> Edits, |
2156 | | FileManager &FileMgr, |
2157 | 9 | DiagnosticsEngine &Diag) { |
2158 | 9 | using namespace llvm::sys; |
2159 | | |
2160 | 9 | SourceManager SM(Diag, FileMgr); |
2161 | 9 | FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User); |
2162 | 9 | LangOptions LangOpts; |
2163 | 9 | edit::EditedSource Editor(SM, LangOpts); |
2164 | 9 | for (ArrayRef<EditEntry>::iterator |
2165 | 33 | I = Edits.begin(), E = Edits.end(); I != E; ++I24 ) { |
2166 | 24 | const EditEntry &Entry = *I; |
2167 | 24 | assert(Entry.File == FE); |
2168 | 0 | SourceLocation Loc = |
2169 | 24 | SM.getLocForStartOfFile(FID).getLocWithOffset(Entry.Offset); |
2170 | 24 | CharSourceRange Range; |
2171 | 24 | if (Entry.RemoveLen != 0) { |
2172 | 22 | Range = CharSourceRange::getCharRange(Loc, |
2173 | 22 | Loc.getLocWithOffset(Entry.RemoveLen)); |
2174 | 22 | } |
2175 | | |
2176 | 24 | edit::Commit commit(Editor); |
2177 | 24 | if (Range.isInvalid()) { |
2178 | 2 | commit.insert(Loc, Entry.Text); |
2179 | 22 | } else if (Entry.Text.empty()) { |
2180 | 7 | commit.remove(Range); |
2181 | 15 | } else { |
2182 | 15 | commit.replace(Range, Entry.Text); |
2183 | 15 | } |
2184 | 24 | Editor.commit(commit); |
2185 | 24 | } |
2186 | | |
2187 | 9 | Rewriter rewriter(SM, LangOpts); |
2188 | 9 | RewritesReceiver Rec(rewriter); |
2189 | 9 | Editor.applyRewrites(Rec, /*adjustRemovals=*/false); |
2190 | | |
2191 | 9 | const RewriteBuffer *Buf = rewriter.getRewriteBufferFor(FID); |
2192 | 9 | SmallString<512> NewText; |
2193 | 9 | llvm::raw_svector_ostream OS(NewText); |
2194 | 9 | Buf->write(OS); |
2195 | | |
2196 | 9 | SmallString<64> TempPath; |
2197 | 9 | int FD; |
2198 | 9 | if (fs::createTemporaryFile(path::filename(FE.getName()), |
2199 | 9 | path::extension(FE.getName()).drop_front(), FD, |
2200 | 9 | TempPath)) { |
2201 | 0 | reportDiag("Could not create file: " + TempPath.str(), Diag); |
2202 | 0 | return std::string(); |
2203 | 0 | } |
2204 | | |
2205 | 9 | llvm::raw_fd_ostream TmpOut(FD, /*shouldClose=*/true); |
2206 | 9 | TmpOut.write(NewText.data(), NewText.size()); |
2207 | 9 | TmpOut.close(); |
2208 | | |
2209 | 9 | return std::string(TempPath.str()); |
2210 | 9 | } |
2211 | | |
2212 | | bool arcmt::getFileRemappingsFromFileList( |
2213 | | std::vector<std::pair<std::string,std::string> > &remap, |
2214 | | ArrayRef<StringRef> remapFiles, |
2215 | 6 | DiagnosticConsumer *DiagClient) { |
2216 | 6 | bool hasErrorOccurred = false; |
2217 | | |
2218 | 6 | FileSystemOptions FSOpts; |
2219 | 6 | FileManager FileMgr(FSOpts); |
2220 | 6 | RemapFileParser Parser(FileMgr); |
2221 | | |
2222 | 6 | IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); |
2223 | 6 | IntrusiveRefCntPtr<DiagnosticsEngine> Diags( |
2224 | 6 | new DiagnosticsEngine(DiagID, new DiagnosticOptions, |
2225 | 6 | DiagClient, /*ShouldOwnClient=*/false)); |
2226 | | |
2227 | 6 | typedef llvm::DenseMap<FileEntryRef, std::vector<EditEntry> > |
2228 | 6 | FileEditEntriesTy; |
2229 | 6 | FileEditEntriesTy FileEditEntries; |
2230 | | |
2231 | 6 | llvm::DenseSet<EditEntry> EntriesSet; |
2232 | | |
2233 | 6 | for (ArrayRef<StringRef>::iterator |
2234 | 13 | I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I7 ) { |
2235 | 7 | SmallVector<EditEntry, 16> Entries; |
2236 | 7 | if (Parser.parse(*I, Entries)) |
2237 | 0 | continue; |
2238 | | |
2239 | 7 | for (SmallVectorImpl<EditEntry>::iterator |
2240 | 36 | EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI29 ) { |
2241 | 29 | EditEntry &Entry = *EI; |
2242 | 29 | if (!Entry.File) |
2243 | 0 | continue; |
2244 | 29 | std::pair<llvm::DenseSet<EditEntry>::iterator, bool> |
2245 | 29 | Insert = EntriesSet.insert(Entry); |
2246 | 29 | if (!Insert.second) |
2247 | 5 | continue; |
2248 | | |
2249 | 24 | FileEditEntries[*Entry.File].push_back(Entry); |
2250 | 24 | } |
2251 | 7 | } |
2252 | | |
2253 | 6 | for (FileEditEntriesTy::iterator |
2254 | 15 | I = FileEditEntries.begin(), E = FileEditEntries.end(); I != E; ++I9 ) { |
2255 | 9 | std::string TempFile = applyEditsToTemp(I->first, I->second, |
2256 | 9 | FileMgr, *Diags); |
2257 | 9 | if (TempFile.empty()) { |
2258 | 0 | hasErrorOccurred = true; |
2259 | 0 | continue; |
2260 | 0 | } |
2261 | | |
2262 | 9 | remap.emplace_back(std::string(I->first.getName()), TempFile); |
2263 | 9 | } |
2264 | | |
2265 | 6 | return hasErrorOccurred; |
2266 | 6 | } |