1 //===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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"
36 using namespace clang
;
37 using namespace arcmt
;
42 class ObjCMigrateASTConsumer
: public ASTConsumer
{
43 enum CF_BRIDGING_KIND
{
46 CF_BRIDGING_MAY_INCLUDE
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
,
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
,
64 ObjCInstanceTypeFamily OIT_Family
= OIT_None
);
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
);
74 void AnnotateImplicitBridging(ASTContext
&Ctx
);
76 CF_BRIDGING_KIND
migrateAddFunctionAnnotation(ASTContext
&Ctx
,
77 const FunctionDecl
*FuncDecl
);
79 void migrateARCSafeAnnotation(ASTContext
&Ctx
, ObjCContainerDecl
*CDecl
);
81 void migrateAddMethodAnnotation(ASTContext
&Ctx
,
82 const ObjCMethodDecl
*MethodDecl
);
84 void inferDesignatedInitializers(ASTContext
&Ctx
,
85 const ObjCImplementationDecl
*ImplD
);
87 bool InsertFoundation(ASTContext
&Ctx
, SourceLocation Loc
);
89 std::unique_ptr
<RetainSummaryManager
> Summaries
;
92 std::string MigrateDir
;
93 unsigned ASTMigrateActions
;
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
;
104 bool FoundationIncluded
;
105 llvm::SmallPtrSet
<ObjCProtocolDecl
*, 32> ObjCProtocolDecls
;
106 llvm::SmallVector
<const Decl
*, 8> CFFunctionIBCandidates
;
107 llvm::StringSet
<> AllowListFilenames
;
109 RetainSummaryManager
&getSummaryManager(ASTContext
&Ctx
) {
111 Summaries
.reset(new RetainSummaryManager(Ctx
,
112 /*TrackNSCFObjects=*/true,
113 /*trackOSObjects=*/false));
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 IsOutputFile(isOutputFile
), FoundationIncluded(false) {
126 // FIXME: StringSet should have insert(iter, iter) to use here.
127 for (const std::string
&Val
: AllowList
)
128 AllowListFilenames
.insert(Val
);
132 void Initialize(ASTContext
&Context
) override
{
133 NSAPIObj
.reset(new NSAPI(Context
));
134 Editor
.reset(new edit::EditedSource(Context
.getSourceManager(),
135 Context
.getLangOpts(),
139 bool HandleTopLevelDecl(DeclGroupRef DG
) override
{
140 for (DeclGroupRef::iterator I
= DG
.begin(), E
= DG
.end(); I
!= E
; ++I
)
144 void HandleInterestingDecl(DeclGroupRef DG
) override
{
145 // Ignore decls from the PCH.
147 void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG
) override
{
148 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG
);
151 void HandleTranslationUnit(ASTContext
&Ctx
) override
;
153 bool canModifyFile(StringRef Path
) {
154 if (AllowListFilenames
.empty())
156 return AllowListFilenames
.find(llvm::sys::path::filename(Path
)) !=
157 AllowListFilenames
.end();
159 bool canModifyFile(Optional
<FileEntryRef
> FE
) {
162 return canModifyFile(FE
->getName());
164 bool canModifyFile(FileID FID
) {
167 return canModifyFile(PP
.getSourceManager().getFileEntryRefForID(FID
));
170 bool canModify(const Decl
*D
) {
173 if (const ObjCCategoryImplDecl
*CatImpl
= dyn_cast
<ObjCCategoryImplDecl
>(D
))
174 return canModify(CatImpl
->getCategoryDecl());
175 if (const ObjCImplementationDecl
*Impl
= dyn_cast
<ObjCImplementationDecl
>(D
))
176 return canModify(Impl
->getClassInterface());
177 if (const ObjCMethodDecl
*MD
= dyn_cast
<ObjCMethodDecl
>(D
))
178 return canModify(cast
<Decl
>(MD
->getDeclContext()));
180 FileID FID
= PP
.getSourceManager().getFileID(D
->getLocation());
181 return canModifyFile(FID
);
185 } // end anonymous namespace
187 ObjCMigrateAction::ObjCMigrateAction(
188 std::unique_ptr
<FrontendAction
> WrappedAction
, StringRef migrateDir
,
189 unsigned migrateAction
)
190 : WrapperFrontendAction(std::move(WrappedAction
)), MigrateDir(migrateDir
),
191 ObjCMigAction(migrateAction
), CompInst(nullptr) {
192 if (MigrateDir
.empty())
193 MigrateDir
= "."; // user current directory if none is given.
196 std::unique_ptr
<ASTConsumer
>
197 ObjCMigrateAction::CreateASTConsumer(CompilerInstance
&CI
, StringRef InFile
) {
198 PPConditionalDirectiveRecord
*
199 PPRec
= new PPConditionalDirectiveRecord(CompInst
->getSourceManager());
200 CI
.getPreprocessor().addPPCallbacks(std::unique_ptr
<PPCallbacks
>(PPRec
));
201 std::vector
<std::unique_ptr
<ASTConsumer
>> Consumers
;
202 Consumers
.push_back(WrapperFrontendAction::CreateASTConsumer(CI
, InFile
));
203 Consumers
.push_back(std::make_unique
<ObjCMigrateASTConsumer
>(
204 MigrateDir
, ObjCMigAction
, Remapper
, CompInst
->getFileManager(), PPRec
,
205 CompInst
->getPreprocessor(), false, None
));
206 return std::make_unique
<MultiplexConsumer
>(std::move(Consumers
));
209 bool ObjCMigrateAction::BeginInvocation(CompilerInstance
&CI
) {
210 Remapper
.initFromDisk(MigrateDir
, CI
.getDiagnostics(),
211 /*ignoreIfFilesChanged=*/true);
213 CI
.getDiagnostics().setIgnoreAllWarnings(true);
218 // FIXME. This duplicates one in RewriteObjCFoundationAPI.cpp
219 bool subscriptOperatorNeedsParens(const Expr
*FullExpr
) {
220 const Expr
* Expr
= FullExpr
->IgnoreImpCasts();
221 return !(isa
<ArraySubscriptExpr
>(Expr
) || isa
<CallExpr
>(Expr
) ||
222 isa
<DeclRefExpr
>(Expr
) || isa
<CXXNamedCastExpr
>(Expr
) ||
223 isa
<CXXConstructExpr
>(Expr
) || isa
<CXXThisExpr
>(Expr
) ||
224 isa
<CXXTypeidExpr
>(Expr
) ||
225 isa
<CXXUnresolvedConstructExpr
>(Expr
) ||
226 isa
<ObjCMessageExpr
>(Expr
) || isa
<ObjCPropertyRefExpr
>(Expr
) ||
227 isa
<ObjCProtocolExpr
>(Expr
) || isa
<MemberExpr
>(Expr
) ||
228 isa
<ObjCIvarRefExpr
>(Expr
) || isa
<ParenExpr
>(FullExpr
) ||
229 isa
<ParenListExpr
>(Expr
) || isa
<SizeOfPackExpr
>(Expr
));
232 /// - Rewrite message expression for Objective-C setter and getters into
233 /// property-dot syntax.
234 bool rewriteToPropertyDotSyntax(const ObjCMessageExpr
*Msg
,
236 const NSAPI
&NS
, edit::Commit
&commit
,
237 const ParentMap
*PMap
) {
238 if (!Msg
|| Msg
->isImplicit() ||
239 (Msg
->getReceiverKind() != ObjCMessageExpr::Instance
&&
240 Msg
->getReceiverKind() != ObjCMessageExpr::SuperInstance
))
242 if (const Expr
*Receiver
= Msg
->getInstanceReceiver())
243 if (Receiver
->getType()->isObjCBuiltinType())
246 const ObjCMethodDecl
*Method
= Msg
->getMethodDecl();
249 if (!Method
->isPropertyAccessor())
252 const ObjCPropertyDecl
*Prop
= Method
->findPropertyDecl();
256 SourceRange MsgRange
= Msg
->getSourceRange();
257 bool ReceiverIsSuper
=
258 (Msg
->getReceiverKind() == ObjCMessageExpr::SuperInstance
);
259 // for 'super' receiver is nullptr.
260 const Expr
*receiver
= Msg
->getInstanceReceiver();
262 ReceiverIsSuper
? false : subscriptOperatorNeedsParens(receiver
);
263 bool IsGetter
= (Msg
->getNumArgs() == 0);
265 // Find space location range between receiver expression and getter method.
266 SourceLocation BegLoc
=
267 ReceiverIsSuper
? Msg
->getSuperLoc() : receiver
->getEndLoc();
268 BegLoc
= PP
.getLocForEndOfToken(BegLoc
);
269 SourceLocation EndLoc
= Msg
->getSelectorLoc(0);
270 SourceRange
SpaceRange(BegLoc
, EndLoc
);
271 std::string PropertyDotString
;
272 // rewrite getter method expression into: receiver.property or
273 // (receiver).property
275 commit
.insertBefore(receiver
->getBeginLoc(), "(");
276 PropertyDotString
= ").";
279 PropertyDotString
= ".";
280 PropertyDotString
+= Prop
->getName();
281 commit
.replace(SpaceRange
, PropertyDotString
);
284 commit
.replace(SourceRange(MsgRange
.getBegin(), MsgRange
.getBegin()), "");
285 commit
.replace(SourceRange(MsgRange
.getEnd(), MsgRange
.getEnd()), "");
288 commit
.insertWrap("(", receiver
->getSourceRange(), ")");
289 std::string PropertyDotString
= ".";
290 PropertyDotString
+= Prop
->getName();
291 PropertyDotString
+= " =";
292 const Expr
*const* Args
= Msg
->getArgs();
293 const Expr
*RHS
= Args
[0];
296 SourceLocation BegLoc
=
297 ReceiverIsSuper
? Msg
->getSuperLoc() : receiver
->getEndLoc();
298 BegLoc
= PP
.getLocForEndOfToken(BegLoc
);
299 SourceLocation EndLoc
= RHS
->getBeginLoc();
300 EndLoc
= EndLoc
.getLocWithOffset(-1);
301 const char *colon
= PP
.getSourceManager().getCharacterData(EndLoc
);
302 // Add a space after '=' if there is no space between RHS and '='
303 if (colon
&& colon
[0] == ':')
304 PropertyDotString
+= " ";
305 SourceRange
Range(BegLoc
, EndLoc
);
306 commit
.replace(Range
, PropertyDotString
);
308 commit
.replace(SourceRange(MsgRange
.getBegin(), MsgRange
.getBegin()), "");
309 commit
.replace(SourceRange(MsgRange
.getEnd(), MsgRange
.getEnd()), "");
314 class ObjCMigrator
: public RecursiveASTVisitor
<ObjCMigrator
> {
315 ObjCMigrateASTConsumer
&Consumer
;
319 ObjCMigrator(ObjCMigrateASTConsumer
&consumer
, ParentMap
&PMap
)
320 : Consumer(consumer
), PMap(PMap
) { }
322 bool shouldVisitTemplateInstantiations() const { return false; }
323 bool shouldWalkTypesOfTypeLocs() const { return false; }
325 bool VisitObjCMessageExpr(ObjCMessageExpr
*E
) {
326 if (Consumer
.ASTMigrateActions
& FrontendOptions::ObjCMT_Literals
) {
327 edit::Commit
commit(*Consumer
.Editor
);
328 edit::rewriteToObjCLiteralSyntax(E
, *Consumer
.NSAPIObj
, commit
, &PMap
);
329 Consumer
.Editor
->commit(commit
);
332 if (Consumer
.ASTMigrateActions
& FrontendOptions::ObjCMT_Subscripting
) {
333 edit::Commit
commit(*Consumer
.Editor
);
334 edit::rewriteToObjCSubscriptSyntax(E
, *Consumer
.NSAPIObj
, commit
);
335 Consumer
.Editor
->commit(commit
);
338 if (Consumer
.ASTMigrateActions
& FrontendOptions::ObjCMT_PropertyDotSyntax
) {
339 edit::Commit
commit(*Consumer
.Editor
);
340 rewriteToPropertyDotSyntax(E
, Consumer
.PP
, *Consumer
.NSAPIObj
,
342 Consumer
.Editor
->commit(commit
);
348 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 for (Stmt
*SubStmt
: E
->children())
352 if (!TraverseStmt(SubStmt
))
355 return WalkUpFromObjCMessageExpr(E
);
359 class BodyMigrator
: public RecursiveASTVisitor
<BodyMigrator
> {
360 ObjCMigrateASTConsumer
&Consumer
;
361 std::unique_ptr
<ParentMap
> PMap
;
364 BodyMigrator(ObjCMigrateASTConsumer
&consumer
) : Consumer(consumer
) { }
366 bool shouldVisitTemplateInstantiations() const { return false; }
367 bool shouldWalkTypesOfTypeLocs() const { return false; }
369 bool TraverseStmt(Stmt
*S
) {
370 PMap
.reset(new ParentMap(S
));
371 ObjCMigrator(Consumer
, *PMap
).TraverseStmt(S
);
375 } // end anonymous namespace
377 void ObjCMigrateASTConsumer::migrateDecl(Decl
*D
) {
380 if (isa
<ObjCMethodDecl
>(D
))
381 return; // Wait for the ObjC container declaration.
383 BodyMigrator(*this).TraverseDecl(D
);
386 static void append_attr(std::string
&PropertyString
, const char *attr
,
389 PropertyString
+= "(";
393 PropertyString
+= ", ";
394 PropertyString
+= attr
;
398 void MigrateBlockOrFunctionPointerTypeVariable(std::string
& PropertyString
,
399 const std::string
& TypeString
,
401 const char *argPtr
= TypeString
.c_str();
406 PropertyString
+= *argPtr
;
410 PropertyString
+= *argPtr
;
415 PropertyString
+= (*argPtr
);
417 PropertyString
+= name
;
422 PropertyString
+= *argPtr
;
429 static const char *PropertyMemoryAttribute(ASTContext
&Context
, QualType ArgType
) {
430 Qualifiers::ObjCLifetime propertyLifetime
= ArgType
.getObjCLifetime();
431 bool RetainableObject
= ArgType
->isObjCRetainableType();
432 if (RetainableObject
&&
433 (propertyLifetime
== Qualifiers::OCL_Strong
434 || propertyLifetime
== Qualifiers::OCL_None
)) {
435 if (const ObjCObjectPointerType
*ObjPtrTy
=
436 ArgType
->getAs
<ObjCObjectPointerType
>()) {
437 ObjCInterfaceDecl
*IDecl
= ObjPtrTy
->getObjectType()->getInterface();
439 IDecl
->lookupNestedProtocol(&Context
.Idents
.get("NSCopying")))
444 else if (ArgType
->isBlockPointerType())
446 } 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.
450 else if (RetainableObject
)
451 return ArgType
->isBlockPointerType() ? "copy" : "strong";
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 bool AvailabilityArgsMatch
) {
461 ASTContext
&Context
= NS
.getASTContext();
462 bool LParenAdded
= false;
463 std::string PropertyString
= "@property ";
464 if (UseNsIosOnlyMacro
&& NS
.isMacroDefined("NS_NONATOMIC_IOSONLY")) {
465 PropertyString
+= "(NS_NONATOMIC_IOSONLY";
467 } else if (!Atomic
) {
468 PropertyString
+= "(nonatomic";
472 std::string PropertyNameString
= Getter
->getNameAsString();
473 StringRef
PropertyName(PropertyNameString
);
474 if (LengthOfPrefix
> 0) {
476 PropertyString
+= "(getter=";
480 PropertyString
+= ", getter=";
481 PropertyString
+= PropertyNameString
;
483 // Property with no setter may be suggested as a 'readonly' property.
485 append_attr(PropertyString
, "readonly", LParenAdded
);
488 // Short circuit 'delegate' properties that contain the name "delegate" or
489 // "dataSource", or have exact name "target" to have 'assign' attribute.
490 if (PropertyName
.equals("target") || PropertyName
.contains("delegate") ||
491 PropertyName
.contains("dataSource")) {
492 QualType QT
= Getter
->getReturnType();
493 if (!QT
->isRealType())
494 append_attr(PropertyString
, "assign", LParenAdded
);
495 } else if (!Setter
) {
496 QualType ResType
= Context
.getCanonicalType(Getter
->getReturnType());
497 if (const char *MemoryManagementAttr
= PropertyMemoryAttribute(Context
, ResType
))
498 append_attr(PropertyString
, MemoryManagementAttr
, LParenAdded
);
500 const ParmVarDecl
*argDecl
= *Setter
->param_begin();
501 QualType ArgType
= Context
.getCanonicalType(argDecl
->getType());
502 if (const char *MemoryManagementAttr
= PropertyMemoryAttribute(Context
, ArgType
))
503 append_attr(PropertyString
, MemoryManagementAttr
, LParenAdded
);
506 PropertyString
+= ')';
507 QualType RT
= Getter
->getReturnType();
508 if (!RT
->getAs
<TypedefType
>()) {
509 // strip off any ARC lifetime qualifier.
510 QualType CanResultTy
= Context
.getCanonicalType(RT
);
511 if (CanResultTy
.getQualifiers().hasObjCLifetime()) {
512 Qualifiers Qs
= CanResultTy
.getQualifiers();
513 Qs
.removeObjCLifetime();
514 RT
= Context
.getQualifiedType(CanResultTy
.getUnqualifiedType(), Qs
);
517 PropertyString
+= " ";
518 PrintingPolicy
SubPolicy(Context
.getPrintingPolicy());
519 SubPolicy
.SuppressStrongLifetime
= true;
520 SubPolicy
.SuppressLifetimeQualifiers
= true;
521 std::string TypeString
= RT
.getAsString(SubPolicy
);
522 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 StringRef
PropertyNameStringRef(PropertyNameString
);
526 PropertyNameStringRef
= PropertyNameStringRef
.drop_front(LengthOfPrefix
);
527 PropertyNameString
= std::string(PropertyNameStringRef
);
528 bool NoLowering
= (isUppercase(PropertyNameString
[0]) &&
529 PropertyNameString
.size() > 1 &&
530 isUppercase(PropertyNameString
[1]));
532 PropertyNameString
[0] = toLowercase(PropertyNameString
[0]);
534 if (RT
->isBlockPointerType() || RT
->isFunctionPointerType())
535 MigrateBlockOrFunctionPointerTypeVariable(PropertyString
,
537 PropertyNameString
.c_str());
539 char LastChar
= TypeString
[TypeString
.size()-1];
540 PropertyString
+= TypeString
;
542 PropertyString
+= ' ';
543 PropertyString
+= PropertyNameString
;
545 SourceLocation StartGetterSelectorLoc
= Getter
->getSelectorStartLoc();
546 Selector GetterSelector
= Getter
->getSelector();
548 SourceLocation EndGetterSelectorLoc
=
549 StartGetterSelectorLoc
.getLocWithOffset(GetterSelector
.getNameForSlot(0).size());
550 commit
.replace(CharSourceRange::getCharRange(Getter
->getBeginLoc(),
551 EndGetterSelectorLoc
),
553 if (Setter
&& AvailabilityArgsMatch
) {
554 SourceLocation EndLoc
= Setter
->getDeclaratorEndLoc();
555 // Get location past ';'
556 EndLoc
= EndLoc
.getLocWithOffset(1);
557 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 BeginOfSetterDclLoc
= BeginOfSetterDclLoc
.getLocWithOffset(-1);
561 commit
.remove(SourceRange(BeginOfSetterDclLoc
, EndLoc
));
565 static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl
*D
) {
566 if (ObjCCategoryDecl
*CatDecl
= dyn_cast
<ObjCCategoryDecl
>(D
)) {
567 StringRef Name
= CatDecl
->getName();
568 return Name
.endswith("Deprecated");
573 void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext
&Ctx
,
574 ObjCContainerDecl
*D
) {
575 if (D
->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D
))
578 for (auto *Method
: D
->methods()) {
579 if (Method
->isDeprecated())
581 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 if (!PropertyInferred
||
586 (ASTMigrateActions
& FrontendOptions::ObjCMT_ReturnsInnerPointerProperty
))
587 if (ASTMigrateActions
& FrontendOptions::ObjCMT_Annotation
)
588 migrateNsReturnsInnerPointer(Ctx
, Method
);
590 if (!(ASTMigrateActions
& FrontendOptions::ObjCMT_ReturnsInnerPointerProperty
))
593 for (auto *Prop
: D
->instance_properties()) {
594 if ((ASTMigrateActions
& FrontendOptions::ObjCMT_Annotation
) &&
595 !Prop
->isDeprecated())
596 migratePropertyNsReturnsInnerPointer(Ctx
, Prop
);
601 ClassImplementsAllMethodsAndProperties(ASTContext
&Ctx
,
602 const ObjCImplementationDecl
*ImpDecl
,
603 const ObjCInterfaceDecl
*IDecl
,
604 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 bool HasAtleastOneRequiredProperty
= false;
609 if (const ObjCProtocolDecl
*PDecl
= Protocol
->getDefinition())
610 for (const auto *Property
: PDecl
->instance_properties()) {
611 if (Property
->getPropertyImplementation() == ObjCPropertyDecl::Optional
)
613 HasAtleastOneRequiredProperty
= true;
614 DeclContext::lookup_result R
= IDecl
->lookup(Property
->getDeclName());
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 if (!ImpDecl
->FindPropertyImplDecl(
620 Property
->getDeclName().getAsIdentifierInfo(),
621 Property
->getQueryKind()))
623 } else if (auto *ClassProperty
= R
.find_first
<ObjCPropertyDecl
>()) {
624 if ((ClassProperty
->getPropertyAttributes() !=
625 Property
->getPropertyAttributes()) ||
626 !Ctx
.hasSameType(ClassProperty
->getType(), Property
->getType()))
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 bool HasAtleastOneRequiredMethod
= false;
636 if (const ObjCProtocolDecl
*PDecl
= Protocol
->getDefinition()) {
637 if (PDecl
->meth_begin() == PDecl
->meth_end())
638 return HasAtleastOneRequiredProperty
;
639 for (const auto *MD
: PDecl
->methods()) {
640 if (MD
->isImplicit())
642 if (MD
->getImplementationControl() == ObjCMethodDecl::Optional
)
644 DeclContext::lookup_result R
= ImpDecl
->lookup(MD
->getDeclName());
648 HasAtleastOneRequiredMethod
= true;
649 for (NamedDecl
*ND
: R
)
650 if (ObjCMethodDecl
*ImpMD
= dyn_cast
<ObjCMethodDecl
>(ND
))
651 if (Ctx
.ObjCMethodsAreEqual(MD
, ImpMD
)) {
659 return HasAtleastOneRequiredProperty
|| HasAtleastOneRequiredMethod
;
662 static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl
*IDecl
,
663 llvm::SmallVectorImpl
<ObjCProtocolDecl
*> &ConformingProtocols
,
664 const NSAPI
&NS
, edit::Commit
&commit
) {
665 const ObjCList
<ObjCProtocolDecl
> &Protocols
= IDecl
->getReferencedProtocols();
666 std::string ClassString
;
667 SourceLocation EndLoc
=
668 IDecl
->getSuperClass() ? IDecl
->getSuperClassLoc() : IDecl
->getLocation();
670 if (Protocols
.empty()) {
672 for (unsigned i
= 0, e
= ConformingProtocols
.size(); i
!= e
; i
++) {
673 ClassString
+= ConformingProtocols
[i
]->getNameAsString();
681 for (unsigned i
= 0, e
= ConformingProtocols
.size(); i
!= e
; i
++) {
682 ClassString
+= ConformingProtocols
[i
]->getNameAsString();
686 ObjCInterfaceDecl::protocol_loc_iterator PL
= IDecl
->protocol_loc_end() - 1;
690 commit
.insertAfterToken(EndLoc
, ClassString
);
694 static StringRef
GetUnsignedName(StringRef NSIntegerName
) {
695 StringRef UnsignedName
= llvm::StringSwitch
<StringRef
>(NSIntegerName
)
696 .Case("int8_t", "uint8_t")
697 .Case("int16_t", "uint16_t")
698 .Case("int32_t", "uint32_t")
699 .Case("NSInteger", "NSUInteger")
700 .Case("int64_t", "uint64_t")
701 .Default(NSIntegerName
);
705 static bool rewriteToNSEnumDecl(const EnumDecl
*EnumDcl
,
706 const TypedefDecl
*TypedefDcl
,
707 const NSAPI
&NS
, edit::Commit
&commit
,
708 StringRef NSIntegerName
,
710 std::string ClassString
;
712 ClassString
= "typedef NS_OPTIONS(";
713 ClassString
+= GetUnsignedName(NSIntegerName
);
716 ClassString
= "typedef NS_ENUM(";
717 ClassString
+= NSIntegerName
;
721 ClassString
+= TypedefDcl
->getIdentifier()->getName();
723 SourceRange
R(EnumDcl
->getBeginLoc(), EnumDcl
->getBeginLoc());
724 commit
.replace(R
, ClassString
);
725 SourceLocation EndOfEnumDclLoc
= EnumDcl
->getEndLoc();
726 EndOfEnumDclLoc
= trans::findSemiAfterLocation(EndOfEnumDclLoc
,
727 NS
.getASTContext(), /*IsDecl*/true);
728 if (EndOfEnumDclLoc
.isValid()) {
729 SourceRange
EnumDclRange(EnumDcl
->getBeginLoc(), EndOfEnumDclLoc
);
730 commit
.insertFromRange(TypedefDcl
->getBeginLoc(), EnumDclRange
);
735 SourceLocation EndTypedefDclLoc
= TypedefDcl
->getEndLoc();
736 EndTypedefDclLoc
= trans::findSemiAfterLocation(EndTypedefDclLoc
,
737 NS
.getASTContext(), /*IsDecl*/true);
738 if (EndTypedefDclLoc
.isValid()) {
739 SourceRange
TDRange(TypedefDcl
->getBeginLoc(), EndTypedefDclLoc
);
740 commit
.remove(TDRange
);
746 trans::findLocationAfterSemi(EnumDcl
->getEndLoc(), NS
.getASTContext(),
748 if (EndOfEnumDclLoc
.isValid()) {
749 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 BeginOfEnumDclLoc
= BeginOfEnumDclLoc
.getLocWithOffset(-1);
753 commit
.remove(SourceRange(BeginOfEnumDclLoc
, EndOfEnumDclLoc
));
759 static void rewriteToNSMacroDecl(ASTContext
&Ctx
,
760 const EnumDecl
*EnumDcl
,
761 const TypedefDecl
*TypedefDcl
,
762 const NSAPI
&NS
, edit::Commit
&commit
,
763 bool IsNSIntegerType
) {
764 QualType DesignatedEnumType
= EnumDcl
->getIntegerType();
765 assert(!DesignatedEnumType
.isNull()
766 && "rewriteToNSMacroDecl - underlying enum type is null");
768 PrintingPolicy
Policy(Ctx
.getPrintingPolicy());
769 std::string TypeString
= DesignatedEnumType
.getAsString(Policy
);
770 std::string ClassString
= IsNSIntegerType
? "NS_ENUM(" : "NS_OPTIONS(";
771 ClassString
+= TypeString
;
774 ClassString
+= TypedefDcl
->getIdentifier()->getName();
776 SourceLocation EndLoc
= EnumDcl
->getBraceRange().getBegin();
777 if (EndLoc
.isInvalid())
780 CharSourceRange::getCharRange(EnumDcl
->getBeginLoc(), EndLoc
);
781 commit
.replace(R
, ClassString
);
782 // This is to remove spaces between '}' and typedef name.
783 SourceLocation StartTypedefLoc
= EnumDcl
->getEndLoc();
784 StartTypedefLoc
= StartTypedefLoc
.getLocWithOffset(+1);
785 SourceLocation EndTypedefLoc
= TypedefDcl
->getEndLoc();
787 commit
.remove(SourceRange(StartTypedefLoc
, EndTypedefLoc
));
790 static bool UseNSOptionsMacro(Preprocessor
&PP
, ASTContext
&Ctx
,
791 const EnumDecl
*EnumDcl
) {
792 bool PowerOfTwo
= true;
793 bool AllHexdecimalEnumerator
= true;
794 uint64_t MaxPowerOfTwoVal
= 0;
795 for (auto Enumerator
: EnumDcl
->enumerators()) {
796 const Expr
*InitExpr
= Enumerator
->getInitExpr();
799 AllHexdecimalEnumerator
= false;
802 InitExpr
= InitExpr
->IgnoreParenCasts();
803 if (const BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(InitExpr
))
804 if (BO
->isShiftOp() || BO
->isBitwiseOp())
807 uint64_t EnumVal
= Enumerator
->getInitVal().getZExtValue();
808 if (PowerOfTwo
&& EnumVal
) {
809 if (!llvm::isPowerOf2_64(EnumVal
))
811 else if (EnumVal
> MaxPowerOfTwoVal
)
812 MaxPowerOfTwoVal
= EnumVal
;
814 if (AllHexdecimalEnumerator
&& EnumVal
) {
815 bool FoundHexdecimalEnumerator
= false;
816 SourceLocation EndLoc
= Enumerator
->getEndLoc();
818 if (!PP
.getRawToken(EndLoc
, Tok
, /*IgnoreWhiteSpace=*/true))
819 if (Tok
.isLiteral() && Tok
.getLength() > 2) {
820 if (const char *StringLit
= Tok
.getLiteralData())
821 FoundHexdecimalEnumerator
=
822 (StringLit
[0] == '0' && (toLowercase(StringLit
[1]) == 'x'));
824 if (!FoundHexdecimalEnumerator
)
825 AllHexdecimalEnumerator
= false;
828 return AllHexdecimalEnumerator
|| (PowerOfTwo
&& (MaxPowerOfTwoVal
> 2));
831 void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext
&Ctx
,
832 const ObjCImplementationDecl
*ImpDecl
) {
833 const ObjCInterfaceDecl
*IDecl
= ImpDecl
->getClassInterface();
834 if (!IDecl
|| ObjCProtocolDecls
.empty() || IDecl
->isDeprecated())
836 // Find all implicit conforming protocols for this class
837 // and make them explicit.
838 llvm::SmallPtrSet
<ObjCProtocolDecl
*, 8> ExplicitProtocols
;
839 Ctx
.CollectInheritedProtocols(IDecl
, ExplicitProtocols
);
840 llvm::SmallVector
<ObjCProtocolDecl
*, 8> PotentialImplicitProtocols
;
842 for (ObjCProtocolDecl
*ProtDecl
: ObjCProtocolDecls
)
843 if (!ExplicitProtocols
.count(ProtDecl
))
844 PotentialImplicitProtocols
.push_back(ProtDecl
);
846 if (PotentialImplicitProtocols
.empty())
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 llvm::SmallVector
<ObjCProtocolDecl
*, 8> ConformingProtocols
;
853 for (unsigned i
= 0, e
= PotentialImplicitProtocols
.size(); i
!= e
; i
++)
854 if (ClassImplementsAllMethodsAndProperties(Ctx
, ImpDecl
, IDecl
,
855 PotentialImplicitProtocols
[i
]))
856 ConformingProtocols
.push_back(PotentialImplicitProtocols
[i
]);
858 if (ConformingProtocols
.empty())
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 llvm::SmallVector
<ObjCProtocolDecl
*, 8> MinimalConformingProtocols
;
864 for (unsigned i
= 0, e
= ConformingProtocols
.size(); i
!= e
; i
++) {
866 ObjCProtocolDecl
*TargetPDecl
= ConformingProtocols
[i
];
867 for (unsigned i1
= 0, e1
= ConformingProtocols
.size(); i1
!= e1
; i1
++) {
868 ObjCProtocolDecl
*PDecl
= ConformingProtocols
[i1
];
869 if (PDecl
== TargetPDecl
)
871 if (PDecl
->lookupProtocolNamed(
872 TargetPDecl
->getDeclName().getAsIdentifierInfo())) {
878 MinimalConformingProtocols
.push_back(TargetPDecl
);
880 if (MinimalConformingProtocols
.empty())
882 edit::Commit
commit(*Editor
);
883 rewriteToObjCInterfaceDecl(IDecl
, MinimalConformingProtocols
,
885 Editor
->commit(commit
);
888 void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
889 const TypedefDecl
*TypedefDcl
) {
891 QualType qt
= TypedefDcl
->getTypeSourceInfo()->getType();
892 if (NSAPIObj
->isObjCNSIntegerType(qt
))
893 NSIntegerTypedefed
= TypedefDcl
;
894 else if (NSAPIObj
->isObjCNSUIntegerType(qt
))
895 NSUIntegerTypedefed
= TypedefDcl
;
898 bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext
&Ctx
,
899 const EnumDecl
*EnumDcl
,
900 const TypedefDecl
*TypedefDcl
) {
901 if (!EnumDcl
->isCompleteDefinition() || EnumDcl
->getIdentifier() ||
902 EnumDcl
->isDeprecated())
905 if (NSIntegerTypedefed
) {
906 TypedefDcl
= NSIntegerTypedefed
;
907 NSIntegerTypedefed
= nullptr;
909 else if (NSUIntegerTypedefed
) {
910 TypedefDcl
= NSUIntegerTypedefed
;
911 NSUIntegerTypedefed
= nullptr;
915 FileID FileIdOfTypedefDcl
=
916 PP
.getSourceManager().getFileID(TypedefDcl
->getLocation());
917 FileID FileIdOfEnumDcl
=
918 PP
.getSourceManager().getFileID(EnumDcl
->getLocation());
919 if (FileIdOfTypedefDcl
!= FileIdOfEnumDcl
)
922 if (TypedefDcl
->isDeprecated())
925 QualType qt
= TypedefDcl
->getTypeSourceInfo()->getType();
926 StringRef NSIntegerName
= NSAPIObj
->GetNSIntegralKind(qt
);
928 if (NSIntegerName
.empty()) {
929 // Also check for typedef enum {...} TD;
930 if (const EnumType
*EnumTy
= qt
->getAs
<EnumType
>()) {
931 if (EnumTy
->getDecl() == EnumDcl
) {
932 bool NSOptions
= UseNSOptionsMacro(PP
, Ctx
, EnumDcl
);
933 if (!InsertFoundation(Ctx
, TypedefDcl
->getBeginLoc()))
935 edit::Commit
commit(*Editor
);
936 rewriteToNSMacroDecl(Ctx
, EnumDcl
, TypedefDcl
, *NSAPIObj
, commit
, !NSOptions
);
937 Editor
->commit(commit
);
944 // We may still use NS_OPTIONS based on what we find in the enumertor list.
945 bool NSOptions
= UseNSOptionsMacro(PP
, Ctx
, EnumDcl
);
946 if (!InsertFoundation(Ctx
, TypedefDcl
->getBeginLoc()))
948 edit::Commit
commit(*Editor
);
949 bool Res
= rewriteToNSEnumDecl(EnumDcl
, TypedefDcl
, *NSAPIObj
,
950 commit
, NSIntegerName
, NSOptions
);
951 Editor
->commit(commit
);
955 static void ReplaceWithInstancetype(ASTContext
&Ctx
,
956 const ObjCMigrateASTConsumer
&ASTC
,
957 ObjCMethodDecl
*OM
) {
958 if (OM
->getReturnType() == Ctx
.getObjCInstanceType())
959 return; // already has instancetype.
962 std::string ClassString
;
963 if (TypeSourceInfo
*TSInfo
= OM
->getReturnTypeSourceInfo()) {
964 TypeLoc TL
= TSInfo
->getTypeLoc();
965 R
= SourceRange(TL
.getBeginLoc(), TL
.getEndLoc());
966 ClassString
= "instancetype";
969 R
= SourceRange(OM
->getBeginLoc(), OM
->getBeginLoc());
970 ClassString
= OM
->isInstanceMethod() ? '-' : '+';
971 ClassString
+= " (instancetype)";
973 edit::Commit
commit(*ASTC
.Editor
);
974 commit
.replace(R
, ClassString
);
975 ASTC
.Editor
->commit(commit
);
978 static void ReplaceWithClasstype(const ObjCMigrateASTConsumer
&ASTC
,
979 ObjCMethodDecl
*OM
) {
980 ObjCInterfaceDecl
*IDecl
= OM
->getClassInterface();
982 std::string ClassString
;
983 if (TypeSourceInfo
*TSInfo
= OM
->getReturnTypeSourceInfo()) {
984 TypeLoc TL
= TSInfo
->getTypeLoc();
985 R
= SourceRange(TL
.getBeginLoc(), TL
.getEndLoc()); {
986 ClassString
= std::string(IDecl
->getName());
991 R
= SourceRange(OM
->getBeginLoc(), OM
->getBeginLoc());
993 ClassString
+= IDecl
->getName(); ClassString
+= "*)";
995 edit::Commit
commit(*ASTC
.Editor
);
996 commit
.replace(R
, ClassString
);
997 ASTC
.Editor
->commit(commit
);
1000 void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext
&Ctx
,
1001 ObjCContainerDecl
*CDecl
,
1002 ObjCMethodDecl
*OM
) {
1003 ObjCInstanceTypeFamily OIT_Family
=
1004 Selector::getInstTypeMethodFamily(OM
->getSelector());
1006 std::string ClassName
;
1007 switch (OIT_Family
) {
1009 migrateFactoryMethod(Ctx
, CDecl
, OM
);
1012 ClassName
= "NSArray";
1014 case OIT_Dictionary
:
1015 ClassName
= "NSDictionary";
1018 migrateFactoryMethod(Ctx
, CDecl
, OM
, OIT_Singleton
);
1021 if (OM
->getReturnType()->isObjCIdType())
1022 ReplaceWithInstancetype(Ctx
, *this, OM
);
1024 case OIT_ReturnsSelf
:
1025 migrateFactoryMethod(Ctx
, CDecl
, OM
, OIT_ReturnsSelf
);
1028 if (!OM
->getReturnType()->isObjCIdType())
1031 ObjCInterfaceDecl
*IDecl
= dyn_cast
<ObjCInterfaceDecl
>(CDecl
);
1033 if (ObjCCategoryDecl
*CatDecl
= dyn_cast
<ObjCCategoryDecl
>(CDecl
))
1034 IDecl
= CatDecl
->getClassInterface();
1035 else if (ObjCImplDecl
*ImpDecl
= dyn_cast
<ObjCImplDecl
>(CDecl
))
1036 IDecl
= ImpDecl
->getClassInterface();
1039 !IDecl
->lookupInheritedClass(&Ctx
.Idents
.get(ClassName
))) {
1040 migrateFactoryMethod(Ctx
, CDecl
, OM
);
1043 ReplaceWithInstancetype(Ctx
, *this, OM
);
1046 static bool TypeIsInnerPointer(QualType T
) {
1047 if (!T
->isAnyPointerType())
1049 if (T
->isObjCObjectPointerType() || T
->isObjCBuiltinType() ||
1050 T
->isBlockPointerType() || T
->isFunctionPointerType() ||
1051 ento::coreFoundation::isCFObjectRef(T
))
1053 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
1054 // is not an innter pointer type.
1056 while (const auto *TD
= T
->getAs
<TypedefType
>())
1057 T
= TD
->getDecl()->getUnderlyingType();
1058 if (OrigT
== T
|| !T
->isPointerType())
1060 const PointerType
* PT
= T
->getAs
<PointerType
>();
1061 QualType UPointeeT
= PT
->getPointeeType().getUnqualifiedType();
1062 if (UPointeeT
->isRecordType()) {
1063 const RecordType
*RecordTy
= UPointeeT
->getAs
<RecordType
>();
1064 if (!RecordTy
->getDecl()->isCompleteDefinition())
1070 /// Check whether the two versions match.
1071 static bool versionsMatch(const VersionTuple
&X
, const VersionTuple
&Y
) {
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 static bool AvailabilityAttrsMatch(Attr
*At1
, Attr
*At2
) {
1081 const AvailabilityAttr
*AA1
= dyn_cast
<AvailabilityAttr
>(At1
);
1084 const AvailabilityAttr
*AA2
= cast
<AvailabilityAttr
>(At2
);
1086 VersionTuple Introduced1
= AA1
->getIntroduced();
1087 VersionTuple Deprecated1
= AA1
->getDeprecated();
1088 VersionTuple Obsoleted1
= AA1
->getObsoleted();
1089 bool IsUnavailable1
= AA1
->getUnavailable();
1090 VersionTuple Introduced2
= AA2
->getIntroduced();
1091 VersionTuple Deprecated2
= AA2
->getDeprecated();
1092 VersionTuple Obsoleted2
= AA2
->getObsoleted();
1093 bool IsUnavailable2
= AA2
->getUnavailable();
1094 return (versionsMatch(Introduced1
, Introduced2
) &&
1095 versionsMatch(Deprecated1
, Deprecated2
) &&
1096 versionsMatch(Obsoleted1
, Obsoleted2
) &&
1097 IsUnavailable1
== IsUnavailable2
);
1100 static bool MatchTwoAttributeLists(const AttrVec
&Attrs1
, const AttrVec
&Attrs2
,
1101 bool &AvailabilityArgsMatch
) {
1102 // This list is very small, so this need not be optimized.
1103 for (unsigned i
= 0, e
= Attrs1
.size(); i
!= e
; i
++) {
1105 for (unsigned j
= 0, f
= Attrs2
.size(); j
!= f
; j
++) {
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 if (Attrs1
[i
]->getKind() == Attrs2
[j
]->getKind()) {
1110 if (AvailabilityArgsMatch
)
1111 AvailabilityArgsMatch
= AvailabilityAttrsMatch(Attrs1
[i
], Attrs2
[j
]);
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 bool &AvailabilityArgsMatch
) {
1131 if (!Decl1
->hasAttrs() || !Decl2
->hasAttrs()) {
1132 AvailabilityArgsMatch
= (Decl1
->hasAttrs() == Decl2
->hasAttrs());
1135 AvailabilityArgsMatch
= true;
1136 const AttrVec
&Attrs1
= Decl1
->getAttrs();
1137 const AttrVec
&Attrs2
= Decl2
->getAttrs();
1138 bool match
= MatchTwoAttributeLists(Attrs1
, Attrs2
, AvailabilityArgsMatch
);
1139 if (match
&& (Attrs2
.size() > Attrs1
.size()))
1140 return MatchTwoAttributeLists(Attrs2
, Attrs1
, AvailabilityArgsMatch
);
1144 static bool IsValidIdentifier(ASTContext
&Ctx
,
1146 if (!isAsciiIdentifierStart(Name
[0]))
1148 std::string NameString
= Name
;
1149 NameString
[0] = toLowercase(NameString
[0]);
1150 IdentifierInfo
*II
= &Ctx
.Idents
.get(NameString
);
1151 return II
->getTokenID() == tok::identifier
;
1154 bool ObjCMigrateASTConsumer::migrateProperty(ASTContext
&Ctx
,
1155 ObjCContainerDecl
*D
,
1156 ObjCMethodDecl
*Method
) {
1157 if (Method
->isPropertyAccessor() || !Method
->isInstanceMethod() ||
1158 Method
->param_size() != 0)
1160 // Is this method candidate to be a getter?
1161 QualType GRT
= Method
->getReturnType();
1162 if (GRT
->isVoidType())
1165 Selector GetterSelector
= Method
->getSelector();
1166 ObjCInstanceTypeFamily OIT_Family
=
1167 Selector::getInstTypeMethodFamily(GetterSelector
);
1169 if (OIT_Family
!= OIT_None
)
1172 IdentifierInfo
*getterName
= GetterSelector
.getIdentifierInfoForSlot(0);
1173 Selector SetterSelector
=
1174 SelectorTable::constructSetterSelector(PP
.getIdentifierTable(),
1175 PP
.getSelectorTable(),
1177 ObjCMethodDecl
*SetterMethod
= D
->getInstanceMethod(SetterSelector
);
1178 unsigned LengthOfPrefix
= 0;
1179 if (!SetterMethod
) {
1180 // try a different naming convention for getter: isXxxxx
1181 StringRef getterNameString
= getterName
->getName();
1182 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 if (IsPrefix
&& GRT
->isObjCRetainableType())
1187 if (IsPrefix
|| getterNameString
.startswith("get")) {
1188 LengthOfPrefix
= (IsPrefix
? 2 : 3);
1189 const char *CGetterName
= getterNameString
.data() + LengthOfPrefix
;
1190 // Make sure that first character after "is" or "get" prefix can
1191 // start an identifier.
1192 if (!IsValidIdentifier(Ctx
, CGetterName
))
1194 if (CGetterName
[0] && isUppercase(CGetterName
[0])) {
1195 getterName
= &Ctx
.Idents
.get(CGetterName
);
1197 SelectorTable::constructSetterSelector(PP
.getIdentifierTable(),
1198 PP
.getSelectorTable(),
1200 SetterMethod
= D
->getInstanceMethod(SetterSelector
);
1206 if ((ASTMigrateActions
& FrontendOptions::ObjCMT_ReadwriteProperty
) == 0)
1208 bool AvailabilityArgsMatch
;
1209 if (SetterMethod
->isDeprecated() ||
1210 !AttributesMatch(Method
, SetterMethod
, AvailabilityArgsMatch
))
1213 // Is this a valid setter, matching the target getter?
1214 QualType SRT
= SetterMethod
->getReturnType();
1215 if (!SRT
->isVoidType())
1217 const ParmVarDecl
*argDecl
= *SetterMethod
->param_begin();
1218 QualType ArgType
= argDecl
->getType();
1219 if (!Ctx
.hasSameUnqualifiedType(ArgType
, GRT
))
1221 edit::Commit
commit(*Editor
);
1222 rewriteToObjCProperty(Method
, SetterMethod
, *NSAPIObj
, commit
,
1224 (ASTMigrateActions
&
1225 FrontendOptions::ObjCMT_AtomicProperty
) != 0,
1226 (ASTMigrateActions
&
1227 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty
) != 0,
1228 AvailabilityArgsMatch
);
1229 Editor
->commit(commit
);
1232 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 edit::Commit
commit(*Editor
);
1236 rewriteToObjCProperty(Method
, nullptr /*SetterMethod*/, *NSAPIObj
, commit
,
1238 (ASTMigrateActions
&
1239 FrontendOptions::ObjCMT_AtomicProperty
) != 0,
1240 (ASTMigrateActions
&
1241 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty
) != 0,
1242 /*AvailabilityArgsMatch*/false);
1243 Editor
->commit(commit
);
1249 void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext
&Ctx
,
1250 ObjCMethodDecl
*OM
) {
1251 if (OM
->isImplicit() ||
1252 !OM
->isInstanceMethod() ||
1253 OM
->hasAttr
<ObjCReturnsInnerPointerAttr
>())
1256 QualType RT
= OM
->getReturnType();
1257 if (!TypeIsInnerPointer(RT
) ||
1258 !NSAPIObj
->isMacroDefined("NS_RETURNS_INNER_POINTER"))
1261 edit::Commit
commit(*Editor
);
1262 commit
.insertBefore(OM
->getEndLoc(), " NS_RETURNS_INNER_POINTER");
1263 Editor
->commit(commit
);
1266 void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext
&Ctx
,
1267 ObjCPropertyDecl
*P
) {
1268 QualType T
= P
->getType();
1270 if (!TypeIsInnerPointer(T
) ||
1271 !NSAPIObj
->isMacroDefined("NS_RETURNS_INNER_POINTER"))
1273 edit::Commit
commit(*Editor
);
1274 commit
.insertBefore(P
->getEndLoc(), " NS_RETURNS_INNER_POINTER ");
1275 Editor
->commit(commit
);
1278 void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext
&Ctx
,
1279 ObjCContainerDecl
*CDecl
) {
1280 if (CDecl
->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl
))
1283 // migrate methods which can have instancetype as their result type.
1284 for (auto *Method
: CDecl
->methods()) {
1285 if (Method
->isDeprecated())
1287 migrateMethodInstanceType(Ctx
, CDecl
, Method
);
1291 void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext
&Ctx
,
1292 ObjCContainerDecl
*CDecl
,
1294 ObjCInstanceTypeFamily OIT_Family
) {
1295 if (OM
->isInstanceMethod() ||
1296 OM
->getReturnType() == Ctx
.getObjCInstanceType() ||
1297 !OM
->getReturnType()->isObjCIdType())
1300 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1301 // NSYYYNamE with matching names be at least 3 characters long.
1302 ObjCInterfaceDecl
*IDecl
= dyn_cast
<ObjCInterfaceDecl
>(CDecl
);
1304 if (ObjCCategoryDecl
*CatDecl
= dyn_cast
<ObjCCategoryDecl
>(CDecl
))
1305 IDecl
= CatDecl
->getClassInterface();
1306 else if (ObjCImplDecl
*ImpDecl
= dyn_cast
<ObjCImplDecl
>(CDecl
))
1307 IDecl
= ImpDecl
->getClassInterface();
1312 std::string StringClassName
= std::string(IDecl
->getName());
1313 StringRef
LoweredClassName(StringClassName
);
1314 std::string StringLoweredClassName
= LoweredClassName
.lower();
1315 LoweredClassName
= StringLoweredClassName
;
1317 IdentifierInfo
*MethodIdName
= OM
->getSelector().getIdentifierInfoForSlot(0);
1318 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1322 std::string MethodName
= std::string(MethodIdName
->getName());
1323 if (OIT_Family
== OIT_Singleton
|| OIT_Family
== OIT_ReturnsSelf
) {
1324 StringRef
STRefMethodName(MethodName
);
1326 if (STRefMethodName
.startswith("standard"))
1327 len
= strlen("standard");
1328 else if (STRefMethodName
.startswith("shared"))
1329 len
= strlen("shared");
1330 else if (STRefMethodName
.startswith("default"))
1331 len
= strlen("default");
1334 MethodName
= std::string(STRefMethodName
.substr(len
));
1336 std::string MethodNameSubStr
= MethodName
.substr(0, 3);
1337 StringRef
MethodNamePrefix(MethodNameSubStr
);
1338 std::string StringLoweredMethodNamePrefix
= MethodNamePrefix
.lower();
1339 MethodNamePrefix
= StringLoweredMethodNamePrefix
;
1340 size_t Ix
= LoweredClassName
.rfind(MethodNamePrefix
);
1341 if (Ix
== StringRef::npos
)
1343 std::string ClassNamePostfix
= std::string(LoweredClassName
.substr(Ix
));
1344 StringRef
LoweredMethodName(MethodName
);
1345 std::string StringLoweredMethodName
= LoweredMethodName
.lower();
1346 LoweredMethodName
= StringLoweredMethodName
;
1347 if (!LoweredMethodName
.startswith(ClassNamePostfix
))
1349 if (OIT_Family
== OIT_ReturnsSelf
)
1350 ReplaceWithClasstype(*this, OM
);
1352 ReplaceWithInstancetype(Ctx
, *this, OM
);
1355 static bool IsVoidStarType(QualType Ty
) {
1356 if (!Ty
->isPointerType())
1359 // Is the type void*?
1360 const PointerType
* PT
= Ty
->castAs
<PointerType
>();
1361 if (PT
->getPointeeType().getUnqualifiedType()->isVoidType())
1363 return IsVoidStarType(PT
->getPointeeType());
1366 /// AuditedType - This routine audits the type AT and returns false if it is one of known
1367 /// CF object types or of the "void *" variety. It returns true if we don't care about the type
1368 /// such as a non-pointer or pointers which have no ownership issues (such as "int *").
1369 static bool AuditedType (QualType AT
) {
1370 if (!AT
->isAnyPointerType() && !AT
->isBlockPointerType())
1372 // FIXME. There isn't much we can say about CF pointer type; or is there?
1373 if (ento::coreFoundation::isCFObjectRef(AT
) ||
1374 IsVoidStarType(AT
) ||
1375 // If an ObjC object is type, assuming that it is not a CF function and
1376 // that it is an un-audited function.
1377 AT
->isObjCObjectPointerType() || AT
->isObjCBuiltinType())
1379 // All other pointers are assumed audited as harmless.
1383 void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext
&Ctx
) {
1384 if (CFFunctionIBCandidates
.empty())
1386 if (!NSAPIObj
->isMacroDefined("CF_IMPLICIT_BRIDGING_ENABLED")) {
1387 CFFunctionIBCandidates
.clear();
1391 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
1392 const Decl
*FirstFD
= CFFunctionIBCandidates
[0];
1393 const Decl
*LastFD
=
1394 CFFunctionIBCandidates
[CFFunctionIBCandidates
.size()-1];
1395 const char *PragmaString
= "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1396 edit::Commit
commit(*Editor
);
1397 commit
.insertBefore(FirstFD
->getBeginLoc(), PragmaString
);
1398 PragmaString
= "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1399 SourceLocation EndLoc
= LastFD
->getEndLoc();
1400 // get location just past end of function location.
1401 EndLoc
= PP
.getLocForEndOfToken(EndLoc
);
1402 if (isa
<FunctionDecl
>(LastFD
)) {
1403 // For Methods, EndLoc points to the ending semcolon. So,
1404 // not of these extra work is needed.
1406 // get locaiton of token that comes after end of function.
1407 bool Failed
= PP
.getRawToken(EndLoc
, Tok
, /*IgnoreWhiteSpace=*/true);
1409 EndLoc
= Tok
.getLocation();
1411 commit
.insertAfterToken(EndLoc
, PragmaString
);
1412 Editor
->commit(commit
);
1414 CFFunctionIBCandidates
.clear();
1417 void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext
&Ctx
, const Decl
*Decl
) {
1418 if (Decl
->isDeprecated())
1421 if (Decl
->hasAttr
<CFAuditedTransferAttr
>()) {
1422 assert(CFFunctionIBCandidates
.empty() &&
1423 "Cannot have audited functions/methods inside user "
1424 "provided CF_IMPLICIT_BRIDGING_ENABLE");
1428 // Finction must be annotated first.
1429 if (const FunctionDecl
*FuncDecl
= dyn_cast
<FunctionDecl
>(Decl
)) {
1430 CF_BRIDGING_KIND AuditKind
= migrateAddFunctionAnnotation(Ctx
, FuncDecl
);
1431 if (AuditKind
== CF_BRIDGING_ENABLE
) {
1432 CFFunctionIBCandidates
.push_back(Decl
);
1433 if (FileId
.isInvalid())
1434 FileId
= PP
.getSourceManager().getFileID(Decl
->getLocation());
1436 else if (AuditKind
== CF_BRIDGING_MAY_INCLUDE
) {
1437 if (!CFFunctionIBCandidates
.empty()) {
1438 CFFunctionIBCandidates
.push_back(Decl
);
1439 if (FileId
.isInvalid())
1440 FileId
= PP
.getSourceManager().getFileID(Decl
->getLocation());
1444 AnnotateImplicitBridging(Ctx
);
1447 migrateAddMethodAnnotation(Ctx
, cast
<ObjCMethodDecl
>(Decl
));
1448 AnnotateImplicitBridging(Ctx
);
1452 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext
&Ctx
,
1453 const RetainSummary
*RS
,
1454 const FunctionDecl
*FuncDecl
,
1455 bool ResultAnnotated
) {
1456 // Annotate function.
1457 if (!ResultAnnotated
) {
1458 RetEffect Ret
= RS
->getRetEffect();
1459 const char *AnnotationString
= nullptr;
1460 if (Ret
.getObjKind() == ObjKind::CF
) {
1461 if (Ret
.isOwned() && NSAPIObj
->isMacroDefined("CF_RETURNS_RETAINED"))
1462 AnnotationString
= " CF_RETURNS_RETAINED";
1463 else if (Ret
.notOwned() &&
1464 NSAPIObj
->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
1465 AnnotationString
= " CF_RETURNS_NOT_RETAINED";
1467 else if (Ret
.getObjKind() == ObjKind::ObjC
) {
1468 if (Ret
.isOwned() && NSAPIObj
->isMacroDefined("NS_RETURNS_RETAINED"))
1469 AnnotationString
= " NS_RETURNS_RETAINED";
1472 if (AnnotationString
) {
1473 edit::Commit
commit(*Editor
);
1474 commit
.insertAfterToken(FuncDecl
->getEndLoc(), AnnotationString
);
1475 Editor
->commit(commit
);
1479 for (FunctionDecl::param_const_iterator pi
= FuncDecl
->param_begin(),
1480 pe
= FuncDecl
->param_end(); pi
!= pe
; ++pi
, ++i
) {
1481 const ParmVarDecl
*pd
= *pi
;
1482 ArgEffect AE
= RS
->getArg(i
);
1483 if (AE
.getKind() == DecRef
&& AE
.getObjKind() == ObjKind::CF
&&
1484 !pd
->hasAttr
<CFConsumedAttr
>() &&
1485 NSAPIObj
->isMacroDefined("CF_CONSUMED")) {
1486 edit::Commit
commit(*Editor
);
1487 commit
.insertBefore(pd
->getLocation(), "CF_CONSUMED ");
1488 Editor
->commit(commit
);
1489 } else if (AE
.getKind() == DecRef
&& AE
.getObjKind() == ObjKind::ObjC
&&
1490 !pd
->hasAttr
<NSConsumedAttr
>() &&
1491 NSAPIObj
->isMacroDefined("NS_CONSUMED")) {
1492 edit::Commit
commit(*Editor
);
1493 commit
.insertBefore(pd
->getLocation(), "NS_CONSUMED ");
1494 Editor
->commit(commit
);
1499 ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1500 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1502 const FunctionDecl
*FuncDecl
) {
1503 if (FuncDecl
->hasBody())
1504 return CF_BRIDGING_NONE
;
1506 const RetainSummary
*RS
=
1507 getSummaryManager(Ctx
).getSummary(AnyCall(FuncDecl
));
1508 bool FuncIsReturnAnnotated
= (FuncDecl
->hasAttr
<CFReturnsRetainedAttr
>() ||
1509 FuncDecl
->hasAttr
<CFReturnsNotRetainedAttr
>() ||
1510 FuncDecl
->hasAttr
<NSReturnsRetainedAttr
>() ||
1511 FuncDecl
->hasAttr
<NSReturnsNotRetainedAttr
>() ||
1512 FuncDecl
->hasAttr
<NSReturnsAutoreleasedAttr
>());
1514 // Trivial case of when function is annotated and has no argument.
1515 if (FuncIsReturnAnnotated
&& FuncDecl
->getNumParams() == 0)
1516 return CF_BRIDGING_NONE
;
1518 bool ReturnCFAudited
= false;
1519 if (!FuncIsReturnAnnotated
) {
1520 RetEffect Ret
= RS
->getRetEffect();
1521 if (Ret
.getObjKind() == ObjKind::CF
&&
1522 (Ret
.isOwned() || Ret
.notOwned()))
1523 ReturnCFAudited
= true;
1524 else if (!AuditedType(FuncDecl
->getReturnType()))
1525 return CF_BRIDGING_NONE
;
1528 // At this point result type is audited for potential inclusion.
1530 bool ArgCFAudited
= false;
1531 for (FunctionDecl::param_const_iterator pi
= FuncDecl
->param_begin(),
1532 pe
= FuncDecl
->param_end(); pi
!= pe
; ++pi
, ++i
) {
1533 const ParmVarDecl
*pd
= *pi
;
1534 ArgEffect AE
= RS
->getArg(i
);
1535 if ((AE
.getKind() == DecRef
/*CFConsumed annotated*/ ||
1536 AE
.getKind() == IncRef
) && AE
.getObjKind() == ObjKind::CF
) {
1537 if (AE
.getKind() == DecRef
&& !pd
->hasAttr
<CFConsumedAttr
>())
1538 ArgCFAudited
= true;
1539 else if (AE
.getKind() == IncRef
)
1540 ArgCFAudited
= true;
1542 QualType AT
= pd
->getType();
1543 if (!AuditedType(AT
)) {
1544 AddCFAnnotations(Ctx
, RS
, FuncDecl
, FuncIsReturnAnnotated
);
1545 return CF_BRIDGING_NONE
;
1549 if (ReturnCFAudited
|| ArgCFAudited
)
1550 return CF_BRIDGING_ENABLE
;
1552 return CF_BRIDGING_MAY_INCLUDE
;
1555 void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext
&Ctx
,
1556 ObjCContainerDecl
*CDecl
) {
1557 if (!isa
<ObjCInterfaceDecl
>(CDecl
) || CDecl
->isDeprecated())
1560 // migrate methods which can have instancetype as their result type.
1561 for (const auto *Method
: CDecl
->methods())
1562 migrateCFAnnotation(Ctx
, Method
);
1565 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext
&Ctx
,
1566 const RetainSummary
*RS
,
1567 const ObjCMethodDecl
*MethodDecl
,
1568 bool ResultAnnotated
) {
1569 // Annotate function.
1570 if (!ResultAnnotated
) {
1571 RetEffect Ret
= RS
->getRetEffect();
1572 const char *AnnotationString
= nullptr;
1573 if (Ret
.getObjKind() == ObjKind::CF
) {
1574 if (Ret
.isOwned() && NSAPIObj
->isMacroDefined("CF_RETURNS_RETAINED"))
1575 AnnotationString
= " CF_RETURNS_RETAINED";
1576 else if (Ret
.notOwned() &&
1577 NSAPIObj
->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
1578 AnnotationString
= " CF_RETURNS_NOT_RETAINED";
1580 else if (Ret
.getObjKind() == ObjKind::ObjC
) {
1581 ObjCMethodFamily OMF
= MethodDecl
->getMethodFamily();
1583 case clang::OMF_alloc
:
1584 case clang::OMF_new
:
1585 case clang::OMF_copy
:
1586 case clang::OMF_init
:
1587 case clang::OMF_mutableCopy
:
1591 if (Ret
.isOwned() && NSAPIObj
->isMacroDefined("NS_RETURNS_RETAINED"))
1592 AnnotationString
= " NS_RETURNS_RETAINED";
1597 if (AnnotationString
) {
1598 edit::Commit
commit(*Editor
);
1599 commit
.insertBefore(MethodDecl
->getEndLoc(), AnnotationString
);
1600 Editor
->commit(commit
);
1604 for (ObjCMethodDecl::param_const_iterator pi
= MethodDecl
->param_begin(),
1605 pe
= MethodDecl
->param_end(); pi
!= pe
; ++pi
, ++i
) {
1606 const ParmVarDecl
*pd
= *pi
;
1607 ArgEffect AE
= RS
->getArg(i
);
1608 if (AE
.getKind() == DecRef
1609 && AE
.getObjKind() == ObjKind::CF
1610 && !pd
->hasAttr
<CFConsumedAttr
>() &&
1611 NSAPIObj
->isMacroDefined("CF_CONSUMED")) {
1612 edit::Commit
commit(*Editor
);
1613 commit
.insertBefore(pd
->getLocation(), "CF_CONSUMED ");
1614 Editor
->commit(commit
);
1619 void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
1621 const ObjCMethodDecl
*MethodDecl
) {
1622 if (MethodDecl
->hasBody() || MethodDecl
->isImplicit())
1625 const RetainSummary
*RS
=
1626 getSummaryManager(Ctx
).getSummary(AnyCall(MethodDecl
));
1628 bool MethodIsReturnAnnotated
=
1629 (MethodDecl
->hasAttr
<CFReturnsRetainedAttr
>() ||
1630 MethodDecl
->hasAttr
<CFReturnsNotRetainedAttr
>() ||
1631 MethodDecl
->hasAttr
<NSReturnsRetainedAttr
>() ||
1632 MethodDecl
->hasAttr
<NSReturnsNotRetainedAttr
>() ||
1633 MethodDecl
->hasAttr
<NSReturnsAutoreleasedAttr
>());
1635 if (RS
->getReceiverEffect().getKind() == DecRef
&&
1636 !MethodDecl
->hasAttr
<NSConsumesSelfAttr
>() &&
1637 MethodDecl
->getMethodFamily() != OMF_init
&&
1638 MethodDecl
->getMethodFamily() != OMF_release
&&
1639 NSAPIObj
->isMacroDefined("NS_CONSUMES_SELF")) {
1640 edit::Commit
commit(*Editor
);
1641 commit
.insertBefore(MethodDecl
->getEndLoc(), " NS_CONSUMES_SELF");
1642 Editor
->commit(commit
);
1645 // Trivial case of when function is annotated and has no argument.
1646 if (MethodIsReturnAnnotated
&&
1647 (MethodDecl
->param_begin() == MethodDecl
->param_end()))
1650 if (!MethodIsReturnAnnotated
) {
1651 RetEffect Ret
= RS
->getRetEffect();
1652 if ((Ret
.getObjKind() == ObjKind::CF
||
1653 Ret
.getObjKind() == ObjKind::ObjC
) &&
1654 (Ret
.isOwned() || Ret
.notOwned())) {
1655 AddCFAnnotations(Ctx
, RS
, MethodDecl
, false);
1657 } else if (!AuditedType(MethodDecl
->getReturnType()))
1661 // At this point result type is either annotated or audited.
1663 for (ObjCMethodDecl::param_const_iterator pi
= MethodDecl
->param_begin(),
1664 pe
= MethodDecl
->param_end(); pi
!= pe
; ++pi
, ++i
) {
1665 const ParmVarDecl
*pd
= *pi
;
1666 ArgEffect AE
= RS
->getArg(i
);
1667 if ((AE
.getKind() == DecRef
&& !pd
->hasAttr
<CFConsumedAttr
>()) ||
1668 AE
.getKind() == IncRef
|| !AuditedType(pd
->getType())) {
1669 AddCFAnnotations(Ctx
, RS
, MethodDecl
, MethodIsReturnAnnotated
);
1676 class SuperInitChecker
: public RecursiveASTVisitor
<SuperInitChecker
> {
1678 bool shouldVisitTemplateInstantiations() const { return false; }
1679 bool shouldWalkTypesOfTypeLocs() const { return false; }
1681 bool VisitObjCMessageExpr(ObjCMessageExpr
*E
) {
1682 if (E
->getReceiverKind() == ObjCMessageExpr::SuperInstance
) {
1683 if (E
->getMethodFamily() == OMF_init
)
1689 } // end anonymous namespace
1691 static bool hasSuperInitCall(const ObjCMethodDecl
*MD
) {
1692 return !SuperInitChecker().TraverseStmt(MD
->getBody());
1695 void ObjCMigrateASTConsumer::inferDesignatedInitializers(
1697 const ObjCImplementationDecl
*ImplD
) {
1699 const ObjCInterfaceDecl
*IFace
= ImplD
->getClassInterface();
1700 if (!IFace
|| IFace
->hasDesignatedInitializers())
1702 if (!NSAPIObj
->isMacroDefined("NS_DESIGNATED_INITIALIZER"))
1705 for (const auto *MD
: ImplD
->instance_methods()) {
1706 if (MD
->isDeprecated() ||
1707 MD
->getMethodFamily() != OMF_init
||
1708 MD
->isDesignatedInitializerForTheInterface())
1710 const ObjCMethodDecl
*IFaceM
= IFace
->getMethod(MD
->getSelector(),
1711 /*isInstance=*/true);
1714 if (hasSuperInitCall(MD
)) {
1715 edit::Commit
commit(*Editor
);
1716 commit
.insert(IFaceM
->getEndLoc(), " NS_DESIGNATED_INITIALIZER");
1717 Editor
->commit(commit
);
1722 bool ObjCMigrateASTConsumer::InsertFoundation(ASTContext
&Ctx
,
1723 SourceLocation Loc
) {
1724 if (FoundationIncluded
)
1726 if (Loc
.isInvalid())
1728 auto *nsEnumId
= &Ctx
.Idents
.get("NS_ENUM");
1729 if (PP
.getMacroDefinitionAtLoc(nsEnumId
, Loc
)) {
1730 FoundationIncluded
= true;
1733 edit::Commit
commit(*Editor
);
1734 if (Ctx
.getLangOpts().Modules
)
1735 commit
.insert(Loc
, "#ifndef NS_ENUM\n@import Foundation;\n#endif\n");
1737 commit
.insert(Loc
, "#ifndef NS_ENUM\n#import <Foundation/Foundation.h>\n#endif\n");
1738 Editor
->commit(commit
);
1739 FoundationIncluded
= true;
1745 class RewritesReceiver
: public edit::EditsReceiver
{
1749 RewritesReceiver(Rewriter
&Rewrite
) : Rewrite(Rewrite
) { }
1751 void insert(SourceLocation loc
, StringRef text
) override
{
1752 Rewrite
.InsertText(loc
, text
);
1754 void replace(CharSourceRange range
, StringRef text
) override
{
1755 Rewrite
.ReplaceText(range
.getBegin(), Rewrite
.getRangeSize(range
), text
);
1759 class JSONEditWriter
: public edit::EditsReceiver
{
1760 SourceManager
&SourceMgr
;
1761 llvm::raw_ostream
&OS
;
1764 JSONEditWriter(SourceManager
&SM
, llvm::raw_ostream
&OS
)
1765 : SourceMgr(SM
), OS(OS
) {
1768 ~JSONEditWriter() override
{ OS
<< "]\n"; }
1771 struct EntryWriter
{
1772 SourceManager
&SourceMgr
;
1773 llvm::raw_ostream
&OS
;
1775 EntryWriter(SourceManager
&SM
, llvm::raw_ostream
&OS
)
1776 : SourceMgr(SM
), OS(OS
) {
1783 void writeLoc(SourceLocation Loc
) {
1786 std::tie(FID
, Offset
) = SourceMgr
.getDecomposedLoc(Loc
);
1787 assert(FID
.isValid());
1788 SmallString
<200> Path
=
1789 StringRef(SourceMgr
.getFileEntryForID(FID
)->getName());
1790 llvm::sys::fs::make_absolute(Path
);
1791 OS
<< " \"file\": \"";
1792 OS
.write_escaped(Path
.str()) << "\",\n";
1793 OS
<< " \"offset\": " << Offset
<< ",\n";
1796 void writeRemove(CharSourceRange Range
) {
1797 assert(Range
.isCharRange());
1798 std::pair
<FileID
, unsigned> Begin
=
1799 SourceMgr
.getDecomposedLoc(Range
.getBegin());
1800 std::pair
<FileID
, unsigned> End
=
1801 SourceMgr
.getDecomposedLoc(Range
.getEnd());
1802 assert(Begin
.first
== End
.first
);
1803 assert(Begin
.second
<= End
.second
);
1804 unsigned Length
= End
.second
- Begin
.second
;
1806 OS
<< " \"remove\": " << Length
<< ",\n";
1809 void writeText(StringRef Text
) {
1810 OS
<< " \"text\": \"";
1811 OS
.write_escaped(Text
) << "\",\n";
1815 void insert(SourceLocation Loc
, StringRef Text
) override
{
1816 EntryWriter
Writer(SourceMgr
, OS
);
1817 Writer
.writeLoc(Loc
);
1818 Writer
.writeText(Text
);
1821 void replace(CharSourceRange Range
, StringRef Text
) override
{
1822 EntryWriter
Writer(SourceMgr
, OS
);
1823 Writer
.writeLoc(Range
.getBegin());
1824 Writer
.writeRemove(Range
);
1825 Writer
.writeText(Text
);
1828 void remove(CharSourceRange Range
) override
{
1829 EntryWriter
Writer(SourceMgr
, OS
);
1830 Writer
.writeLoc(Range
.getBegin());
1831 Writer
.writeRemove(Range
);
1835 } // end anonymous namespace
1837 void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext
&Ctx
) {
1839 TranslationUnitDecl
*TU
= Ctx
.getTranslationUnitDecl();
1840 if (ASTMigrateActions
& FrontendOptions::ObjCMT_MigrateDecls
) {
1841 for (DeclContext::decl_iterator D
= TU
->decls_begin(), DEnd
= TU
->decls_end();
1843 FileID FID
= PP
.getSourceManager().getFileID((*D
)->getLocation());
1845 if (FileId
.isValid() && FileId
!= FID
) {
1846 if (ASTMigrateActions
& FrontendOptions::ObjCMT_Annotation
)
1847 AnnotateImplicitBridging(Ctx
);
1850 if (ObjCInterfaceDecl
*CDecl
= dyn_cast
<ObjCInterfaceDecl
>(*D
))
1851 if (canModify(CDecl
))
1852 migrateObjCContainerDecl(Ctx
, CDecl
);
1853 if (ObjCCategoryDecl
*CatDecl
= dyn_cast
<ObjCCategoryDecl
>(*D
)) {
1854 if (canModify(CatDecl
))
1855 migrateObjCContainerDecl(Ctx
, CatDecl
);
1857 else if (ObjCProtocolDecl
*PDecl
= dyn_cast
<ObjCProtocolDecl
>(*D
)) {
1858 ObjCProtocolDecls
.insert(PDecl
->getCanonicalDecl());
1859 if (canModify(PDecl
))
1860 migrateObjCContainerDecl(Ctx
, PDecl
);
1862 else if (const ObjCImplementationDecl
*ImpDecl
=
1863 dyn_cast
<ObjCImplementationDecl
>(*D
)) {
1864 if ((ASTMigrateActions
& FrontendOptions::ObjCMT_ProtocolConformance
) &&
1866 migrateProtocolConformance(Ctx
, ImpDecl
);
1868 else if (const EnumDecl
*ED
= dyn_cast
<EnumDecl
>(*D
)) {
1869 if (!(ASTMigrateActions
& FrontendOptions::ObjCMT_NsMacros
))
1873 DeclContext::decl_iterator N
= D
;
1875 const TypedefDecl
*TD
= dyn_cast
<TypedefDecl
>(*N
);
1876 if (migrateNSEnumDecl(Ctx
, ED
, TD
) && TD
)
1880 migrateNSEnumDecl(Ctx
, ED
, /*TypedefDecl */nullptr);
1882 else if (const TypedefDecl
*TD
= dyn_cast
<TypedefDecl
>(*D
)) {
1883 if (!(ASTMigrateActions
& FrontendOptions::ObjCMT_NsMacros
))
1887 DeclContext::decl_iterator N
= D
;
1890 if (const EnumDecl
*ED
= dyn_cast
<EnumDecl
>(*N
)) {
1891 if (canModify(ED
)) {
1893 if (const TypedefDecl
*TDF
= dyn_cast
<TypedefDecl
>(*N
)) {
1894 // prefer typedef-follows-enum to enum-follows-typedef pattern.
1895 if (migrateNSEnumDecl(Ctx
, ED
, TDF
)) {
1897 CacheObjCNSIntegerTypedefed(TD
);
1901 if (migrateNSEnumDecl(Ctx
, ED
, TD
)) {
1907 CacheObjCNSIntegerTypedefed(TD
);
1909 else if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*D
)) {
1910 if ((ASTMigrateActions
& FrontendOptions::ObjCMT_Annotation
) &&
1912 migrateCFAnnotation(Ctx
, FD
);
1915 if (ObjCContainerDecl
*CDecl
= dyn_cast
<ObjCContainerDecl
>(*D
)) {
1916 bool CanModify
= canModify(CDecl
);
1917 // migrate methods which can have instancetype as their result type.
1918 if ((ASTMigrateActions
& FrontendOptions::ObjCMT_Instancetype
) &&
1920 migrateAllMethodInstaceType(Ctx
, CDecl
);
1921 // annotate methods with CF annotations.
1922 if ((ASTMigrateActions
& FrontendOptions::ObjCMT_Annotation
) &&
1924 migrateARCSafeAnnotation(Ctx
, CDecl
);
1927 if (const ObjCImplementationDecl
*
1928 ImplD
= dyn_cast
<ObjCImplementationDecl
>(*D
)) {
1929 if ((ASTMigrateActions
& FrontendOptions::ObjCMT_DesignatedInitializer
) &&
1931 inferDesignatedInitializers(Ctx
, ImplD
);
1934 if (ASTMigrateActions
& FrontendOptions::ObjCMT_Annotation
)
1935 AnnotateImplicitBridging(Ctx
);
1940 llvm::raw_fd_ostream
OS(MigrateDir
, EC
, llvm::sys::fs::OF_None
);
1942 DiagnosticsEngine
&Diags
= Ctx
.getDiagnostics();
1943 Diags
.Report(Diags
.getCustomDiagID(DiagnosticsEngine::Error
, "%0"))
1948 JSONEditWriter
Writer(Ctx
.getSourceManager(), OS
);
1949 Editor
->applyRewrites(Writer
);
1953 Rewriter
rewriter(Ctx
.getSourceManager(), Ctx
.getLangOpts());
1954 RewritesReceiver
Rec(rewriter
);
1955 Editor
->applyRewrites(Rec
);
1957 for (Rewriter::buffer_iterator
1958 I
= rewriter
.buffer_begin(), E
= rewriter
.buffer_end(); I
!= E
; ++I
) {
1959 FileID FID
= I
->first
;
1960 RewriteBuffer
&buf
= I
->second
;
1961 Optional
<FileEntryRef
> file
= Ctx
.getSourceManager().getFileEntryRefForID(FID
);
1963 SmallString
<512> newText
;
1964 llvm::raw_svector_ostream
vecOS(newText
);
1966 std::unique_ptr
<llvm::MemoryBuffer
> memBuf(
1967 llvm::MemoryBuffer::getMemBufferCopy(
1968 StringRef(newText
.data(), newText
.size()), file
->getName()));
1969 SmallString
<64> filePath(file
->getName());
1970 FileMgr
.FixupRelativePath(filePath
);
1971 Remapper
.remap(filePath
.str(), std::move(memBuf
));
1975 Remapper
.flushToFile(MigrateDir
, Ctx
.getDiagnostics());
1977 Remapper
.flushToDisk(MigrateDir
, Ctx
.getDiagnostics());
1981 bool MigrateSourceAction::BeginInvocation(CompilerInstance
&CI
) {
1982 CI
.getDiagnostics().setIgnoreAllWarnings(true);
1986 static std::vector
<std::string
> getAllowListFilenames(StringRef DirPath
) {
1987 using namespace llvm::sys::fs
;
1988 using namespace llvm::sys::path
;
1990 std::vector
<std::string
> Filenames
;
1991 if (DirPath
.empty() || !is_directory(DirPath
))
1995 directory_iterator DI
= directory_iterator(DirPath
, EC
);
1996 directory_iterator DE
;
1997 for (; !EC
&& DI
!= DE
; DI
= DI
.increment(EC
)) {
1998 if (is_regular_file(DI
->path()))
1999 Filenames
.push_back(std::string(filename(DI
->path())));
2005 std::unique_ptr
<ASTConsumer
>
2006 MigrateSourceAction::CreateASTConsumer(CompilerInstance
&CI
, StringRef InFile
) {
2007 PPConditionalDirectiveRecord
*
2008 PPRec
= new PPConditionalDirectiveRecord(CI
.getSourceManager());
2009 unsigned ObjCMTAction
= CI
.getFrontendOpts().ObjCMTAction
;
2010 unsigned ObjCMTOpts
= ObjCMTAction
;
2011 // These are companion flags, they do not enable transformations.
2012 ObjCMTOpts
&= ~(FrontendOptions::ObjCMT_AtomicProperty
|
2013 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty
);
2014 if (ObjCMTOpts
== FrontendOptions::ObjCMT_None
) {
2015 // If no specific option was given, enable literals+subscripting transforms
2018 FrontendOptions::ObjCMT_Literals
| FrontendOptions::ObjCMT_Subscripting
;
2020 CI
.getPreprocessor().addPPCallbacks(std::unique_ptr
<PPCallbacks
>(PPRec
));
2021 std::vector
<std::string
> AllowList
=
2022 getAllowListFilenames(CI
.getFrontendOpts().ObjCMTAllowListPath
);
2023 return std::make_unique
<ObjCMigrateASTConsumer
>(
2024 CI
.getFrontendOpts().OutputFile
, ObjCMTAction
, Remapper
,
2025 CI
.getFileManager(), PPRec
, CI
.getPreprocessor(),
2026 /*isOutputFile=*/true, AllowList
);
2031 Optional
<FileEntryRef
> File
;
2032 unsigned Offset
= 0;
2033 unsigned RemoveLen
= 0;
2036 } // end anonymous namespace
2039 template<> struct DenseMapInfo
<EditEntry
> {
2040 static inline EditEntry
getEmptyKey() {
2042 Entry
.Offset
= unsigned(-1);
2045 static inline EditEntry
getTombstoneKey() {
2047 Entry
.Offset
= unsigned(-2);
2050 static unsigned getHashValue(const EditEntry
& Val
) {
2051 return (unsigned)llvm::hash_combine(Val
.File
, Val
.Offset
, Val
.RemoveLen
,
2054 static bool isEqual(const EditEntry
&LHS
, const EditEntry
&RHS
) {
2055 return LHS
.File
== RHS
.File
&&
2056 LHS
.Offset
== RHS
.Offset
&&
2057 LHS
.RemoveLen
== RHS
.RemoveLen
&&
2058 LHS
.Text
== RHS
.Text
;
2061 } // end namespace llvm
2064 class RemapFileParser
{
2065 FileManager
&FileMgr
;
2068 RemapFileParser(FileManager
&FileMgr
) : FileMgr(FileMgr
) { }
2070 bool parse(StringRef File
, SmallVectorImpl
<EditEntry
> &Entries
) {
2071 using namespace llvm::yaml
;
2073 llvm::ErrorOr
<std::unique_ptr
<llvm::MemoryBuffer
>> FileBufOrErr
=
2074 llvm::MemoryBuffer::getFile(File
);
2079 Stream
YAMLStream(FileBufOrErr
.get()->getMemBufferRef(), SM
);
2080 document_iterator I
= YAMLStream
.begin();
2081 if (I
== YAMLStream
.end())
2083 Node
*Root
= I
->getRoot();
2087 SequenceNode
*SeqNode
= dyn_cast
<SequenceNode
>(Root
);
2091 for (SequenceNode::iterator
2092 AI
= SeqNode
->begin(), AE
= SeqNode
->end(); AI
!= AE
; ++AI
) {
2093 MappingNode
*MapNode
= dyn_cast
<MappingNode
>(&*AI
);
2096 parseEdit(MapNode
, Entries
);
2103 void parseEdit(llvm::yaml::MappingNode
*Node
,
2104 SmallVectorImpl
<EditEntry
> &Entries
) {
2105 using namespace llvm::yaml
;
2107 bool Ignore
= false;
2109 for (MappingNode::iterator
2110 KVI
= Node
->begin(), KVE
= Node
->end(); KVI
!= KVE
; ++KVI
) {
2111 ScalarNode
*KeyString
= dyn_cast
<ScalarNode
>((*KVI
).getKey());
2114 SmallString
<10> KeyStorage
;
2115 StringRef Key
= KeyString
->getValue(KeyStorage
);
2117 ScalarNode
*ValueString
= dyn_cast
<ScalarNode
>((*KVI
).getValue());
2120 SmallString
<64> ValueStorage
;
2121 StringRef Val
= ValueString
->getValue(ValueStorage
);
2123 if (Key
== "file") {
2124 if (auto File
= FileMgr
.getOptionalFileRef(Val
))
2128 } else if (Key
== "offset") {
2129 if (Val
.getAsInteger(10, Entry
.Offset
))
2131 } else if (Key
== "remove") {
2132 if (Val
.getAsInteger(10, Entry
.RemoveLen
))
2134 } else if (Key
== "text") {
2135 Entry
.Text
= std::string(Val
);
2140 Entries
.push_back(Entry
);
2143 } // end anonymous namespace
2145 static bool reportDiag(const Twine
&Err
, DiagnosticsEngine
&Diag
) {
2146 Diag
.Report(Diag
.getCustomDiagID(DiagnosticsEngine::Error
, "%0"))
2151 static std::string
applyEditsToTemp(FileEntryRef FE
,
2152 ArrayRef
<EditEntry
> Edits
,
2153 FileManager
&FileMgr
,
2154 DiagnosticsEngine
&Diag
) {
2155 using namespace llvm::sys
;
2157 SourceManager
SM(Diag
, FileMgr
);
2158 FileID FID
= SM
.createFileID(FE
, SourceLocation(), SrcMgr::C_User
);
2159 LangOptions LangOpts
;
2160 edit::EditedSource
Editor(SM
, LangOpts
);
2161 for (ArrayRef
<EditEntry
>::iterator
2162 I
= Edits
.begin(), E
= Edits
.end(); I
!= E
; ++I
) {
2163 const EditEntry
&Entry
= *I
;
2164 assert(Entry
.File
== FE
);
2165 SourceLocation Loc
=
2166 SM
.getLocForStartOfFile(FID
).getLocWithOffset(Entry
.Offset
);
2167 CharSourceRange Range
;
2168 if (Entry
.RemoveLen
!= 0) {
2169 Range
= CharSourceRange::getCharRange(Loc
,
2170 Loc
.getLocWithOffset(Entry
.RemoveLen
));
2173 edit::Commit
commit(Editor
);
2174 if (Range
.isInvalid()) {
2175 commit
.insert(Loc
, Entry
.Text
);
2176 } else if (Entry
.Text
.empty()) {
2177 commit
.remove(Range
);
2179 commit
.replace(Range
, Entry
.Text
);
2181 Editor
.commit(commit
);
2184 Rewriter
rewriter(SM
, LangOpts
);
2185 RewritesReceiver
Rec(rewriter
);
2186 Editor
.applyRewrites(Rec
, /*adjustRemovals=*/false);
2188 const RewriteBuffer
*Buf
= rewriter
.getRewriteBufferFor(FID
);
2189 SmallString
<512> NewText
;
2190 llvm::raw_svector_ostream
OS(NewText
);
2193 SmallString
<64> TempPath
;
2195 if (fs::createTemporaryFile(path::filename(FE
.getName()),
2196 path::extension(FE
.getName()).drop_front(), FD
,
2198 reportDiag("Could not create file: " + TempPath
.str(), Diag
);
2199 return std::string();
2202 llvm::raw_fd_ostream
TmpOut(FD
, /*shouldClose=*/true);
2203 TmpOut
.write(NewText
.data(), NewText
.size());
2206 return std::string(TempPath
.str());
2209 bool arcmt::getFileRemappingsFromFileList(
2210 std::vector
<std::pair
<std::string
,std::string
> > &remap
,
2211 ArrayRef
<StringRef
> remapFiles
,
2212 DiagnosticConsumer
*DiagClient
) {
2213 bool hasErrorOccurred
= false;
2215 FileSystemOptions FSOpts
;
2216 FileManager
FileMgr(FSOpts
);
2217 RemapFileParser
Parser(FileMgr
);
2219 IntrusiveRefCntPtr
<DiagnosticIDs
> DiagID(new DiagnosticIDs());
2220 IntrusiveRefCntPtr
<DiagnosticsEngine
> Diags(
2221 new DiagnosticsEngine(DiagID
, new DiagnosticOptions
,
2222 DiagClient
, /*ShouldOwnClient=*/false));
2224 typedef llvm::DenseMap
<FileEntryRef
, std::vector
<EditEntry
> >
2226 FileEditEntriesTy FileEditEntries
;
2228 llvm::DenseSet
<EditEntry
> EntriesSet
;
2230 for (ArrayRef
<StringRef
>::iterator
2231 I
= remapFiles
.begin(), E
= remapFiles
.end(); I
!= E
; ++I
) {
2232 SmallVector
<EditEntry
, 16> Entries
;
2233 if (Parser
.parse(*I
, Entries
))
2236 for (SmallVectorImpl
<EditEntry
>::iterator
2237 EI
= Entries
.begin(), EE
= Entries
.end(); EI
!= EE
; ++EI
) {
2238 EditEntry
&Entry
= *EI
;
2241 std::pair
<llvm::DenseSet
<EditEntry
>::iterator
, bool>
2242 Insert
= EntriesSet
.insert(Entry
);
2246 FileEditEntries
[*Entry
.File
].push_back(Entry
);
2250 for (FileEditEntriesTy::iterator
2251 I
= FileEditEntries
.begin(), E
= FileEditEntries
.end(); I
!= E
; ++I
) {
2252 std::string TempFile
= applyEditsToTemp(I
->first
, I
->second
,
2254 if (TempFile
.empty()) {
2255 hasErrorOccurred
= true;
2259 remap
.emplace_back(std::string(I
->first
.getName()), TempFile
);
2262 return hasErrorOccurred
;