1 //===--- ObjCMT.cpp - ObjC Migrate Tool -----------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "Transforms.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 "clang/StaticAnalyzer/Checkers/ObjCRetainCount.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringSet.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/SourceMgr.h"
35 #include "llvm/Support/YAMLParser.h"
37 using namespace clang;
38 using namespace arcmt;
39 using namespace ento::objc_retain;
43 class ObjCMigrateASTConsumer : public ASTConsumer {
44 enum CF_BRIDGING_KIND {
47 CF_BRIDGING_MAY_INCLUDE
50 void migrateDecl(Decl *D);
51 void migrateObjCContainerDecl(ASTContext &Ctx, ObjCContainerDecl *D);
52 void migrateProtocolConformance(ASTContext &Ctx,
53 const ObjCImplementationDecl *ImpDecl);
54 void CacheObjCNSIntegerTypedefed(const TypedefDecl *TypedefDcl);
55 bool migrateNSEnumDecl(ASTContext &Ctx, const EnumDecl *EnumDcl,
56 const TypedefDecl *TypedefDcl);
57 void migrateAllMethodInstaceType(ASTContext &Ctx, ObjCContainerDecl *CDecl);
58 void migrateMethodInstanceType(ASTContext &Ctx, ObjCContainerDecl *CDecl,
60 bool migrateProperty(ASTContext &Ctx, ObjCContainerDecl *D, ObjCMethodDecl *OM);
61 void migrateNsReturnsInnerPointer(ASTContext &Ctx, ObjCMethodDecl *OM);
62 void migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, ObjCPropertyDecl *P);
63 void migrateFactoryMethod(ASTContext &Ctx, ObjCContainerDecl *CDecl,
65 ObjCInstanceTypeFamily OIT_Family = OIT_None);
67 void migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl);
68 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
69 const FunctionDecl *FuncDecl, bool ResultAnnotated);
70 void AddCFAnnotations(ASTContext &Ctx, const CallEffects &CE,
71 const ObjCMethodDecl *MethodDecl, bool ResultAnnotated);
73 void AnnotateImplicitBridging(ASTContext &Ctx);
75 CF_BRIDGING_KIND migrateAddFunctionAnnotation(ASTContext &Ctx,
76 const FunctionDecl *FuncDecl);
78 void migrateARCSafeAnnotation(ASTContext &Ctx, ObjCContainerDecl *CDecl);
80 void migrateAddMethodAnnotation(ASTContext &Ctx,
81 const ObjCMethodDecl *MethodDecl);
83 void inferDesignatedInitializers(ASTContext &Ctx,
84 const ObjCImplementationDecl *ImplD);
86 bool InsertFoundation(ASTContext &Ctx, SourceLocation Loc);
89 std::string MigrateDir;
90 unsigned ASTMigrateActions;
92 const TypedefDecl *NSIntegerTypedefed;
93 const TypedefDecl *NSUIntegerTypedefed;
94 std::unique_ptr<NSAPI> NSAPIObj;
95 std::unique_ptr<edit::EditedSource> Editor;
96 FileRemapper &Remapper;
98 const PPConditionalDirectiveRecord *PPRec;
101 bool FoundationIncluded;
102 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ObjCProtocolDecls;
103 llvm::SmallVector<const Decl *, 8> CFFunctionIBCandidates;
104 llvm::StringSet<> WhiteListFilenames;
106 ObjCMigrateASTConsumer(StringRef migrateDir,
107 unsigned astMigrateActions,
108 FileRemapper &remapper,
109 FileManager &fileMgr,
110 const PPConditionalDirectiveRecord *PPRec,
113 ArrayRef<std::string> WhiteList)
114 : MigrateDir(migrateDir),
115 ASTMigrateActions(astMigrateActions),
116 NSIntegerTypedefed(nullptr), NSUIntegerTypedefed(nullptr),
117 Remapper(remapper), FileMgr(fileMgr), PPRec(PPRec), PP(PP),
118 IsOutputFile(isOutputFile),
119 FoundationIncluded(false){
121 // FIXME: StringSet should have insert(iter, iter) to use here.
122 for (const std::string &Val : WhiteList)
123 WhiteListFilenames.insert(Val);
127 void Initialize(ASTContext &Context) override {
128 NSAPIObj.reset(new NSAPI(Context));
129 Editor.reset(new edit::EditedSource(Context.getSourceManager(),
130 Context.getLangOpts(),
134 bool HandleTopLevelDecl(DeclGroupRef DG) override {
135 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
139 void HandleInterestingDecl(DeclGroupRef DG) override {
140 // Ignore decls from the PCH.
142 void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) override {
143 ObjCMigrateASTConsumer::HandleTopLevelDecl(DG);
146 void HandleTranslationUnit(ASTContext &Ctx) override;
148 bool canModifyFile(StringRef Path) {
149 if (WhiteListFilenames.empty())
151 return WhiteListFilenames.find(llvm::sys::path::filename(Path))
152 != WhiteListFilenames.end();
154 bool canModifyFile(const FileEntry *FE) {
157 return canModifyFile(FE->getName());
159 bool canModifyFile(FileID FID) {
162 return canModifyFile(PP.getSourceManager().getFileEntryForID(FID));
165 bool canModify(const Decl *D) {
168 if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(D))
169 return canModify(CatImpl->getCategoryDecl());
170 if (const ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D))
171 return canModify(Impl->getClassInterface());
172 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
173 return canModify(cast<Decl>(MD->getDeclContext()));
175 FileID FID = PP.getSourceManager().getFileID(D->getLocation());
176 return canModifyFile(FID);
182 ObjCMigrateAction::ObjCMigrateAction(FrontendAction *WrappedAction,
183 StringRef migrateDir,
184 unsigned migrateAction)
185 : WrapperFrontendAction(WrappedAction), MigrateDir(migrateDir),
186 ObjCMigAction(migrateAction),
188 if (MigrateDir.empty())
189 MigrateDir = "."; // user current directory if none is given.
192 std::unique_ptr<ASTConsumer>
193 ObjCMigrateAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
194 PPConditionalDirectiveRecord *
195 PPRec = new PPConditionalDirectiveRecord(CompInst->getSourceManager());
196 CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
197 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
198 Consumers.push_back(WrapperFrontendAction::CreateASTConsumer(CI, InFile));
199 Consumers.push_back(llvm::make_unique<ObjCMigrateASTConsumer>(
200 MigrateDir, ObjCMigAction, Remapper, CompInst->getFileManager(), PPRec,
201 CompInst->getPreprocessor(), false, None));
202 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
205 bool ObjCMigrateAction::BeginInvocation(CompilerInstance &CI) {
206 Remapper.initFromDisk(MigrateDir, CI.getDiagnostics(),
207 /*ignoreIfFilesChanges=*/true);
209 CI.getDiagnostics().setIgnoreAllWarnings(true);
214 // FIXME. This duplicates one in RewriteObjCFoundationAPI.cpp
215 bool subscriptOperatorNeedsParens(const Expr *FullExpr) {
216 const Expr* Expr = FullExpr->IgnoreImpCasts();
217 if (isa<ArraySubscriptExpr>(Expr) ||
218 isa<CallExpr>(Expr) ||
219 isa<DeclRefExpr>(Expr) ||
220 isa<CXXNamedCastExpr>(Expr) ||
221 isa<CXXConstructExpr>(Expr) ||
222 isa<CXXThisExpr>(Expr) ||
223 isa<CXXTypeidExpr>(Expr) ||
224 isa<CXXUnresolvedConstructExpr>(Expr) ||
225 isa<ObjCMessageExpr>(Expr) ||
226 isa<ObjCPropertyRefExpr>(Expr) ||
227 isa<ObjCProtocolExpr>(Expr) ||
228 isa<MemberExpr>(Expr) ||
229 isa<ObjCIvarRefExpr>(Expr) ||
230 isa<ParenExpr>(FullExpr) ||
231 isa<ParenListExpr>(Expr) ||
232 isa<SizeOfPackExpr>(Expr))
238 /// \brief - Rewrite message expression for Objective-C setter and getters into
239 /// property-dot syntax.
240 bool rewriteToPropertyDotSyntax(const ObjCMessageExpr *Msg,
242 const NSAPI &NS, edit::Commit &commit,
243 const ParentMap *PMap) {
244 if (!Msg || Msg->isImplicit() ||
245 (Msg->getReceiverKind() != ObjCMessageExpr::Instance &&
246 Msg->getReceiverKind() != ObjCMessageExpr::SuperInstance))
248 if (const Expr *Receiver = Msg->getInstanceReceiver())
249 if (Receiver->getType()->isObjCBuiltinType())
252 const ObjCMethodDecl *Method = Msg->getMethodDecl();
255 if (!Method->isPropertyAccessor())
258 const ObjCPropertyDecl *Prop = Method->findPropertyDecl();
262 SourceRange MsgRange = Msg->getSourceRange();
263 bool ReceiverIsSuper =
264 (Msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
265 // for 'super' receiver is nullptr.
266 const Expr *receiver = Msg->getInstanceReceiver();
268 ReceiverIsSuper ? false : subscriptOperatorNeedsParens(receiver);
269 bool IsGetter = (Msg->getNumArgs() == 0);
271 // Find space location range between receiver expression and getter method.
272 SourceLocation BegLoc =
273 ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
274 BegLoc = PP.getLocForEndOfToken(BegLoc);
275 SourceLocation EndLoc = Msg->getSelectorLoc(0);
276 SourceRange SpaceRange(BegLoc, EndLoc);
277 std::string PropertyDotString;
278 // rewrite getter method expression into: receiver.property or
279 // (receiver).property
281 commit.insertBefore(receiver->getLocStart(), "(");
282 PropertyDotString = ").";
285 PropertyDotString = ".";
286 PropertyDotString += Prop->getName();
287 commit.replace(SpaceRange, PropertyDotString);
290 commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
291 commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
294 commit.insertWrap("(", receiver->getSourceRange(), ")");
295 std::string PropertyDotString = ".";
296 PropertyDotString += Prop->getName();
297 PropertyDotString += " =";
298 const Expr*const* Args = Msg->getArgs();
299 const Expr *RHS = Args[0];
302 SourceLocation BegLoc =
303 ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
304 BegLoc = PP.getLocForEndOfToken(BegLoc);
305 SourceLocation EndLoc = RHS->getLocStart();
306 EndLoc = EndLoc.getLocWithOffset(-1);
307 const char *colon = PP.getSourceManager().getCharacterData(EndLoc);
308 // Add a space after '=' if there is no space between RHS and '='
309 if (colon && colon[0] == ':')
310 PropertyDotString += " ";
311 SourceRange Range(BegLoc, EndLoc);
312 commit.replace(Range, PropertyDotString);
314 commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
315 commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
321 class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
322 ObjCMigrateASTConsumer &Consumer;
326 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
327 : Consumer(consumer), PMap(PMap) { }
329 bool shouldVisitTemplateInstantiations() const { return false; }
330 bool shouldWalkTypesOfTypeLocs() const { return false; }
332 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
333 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
334 edit::Commit commit(*Consumer.Editor);
335 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
336 Consumer.Editor->commit(commit);
339 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
340 edit::Commit commit(*Consumer.Editor);
341 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
342 Consumer.Editor->commit(commit);
345 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_PropertyDotSyntax) {
346 edit::Commit commit(*Consumer.Editor);
347 rewriteToPropertyDotSyntax(E, Consumer.PP, *Consumer.NSAPIObj,
349 Consumer.Editor->commit(commit);
355 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
356 // Do depth first; we want to rewrite the subexpressions first so that if
357 // we have to move expressions we will move them already rewritten.
358 for (Stmt *SubStmt : E->children())
359 if (!TraverseStmt(SubStmt))
362 return WalkUpFromObjCMessageExpr(E);
366 class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
367 ObjCMigrateASTConsumer &Consumer;
368 std::unique_ptr<ParentMap> PMap;
371 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
373 bool shouldVisitTemplateInstantiations() const { return false; }
374 bool shouldWalkTypesOfTypeLocs() const { return false; }
376 bool TraverseStmt(Stmt *S) {
377 PMap.reset(new ParentMap(S));
378 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
384 void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
387 if (isa<ObjCMethodDecl>(D))
388 return; // Wait for the ObjC container declaration.
390 BodyMigrator(*this).TraverseDecl(D);
393 static void append_attr(std::string &PropertyString, const char *attr,
396 PropertyString += "(";
400 PropertyString += ", ";
401 PropertyString += attr;
405 void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
406 const std::string& TypeString,
408 const char *argPtr = TypeString.c_str();
413 PropertyString += *argPtr;
417 PropertyString += *argPtr;
422 PropertyString += (*argPtr);
424 PropertyString += name;
429 PropertyString += *argPtr;
436 static const char *PropertyMemoryAttribute(ASTContext &Context, QualType ArgType) {
437 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
438 bool RetainableObject = ArgType->isObjCRetainableType();
439 if (RetainableObject &&
440 (propertyLifetime == Qualifiers::OCL_Strong
441 || propertyLifetime == Qualifiers::OCL_None)) {
442 if (const ObjCObjectPointerType *ObjPtrTy =
443 ArgType->getAs<ObjCObjectPointerType>()) {
444 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
446 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
451 else if (ArgType->isBlockPointerType())
453 } else if (propertyLifetime == Qualifiers::OCL_Weak)
454 // TODO. More precise determination of 'weak' attribute requires
455 // looking into setter's implementation for backing weak ivar.
457 else if (RetainableObject)
458 return ArgType->isBlockPointerType() ? "copy" : "strong";
462 static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
463 const ObjCMethodDecl *Setter,
464 const NSAPI &NS, edit::Commit &commit,
465 unsigned LengthOfPrefix,
466 bool Atomic, bool UseNsIosOnlyMacro,
467 bool AvailabilityArgsMatch) {
468 ASTContext &Context = NS.getASTContext();
469 bool LParenAdded = false;
470 std::string PropertyString = "@property ";
471 if (UseNsIosOnlyMacro && NS.isMacroDefined("NS_NONATOMIC_IOSONLY")) {
472 PropertyString += "(NS_NONATOMIC_IOSONLY";
474 } else if (!Atomic) {
475 PropertyString += "(nonatomic";
479 std::string PropertyNameString = Getter->getNameAsString();
480 StringRef PropertyName(PropertyNameString);
481 if (LengthOfPrefix > 0) {
483 PropertyString += "(getter=";
487 PropertyString += ", getter=";
488 PropertyString += PropertyNameString;
490 // Property with no setter may be suggested as a 'readonly' property.
492 append_attr(PropertyString, "readonly", LParenAdded);
495 // Short circuit 'delegate' properties that contain the name "delegate" or
496 // "dataSource", or have exact name "target" to have 'assign' attribute.
497 if (PropertyName.equals("target") ||
498 (PropertyName.find("delegate") != StringRef::npos) ||
499 (PropertyName.find("dataSource") != StringRef::npos)) {
500 QualType QT = Getter->getReturnType();
501 if (!QT->isRealType())
502 append_attr(PropertyString, "assign", LParenAdded);
503 } else if (!Setter) {
504 QualType ResType = Context.getCanonicalType(Getter->getReturnType());
505 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ResType))
506 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
508 const ParmVarDecl *argDecl = *Setter->param_begin();
509 QualType ArgType = Context.getCanonicalType(argDecl->getType());
510 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ArgType))
511 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
514 PropertyString += ')';
515 QualType RT = Getter->getReturnType();
516 if (!isa<TypedefType>(RT)) {
517 // strip off any ARC lifetime qualifier.
518 QualType CanResultTy = Context.getCanonicalType(RT);
519 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
520 Qualifiers Qs = CanResultTy.getQualifiers();
521 Qs.removeObjCLifetime();
522 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
525 PropertyString += " ";
526 PrintingPolicy SubPolicy(Context.getPrintingPolicy());
527 SubPolicy.SuppressStrongLifetime = true;
528 SubPolicy.SuppressLifetimeQualifiers = true;
529 std::string TypeString = RT.getAsString(SubPolicy);
530 if (LengthOfPrefix > 0) {
531 // property name must strip off "is" and lower case the first character
532 // after that; e.g. isContinuous will become continuous.
533 StringRef PropertyNameStringRef(PropertyNameString);
534 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
535 PropertyNameString = PropertyNameStringRef;
536 bool NoLowering = (isUppercase(PropertyNameString[0]) &&
537 PropertyNameString.size() > 1 &&
538 isUppercase(PropertyNameString[1]));
540 PropertyNameString[0] = toLowercase(PropertyNameString[0]);
542 if (RT->isBlockPointerType() || RT->isFunctionPointerType())
543 MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
545 PropertyNameString.c_str());
547 char LastChar = TypeString[TypeString.size()-1];
548 PropertyString += TypeString;
550 PropertyString += ' ';
551 PropertyString += PropertyNameString;
553 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
554 Selector GetterSelector = Getter->getSelector();
556 SourceLocation EndGetterSelectorLoc =
557 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
558 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
559 EndGetterSelectorLoc),
561 if (Setter && AvailabilityArgsMatch) {
562 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
563 // Get location past ';'
564 EndLoc = EndLoc.getLocWithOffset(1);
565 SourceLocation BeginOfSetterDclLoc = Setter->getLocStart();
566 // FIXME. This assumes that setter decl; is immediately preceded by eoln.
567 // It is trying to remove the setter method decl. line entirely.
568 BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
569 commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
573 static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) {
574 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) {
575 StringRef Name = CatDecl->getName();
576 return Name.endswith("Deprecated");
581 void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx,
582 ObjCContainerDecl *D) {
583 if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D))
586 for (auto *Method : D->methods()) {
587 if (Method->isDeprecated())
589 bool PropertyInferred = migrateProperty(Ctx, D, Method);
590 // If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to
591 // the getter method as it ends up on the property itself which we don't want
592 // to do unless -objcmt-returns-innerpointer-property option is on.
593 if (!PropertyInferred ||
594 (ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
595 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
596 migrateNsReturnsInnerPointer(Ctx, Method);
598 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
601 for (auto *Prop : D->properties()) {
602 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
603 !Prop->isDeprecated())
604 migratePropertyNsReturnsInnerPointer(Ctx, Prop);
609 ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
610 const ObjCImplementationDecl *ImpDecl,
611 const ObjCInterfaceDecl *IDecl,
612 ObjCProtocolDecl *Protocol) {
613 // In auto-synthesis, protocol properties are not synthesized. So,
614 // a conforming protocol must have its required properties declared
615 // in class interface.
616 bool HasAtleastOneRequiredProperty = false;
617 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
618 for (const auto *Property : PDecl->properties()) {
619 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
621 HasAtleastOneRequiredProperty = true;
622 DeclContext::lookup_result R = IDecl->lookup(Property->getDeclName());
624 // Relax the rule and look into class's implementation for a synthesize
625 // or dynamic declaration. Class is implementing a property coming from
626 // another protocol. This still makes the target protocol as conforming.
627 if (!ImpDecl->FindPropertyImplDecl(
628 Property->getDeclName().getAsIdentifierInfo()))
631 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
632 if ((ClassProperty->getPropertyAttributes()
633 != Property->getPropertyAttributes()) ||
634 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
641 // At this point, all required properties in this protocol conform to those
642 // declared in the class.
643 // Check that class implements the required methods of the protocol too.
644 bool HasAtleastOneRequiredMethod = false;
645 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
646 if (PDecl->meth_begin() == PDecl->meth_end())
647 return HasAtleastOneRequiredProperty;
648 for (const auto *MD : PDecl->methods()) {
649 if (MD->isImplicit())
651 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
653 DeclContext::lookup_result R = ImpDecl->lookup(MD->getDeclName());
657 HasAtleastOneRequiredMethod = true;
658 for (unsigned I = 0, N = R.size(); I != N; ++I)
659 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
660 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
668 if (HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod)
673 static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
674 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
675 const NSAPI &NS, edit::Commit &commit) {
676 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
677 std::string ClassString;
678 SourceLocation EndLoc =
679 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
681 if (Protocols.empty()) {
683 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
684 ClassString += ConformingProtocols[i]->getNameAsString();
692 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
693 ClassString += ConformingProtocols[i]->getNameAsString();
697 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
701 commit.insertAfterToken(EndLoc, ClassString);
705 static StringRef GetUnsignedName(StringRef NSIntegerName) {
706 StringRef UnsignedName = llvm::StringSwitch<StringRef>(NSIntegerName)
707 .Case("int8_t", "uint8_t")
708 .Case("int16_t", "uint16_t")
709 .Case("int32_t", "uint32_t")
710 .Case("NSInteger", "NSUInteger")
711 .Case("int64_t", "uint64_t")
712 .Default(NSIntegerName);
716 static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
717 const TypedefDecl *TypedefDcl,
718 const NSAPI &NS, edit::Commit &commit,
719 StringRef NSIntegerName,
721 std::string ClassString;
723 ClassString = "typedef NS_OPTIONS(";
724 ClassString += GetUnsignedName(NSIntegerName);
727 ClassString = "typedef NS_ENUM(";
728 ClassString += NSIntegerName;
732 ClassString += TypedefDcl->getIdentifier()->getName();
734 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
735 commit.replace(R, ClassString);
736 SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
737 EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
738 NS.getASTContext(), /*IsDecl*/true);
739 if (!EndOfEnumDclLoc.isInvalid()) {
740 SourceRange EnumDclRange(EnumDcl->getLocStart(), EndOfEnumDclLoc);
741 commit.insertFromRange(TypedefDcl->getLocStart(), EnumDclRange);
746 SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
747 EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
748 NS.getASTContext(), /*IsDecl*/true);
749 if (!EndTypedefDclLoc.isInvalid()) {
750 SourceRange TDRange(TypedefDcl->getLocStart(), EndTypedefDclLoc);
751 commit.remove(TDRange);
756 EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
758 if (!EndOfEnumDclLoc.isInvalid()) {
759 SourceLocation BeginOfEnumDclLoc = EnumDcl->getLocStart();
760 // FIXME. This assumes that enum decl; is immediately preceded by eoln.
761 // It is trying to remove the enum decl. lines entirely.
762 BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
763 commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
769 static void rewriteToNSMacroDecl(ASTContext &Ctx,
770 const EnumDecl *EnumDcl,
771 const TypedefDecl *TypedefDcl,
772 const NSAPI &NS, edit::Commit &commit,
773 bool IsNSIntegerType) {
774 QualType DesignatedEnumType = EnumDcl->getIntegerType();
775 assert(!DesignatedEnumType.isNull()
776 && "rewriteToNSMacroDecl - underlying enum type is null");
778 PrintingPolicy Policy(Ctx.getPrintingPolicy());
779 std::string TypeString = DesignatedEnumType.getAsString(Policy);
780 std::string ClassString = IsNSIntegerType ? "NS_ENUM(" : "NS_OPTIONS(";
781 ClassString += TypeString;
784 ClassString += TypedefDcl->getIdentifier()->getName();
786 SourceLocation EndLoc;
787 if (EnumDcl->getIntegerTypeSourceInfo()) {
788 TypeSourceInfo *TSourceInfo = EnumDcl->getIntegerTypeSourceInfo();
789 TypeLoc TLoc = TSourceInfo->getTypeLoc();
790 EndLoc = TLoc.getLocEnd();
791 const char *lbrace = Ctx.getSourceManager().getCharacterData(EndLoc);
794 while (lbrace[count] != '{')
797 EndLoc = EndLoc.getLocWithOffset(count-1);
800 EndLoc = EnumDcl->getLocStart();
801 SourceRange R(EnumDcl->getLocStart(), EndLoc);
802 commit.replace(R, ClassString);
803 // This is to remove spaces between '}' and typedef name.
804 SourceLocation StartTypedefLoc = EnumDcl->getLocEnd();
805 StartTypedefLoc = StartTypedefLoc.getLocWithOffset(+1);
806 SourceLocation EndTypedefLoc = TypedefDcl->getLocEnd();
808 commit.remove(SourceRange(StartTypedefLoc, EndTypedefLoc));
811 static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
812 const EnumDecl *EnumDcl) {
813 bool PowerOfTwo = true;
814 bool AllHexdecimalEnumerator = true;
815 uint64_t MaxPowerOfTwoVal = 0;
816 for (auto Enumerator : EnumDcl->enumerators()) {
817 const Expr *InitExpr = Enumerator->getInitExpr();
820 AllHexdecimalEnumerator = false;
823 InitExpr = InitExpr->IgnoreParenCasts();
824 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
825 if (BO->isShiftOp() || BO->isBitwiseOp())
828 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
829 if (PowerOfTwo && EnumVal) {
830 if (!llvm::isPowerOf2_64(EnumVal))
832 else if (EnumVal > MaxPowerOfTwoVal)
833 MaxPowerOfTwoVal = EnumVal;
835 if (AllHexdecimalEnumerator && EnumVal) {
836 bool FoundHexdecimalEnumerator = false;
837 SourceLocation EndLoc = Enumerator->getLocEnd();
839 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
840 if (Tok.isLiteral() && Tok.getLength() > 2) {
841 if (const char *StringLit = Tok.getLiteralData())
842 FoundHexdecimalEnumerator =
843 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
845 if (!FoundHexdecimalEnumerator)
846 AllHexdecimalEnumerator = false;
849 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
852 void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
853 const ObjCImplementationDecl *ImpDecl) {
854 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
855 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
857 // Find all implicit conforming protocols for this class
858 // and make them explicit.
859 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
860 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
861 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
863 for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls)
864 if (!ExplicitProtocols.count(ProtDecl))
865 PotentialImplicitProtocols.push_back(ProtDecl);
867 if (PotentialImplicitProtocols.empty())
870 // go through list of non-optional methods and properties in each protocol
871 // in the PotentialImplicitProtocols list. If class implements every one of the
872 // methods and properties, then this class conforms to this protocol.
873 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
874 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
875 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
876 PotentialImplicitProtocols[i]))
877 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
879 if (ConformingProtocols.empty())
882 // Further reduce number of conforming protocols. If protocol P1 is in the list
883 // protocol P2 (P2<P1>), No need to include P1.
884 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
885 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
887 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
888 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
889 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
890 if (PDecl == TargetPDecl)
892 if (PDecl->lookupProtocolNamed(
893 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
899 MinimalConformingProtocols.push_back(TargetPDecl);
901 if (MinimalConformingProtocols.empty())
903 edit::Commit commit(*Editor);
904 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
906 Editor->commit(commit);
909 void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
910 const TypedefDecl *TypedefDcl) {
912 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
913 if (NSAPIObj->isObjCNSIntegerType(qt))
914 NSIntegerTypedefed = TypedefDcl;
915 else if (NSAPIObj->isObjCNSUIntegerType(qt))
916 NSUIntegerTypedefed = TypedefDcl;
919 bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
920 const EnumDecl *EnumDcl,
921 const TypedefDecl *TypedefDcl) {
922 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
923 EnumDcl->isDeprecated())
926 if (NSIntegerTypedefed) {
927 TypedefDcl = NSIntegerTypedefed;
928 NSIntegerTypedefed = nullptr;
930 else if (NSUIntegerTypedefed) {
931 TypedefDcl = NSUIntegerTypedefed;
932 NSUIntegerTypedefed = nullptr;
936 FileID FileIdOfTypedefDcl =
937 PP.getSourceManager().getFileID(TypedefDcl->getLocation());
938 FileID FileIdOfEnumDcl =
939 PP.getSourceManager().getFileID(EnumDcl->getLocation());
940 if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
943 if (TypedefDcl->isDeprecated())
946 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
947 StringRef NSIntegerName = NSAPIObj->GetNSIntegralKind(qt);
949 if (NSIntegerName.empty()) {
950 // Also check for typedef enum {...} TD;
951 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
952 if (EnumTy->getDecl() == EnumDcl) {
953 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
954 if (!InsertFoundation(Ctx, TypedefDcl->getLocStart()))
956 edit::Commit commit(*Editor);
957 rewriteToNSMacroDecl(Ctx, EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
958 Editor->commit(commit);
965 // We may still use NS_OPTIONS based on what we find in the enumertor list.
966 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
967 if (!InsertFoundation(Ctx, TypedefDcl->getLocStart()))
969 edit::Commit commit(*Editor);
970 bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
971 commit, NSIntegerName, NSOptions);
972 Editor->commit(commit);
976 static void ReplaceWithInstancetype(ASTContext &Ctx,
977 const ObjCMigrateASTConsumer &ASTC,
978 ObjCMethodDecl *OM) {
979 if (OM->getReturnType() == Ctx.getObjCInstanceType())
980 return; // already has instancetype.
983 std::string ClassString;
984 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
985 TypeLoc TL = TSInfo->getTypeLoc();
986 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
987 ClassString = "instancetype";
990 R = SourceRange(OM->getLocStart(), OM->getLocStart());
991 ClassString = OM->isInstanceMethod() ? '-' : '+';
992 ClassString += " (instancetype)";
994 edit::Commit commit(*ASTC.Editor);
995 commit.replace(R, ClassString);
996 ASTC.Editor->commit(commit);
999 static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
1000 ObjCMethodDecl *OM) {
1001 ObjCInterfaceDecl *IDecl = OM->getClassInterface();
1003 std::string ClassString;
1004 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
1005 TypeLoc TL = TSInfo->getTypeLoc();
1006 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
1007 ClassString = IDecl->getName();
1012 R = SourceRange(OM->getLocStart(), OM->getLocStart());
1013 ClassString = "+ (";
1014 ClassString += IDecl->getName(); ClassString += "*)";
1016 edit::Commit commit(*ASTC.Editor);
1017 commit.replace(R, ClassString);
1018 ASTC.Editor->commit(commit);
1021 void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
1022 ObjCContainerDecl *CDecl,
1023 ObjCMethodDecl *OM) {
1024 ObjCInstanceTypeFamily OIT_Family =
1025 Selector::getInstTypeMethodFamily(OM->getSelector());
1027 std::string ClassName;
1028 switch (OIT_Family) {
1030 migrateFactoryMethod(Ctx, CDecl, OM);
1033 ClassName = "NSArray";
1035 case OIT_Dictionary:
1036 ClassName = "NSDictionary";
1039 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
1042 if (OM->getReturnType()->isObjCIdType())
1043 ReplaceWithInstancetype(Ctx, *this, OM);
1045 case OIT_ReturnsSelf:
1046 migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
1049 if (!OM->getReturnType()->isObjCIdType())
1052 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1054 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1055 IDecl = CatDecl->getClassInterface();
1056 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1057 IDecl = ImpDecl->getClassInterface();
1060 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
1061 migrateFactoryMethod(Ctx, CDecl, OM);
1064 ReplaceWithInstancetype(Ctx, *this, OM);
1067 static bool TypeIsInnerPointer(QualType T) {
1068 if (!T->isAnyPointerType())
1070 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
1071 T->isBlockPointerType() || T->isFunctionPointerType() ||
1072 ento::coreFoundation::isCFObjectRef(T))
1074 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
1075 // is not an innter pointer type.
1077 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
1078 T = TD->getDecl()->getUnderlyingType();
1079 if (OrigT == T || !T->isPointerType())
1081 const PointerType* PT = T->getAs<PointerType>();
1082 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
1083 if (UPointeeT->isRecordType()) {
1084 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
1085 if (!RecordTy->getDecl()->isCompleteDefinition())
1091 /// \brief Check whether the two versions match.
1092 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) {
1096 /// AvailabilityAttrsMatch - This routine checks that if comparing two
1097 /// availability attributes, all their components match. It returns
1098 /// true, if not dealing with availability or when all components of
1099 /// availability attributes match. This routine is only called when
1100 /// the attributes are of the same kind.
1101 static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) {
1102 const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1);
1105 const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2);
1107 VersionTuple Introduced1 = AA1->getIntroduced();
1108 VersionTuple Deprecated1 = AA1->getDeprecated();
1109 VersionTuple Obsoleted1 = AA1->getObsoleted();
1110 bool IsUnavailable1 = AA1->getUnavailable();
1111 VersionTuple Introduced2 = AA2->getIntroduced();
1112 VersionTuple Deprecated2 = AA2->getDeprecated();
1113 VersionTuple Obsoleted2 = AA2->getObsoleted();
1114 bool IsUnavailable2 = AA2->getUnavailable();
1115 return (versionsMatch(Introduced1, Introduced2) &&
1116 versionsMatch(Deprecated1, Deprecated2) &&
1117 versionsMatch(Obsoleted1, Obsoleted2) &&
1118 IsUnavailable1 == IsUnavailable2);
1122 static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2,
1123 bool &AvailabilityArgsMatch) {
1124 // This list is very small, so this need not be optimized.
1125 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
1127 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
1128 // Matching attribute kind only. Except for Availabilty attributes,
1129 // we are not getting into details of the attributes. For all practical purposes
1130 // this is sufficient.
1131 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
1132 if (AvailabilityArgsMatch)
1133 AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]);
1144 /// AttributesMatch - This routine checks list of attributes for two
1145 /// decls. It returns false, if there is a mismatch in kind of
1146 /// attributes seen in the decls. It returns true if the two decls
1147 /// have list of same kind of attributes. Furthermore, when there
1148 /// are availability attributes in the two decls, it sets the
1149 /// AvailabilityArgsMatch to false if availability attributes have
1150 /// different versions, etc.
1151 static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2,
1152 bool &AvailabilityArgsMatch) {
1153 if (!Decl1->hasAttrs() || !Decl2->hasAttrs()) {
1154 AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs());
1157 AvailabilityArgsMatch = true;
1158 const AttrVec &Attrs1 = Decl1->getAttrs();
1159 const AttrVec &Attrs2 = Decl2->getAttrs();
1160 bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch);
1161 if (match && (Attrs2.size() > Attrs1.size()))
1162 return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch);
1166 static bool IsValidIdentifier(ASTContext &Ctx,
1168 if (!isIdentifierHead(Name[0]))
1170 std::string NameString = Name;
1171 NameString[0] = toLowercase(NameString[0]);
1172 IdentifierInfo *II = &Ctx.Idents.get(NameString);
1173 return II->getTokenID() == tok::identifier;
1176 bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
1177 ObjCContainerDecl *D,
1178 ObjCMethodDecl *Method) {
1179 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
1180 Method->param_size() != 0)
1182 // Is this method candidate to be a getter?
1183 QualType GRT = Method->getReturnType();
1184 if (GRT->isVoidType())
1187 Selector GetterSelector = Method->getSelector();
1188 ObjCInstanceTypeFamily OIT_Family =
1189 Selector::getInstTypeMethodFamily(GetterSelector);
1191 if (OIT_Family != OIT_None)
1194 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
1195 Selector SetterSelector =
1196 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1197 PP.getSelectorTable(),
1199 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
1200 unsigned LengthOfPrefix = 0;
1201 if (!SetterMethod) {
1202 // try a different naming convention for getter: isXxxxx
1203 StringRef getterNameString = getterName->getName();
1204 bool IsPrefix = getterNameString.startswith("is");
1205 // Note that we don't want to change an isXXX method of retainable object
1206 // type to property (readonly or otherwise).
1207 if (IsPrefix && GRT->isObjCRetainableType())
1209 if (IsPrefix || getterNameString.startswith("get")) {
1210 LengthOfPrefix = (IsPrefix ? 2 : 3);
1211 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
1212 // Make sure that first character after "is" or "get" prefix can
1213 // start an identifier.
1214 if (!IsValidIdentifier(Ctx, CGetterName))
1216 if (CGetterName[0] && isUppercase(CGetterName[0])) {
1217 getterName = &Ctx.Idents.get(CGetterName);
1219 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1220 PP.getSelectorTable(),
1222 SetterMethod = D->getInstanceMethod(SetterSelector);
1228 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
1230 bool AvailabilityArgsMatch;
1231 if (SetterMethod->isDeprecated() ||
1232 !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch))
1235 // Is this a valid setter, matching the target getter?
1236 QualType SRT = SetterMethod->getReturnType();
1237 if (!SRT->isVoidType())
1239 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
1240 QualType ArgType = argDecl->getType();
1241 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
1243 edit::Commit commit(*Editor);
1244 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
1246 (ASTMigrateActions &
1247 FrontendOptions::ObjCMT_AtomicProperty) != 0,
1248 (ASTMigrateActions &
1249 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
1250 AvailabilityArgsMatch);
1251 Editor->commit(commit);
1254 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
1255 // Try a non-void method with no argument (and no setter or property of same name
1256 // as a 'readonly' property.
1257 edit::Commit commit(*Editor);
1258 rewriteToObjCProperty(Method, nullptr /*SetterMethod*/, *NSAPIObj, commit,
1260 (ASTMigrateActions &
1261 FrontendOptions::ObjCMT_AtomicProperty) != 0,
1262 (ASTMigrateActions &
1263 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
1264 /*AvailabilityArgsMatch*/false);
1265 Editor->commit(commit);
1271 void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
1272 ObjCMethodDecl *OM) {
1273 if (OM->isImplicit() ||
1274 !OM->isInstanceMethod() ||
1275 OM->hasAttr<ObjCReturnsInnerPointerAttr>())
1278 QualType RT = OM->getReturnType();
1279 if (!TypeIsInnerPointer(RT) ||
1280 !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
1283 edit::Commit commit(*Editor);
1284 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
1285 Editor->commit(commit);
1288 void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
1289 ObjCPropertyDecl *P) {
1290 QualType T = P->getType();
1292 if (!TypeIsInnerPointer(T) ||
1293 !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
1295 edit::Commit commit(*Editor);
1296 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
1297 Editor->commit(commit);
1300 void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
1301 ObjCContainerDecl *CDecl) {
1302 if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl))
1305 // migrate methods which can have instancetype as their result type.
1306 for (auto *Method : CDecl->methods()) {
1307 if (Method->isDeprecated())
1309 migrateMethodInstanceType(Ctx, CDecl, Method);
1313 void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
1314 ObjCContainerDecl *CDecl,
1316 ObjCInstanceTypeFamily OIT_Family) {
1317 if (OM->isInstanceMethod() ||
1318 OM->getReturnType() == Ctx.getObjCInstanceType() ||
1319 !OM->getReturnType()->isObjCIdType())
1322 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1323 // NSYYYNamE with matching names be at least 3 characters long.
1324 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1326 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1327 IDecl = CatDecl->getClassInterface();
1328 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1329 IDecl = ImpDecl->getClassInterface();
1334 std::string StringClassName = IDecl->getName();
1335 StringRef LoweredClassName(StringClassName);
1336 std::string StringLoweredClassName = LoweredClassName.lower();
1337 LoweredClassName = StringLoweredClassName;
1339 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
1340 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1344 std::string MethodName = MethodIdName->getName();
1345 if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
1346 StringRef STRefMethodName(MethodName);
1348 if (STRefMethodName.startswith("standard"))
1349 len = strlen("standard");
1350 else if (STRefMethodName.startswith("shared"))
1351 len = strlen("shared");
1352 else if (STRefMethodName.startswith("default"))
1353 len = strlen("default");
1356 MethodName = STRefMethodName.substr(len);
1358 std::string MethodNameSubStr = MethodName.substr(0, 3);
1359 StringRef MethodNamePrefix(MethodNameSubStr);
1360 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1361 MethodNamePrefix = StringLoweredMethodNamePrefix;
1362 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1363 if (Ix == StringRef::npos)
1365 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1366 StringRef LoweredMethodName(MethodName);
1367 std::string StringLoweredMethodName = LoweredMethodName.lower();
1368 LoweredMethodName = StringLoweredMethodName;
1369 if (!LoweredMethodName.startswith(ClassNamePostfix))
1371 if (OIT_Family == OIT_ReturnsSelf)
1372 ReplaceWithClasstype(*this, OM);
1374 ReplaceWithInstancetype(Ctx, *this, OM);
1377 static bool IsVoidStarType(QualType Ty) {
1378 if (!Ty->isPointerType())
1381 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1382 Ty = TD->getDecl()->getUnderlyingType();
1384 // Is the type void*?
1385 const PointerType* PT = Ty->getAs<PointerType>();
1386 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1388 return IsVoidStarType(PT->getPointeeType());
1391 /// AuditedType - This routine audits the type AT and returns false if it is one of known
1392 /// CF object types or of the "void *" variety. It returns true if we don't care about the type
1393 /// such as a non-pointer or pointers which have no ownership issues (such as "int *").
1394 static bool AuditedType (QualType AT) {
1395 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
1397 // FIXME. There isn't much we can say about CF pointer type; or is there?
1398 if (ento::coreFoundation::isCFObjectRef(AT) ||
1399 IsVoidStarType(AT) ||
1400 // If an ObjC object is type, assuming that it is not a CF function and
1401 // that it is an un-audited function.
1402 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
1404 // All other pointers are assumed audited as harmless.
1408 void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
1409 if (CFFunctionIBCandidates.empty())
1411 if (!NSAPIObj->isMacroDefined("CF_IMPLICIT_BRIDGING_ENABLED")) {
1412 CFFunctionIBCandidates.clear();
1416 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
1417 const Decl *FirstFD = CFFunctionIBCandidates[0];
1418 const Decl *LastFD =
1419 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
1420 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1421 edit::Commit commit(*Editor);
1422 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
1423 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1424 SourceLocation EndLoc = LastFD->getLocEnd();
1425 // get location just past end of function location.
1426 EndLoc = PP.getLocForEndOfToken(EndLoc);
1427 if (isa<FunctionDecl>(LastFD)) {
1428 // For Methods, EndLoc points to the ending semcolon. So,
1429 // not of these extra work is needed.
1431 // get locaiton of token that comes after end of function.
1432 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1434 EndLoc = Tok.getLocation();
1436 commit.insertAfterToken(EndLoc, PragmaString);
1437 Editor->commit(commit);
1439 CFFunctionIBCandidates.clear();
1442 void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
1443 if (Decl->isDeprecated())
1446 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
1447 assert(CFFunctionIBCandidates.empty() &&
1448 "Cannot have audited functions/methods inside user "
1449 "provided CF_IMPLICIT_BRIDGING_ENABLE");
1453 // Finction must be annotated first.
1454 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1455 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1456 if (AuditKind == CF_BRIDGING_ENABLE) {
1457 CFFunctionIBCandidates.push_back(Decl);
1458 if (FileId.isInvalid())
1459 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
1461 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1462 if (!CFFunctionIBCandidates.empty()) {
1463 CFFunctionIBCandidates.push_back(Decl);
1464 if (FileId.isInvalid())
1465 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
1469 AnnotateImplicitBridging(Ctx);
1472 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
1473 AnnotateImplicitBridging(Ctx);
1477 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1478 const CallEffects &CE,
1479 const FunctionDecl *FuncDecl,
1480 bool ResultAnnotated) {
1481 // Annotate function.
1482 if (!ResultAnnotated) {
1483 RetEffect Ret = CE.getReturnValue();
1484 const char *AnnotationString = nullptr;
1485 if (Ret.getObjKind() == RetEffect::CF) {
1486 if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
1487 AnnotationString = " CF_RETURNS_RETAINED";
1488 else if (Ret.notOwned() &&
1489 NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
1490 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1492 else if (Ret.getObjKind() == RetEffect::ObjC) {
1493 if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
1494 AnnotationString = " NS_RETURNS_RETAINED";
1497 if (AnnotationString) {
1498 edit::Commit commit(*Editor);
1499 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1500 Editor->commit(commit);
1503 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1505 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1506 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1507 const ParmVarDecl *pd = *pi;
1508 ArgEffect AE = AEArgs[i];
1509 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
1510 NSAPIObj->isMacroDefined("CF_CONSUMED")) {
1511 edit::Commit commit(*Editor);
1512 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1513 Editor->commit(commit);
1515 else if (AE == DecRefMsg && !pd->hasAttr<NSConsumedAttr>() &&
1516 NSAPIObj->isMacroDefined("NS_CONSUMED")) {
1517 edit::Commit commit(*Editor);
1518 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1519 Editor->commit(commit);
1525 ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1526 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1528 const FunctionDecl *FuncDecl) {
1529 if (FuncDecl->hasBody())
1530 return CF_BRIDGING_NONE;
1532 CallEffects CE = CallEffects::getEffect(FuncDecl);
1533 bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() ||
1534 FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1535 FuncDecl->hasAttr<NSReturnsRetainedAttr>() ||
1536 FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1537 FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>());
1539 // Trivial case of when funciton is annotated and has no argument.
1540 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1541 return CF_BRIDGING_NONE;
1543 bool ReturnCFAudited = false;
1544 if (!FuncIsReturnAnnotated) {
1545 RetEffect Ret = CE.getReturnValue();
1546 if (Ret.getObjKind() == RetEffect::CF &&
1547 (Ret.isOwned() || Ret.notOwned()))
1548 ReturnCFAudited = true;
1549 else if (!AuditedType(FuncDecl->getReturnType()))
1550 return CF_BRIDGING_NONE;
1553 // At this point result type is audited for potential inclusion.
1554 // Now, how about argument types.
1555 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1557 bool ArgCFAudited = false;
1558 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1559 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1560 const ParmVarDecl *pd = *pi;
1561 ArgEffect AE = AEArgs[i];
1562 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1563 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>())
1564 ArgCFAudited = true;
1565 else if (AE == IncRef)
1566 ArgCFAudited = true;
1569 QualType AT = pd->getType();
1570 if (!AuditedType(AT)) {
1571 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
1572 return CF_BRIDGING_NONE;
1576 if (ReturnCFAudited || ArgCFAudited)
1577 return CF_BRIDGING_ENABLE;
1579 return CF_BRIDGING_MAY_INCLUDE;
1582 void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1583 ObjCContainerDecl *CDecl) {
1584 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
1587 // migrate methods which can have instancetype as their result type.
1588 for (const auto *Method : CDecl->methods())
1589 migrateCFAnnotation(Ctx, Method);
1592 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1593 const CallEffects &CE,
1594 const ObjCMethodDecl *MethodDecl,
1595 bool ResultAnnotated) {
1596 // Annotate function.
1597 if (!ResultAnnotated) {
1598 RetEffect Ret = CE.getReturnValue();
1599 const char *AnnotationString = nullptr;
1600 if (Ret.getObjKind() == RetEffect::CF) {
1601 if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
1602 AnnotationString = " CF_RETURNS_RETAINED";
1603 else if (Ret.notOwned() &&
1604 NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
1605 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1607 else if (Ret.getObjKind() == RetEffect::ObjC) {
1608 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1610 case clang::OMF_alloc:
1611 case clang::OMF_new:
1612 case clang::OMF_copy:
1613 case clang::OMF_init:
1614 case clang::OMF_mutableCopy:
1618 if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
1619 AnnotationString = " NS_RETURNS_RETAINED";
1624 if (AnnotationString) {
1625 edit::Commit commit(*Editor);
1626 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1627 Editor->commit(commit);
1630 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1632 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1633 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1634 const ParmVarDecl *pd = *pi;
1635 ArgEffect AE = AEArgs[i];
1636 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
1637 NSAPIObj->isMacroDefined("CF_CONSUMED")) {
1638 edit::Commit commit(*Editor);
1639 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1640 Editor->commit(commit);
1645 void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
1647 const ObjCMethodDecl *MethodDecl) {
1648 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
1651 CallEffects CE = CallEffects::getEffect(MethodDecl);
1652 bool MethodIsReturnAnnotated = (MethodDecl->hasAttr<CFReturnsRetainedAttr>() ||
1653 MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1654 MethodDecl->hasAttr<NSReturnsRetainedAttr>() ||
1655 MethodDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1656 MethodDecl->hasAttr<NSReturnsAutoreleasedAttr>());
1658 if (CE.getReceiver() == DecRefMsg &&
1659 !MethodDecl->hasAttr<NSConsumesSelfAttr>() &&
1660 MethodDecl->getMethodFamily() != OMF_init &&
1661 MethodDecl->getMethodFamily() != OMF_release &&
1662 NSAPIObj->isMacroDefined("NS_CONSUMES_SELF")) {
1663 edit::Commit commit(*Editor);
1664 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1665 Editor->commit(commit);
1668 // Trivial case of when funciton is annotated and has no argument.
1669 if (MethodIsReturnAnnotated &&
1670 (MethodDecl->param_begin() == MethodDecl->param_end()))
1673 if (!MethodIsReturnAnnotated) {
1674 RetEffect Ret = CE.getReturnValue();
1675 if ((Ret.getObjKind() == RetEffect::CF ||
1676 Ret.getObjKind() == RetEffect::ObjC) &&
1677 (Ret.isOwned() || Ret.notOwned())) {
1678 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1680 } else if (!AuditedType(MethodDecl->getReturnType()))
1684 // At this point result type is either annotated or audited.
1685 // Now, how about argument types.
1686 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1688 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1689 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1690 const ParmVarDecl *pd = *pi;
1691 ArgEffect AE = AEArgs[i];
1692 if ((AE == DecRef && !pd->hasAttr<CFConsumedAttr>()) || AE == IncRef ||
1693 !AuditedType(pd->getType())) {
1694 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1702 class SuperInitChecker : public RecursiveASTVisitor<SuperInitChecker> {
1704 bool shouldVisitTemplateInstantiations() const { return false; }
1705 bool shouldWalkTypesOfTypeLocs() const { return false; }
1707 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
1708 if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
1709 if (E->getMethodFamily() == OMF_init)
1715 } // anonymous namespace
1717 static bool hasSuperInitCall(const ObjCMethodDecl *MD) {
1718 return !SuperInitChecker().TraverseStmt(MD->getBody());
1721 void ObjCMigrateASTConsumer::inferDesignatedInitializers(
1723 const ObjCImplementationDecl *ImplD) {
1725 const ObjCInterfaceDecl *IFace = ImplD->getClassInterface();
1726 if (!IFace || IFace->hasDesignatedInitializers())
1728 if (!NSAPIObj->isMacroDefined("NS_DESIGNATED_INITIALIZER"))
1731 for (const auto *MD : ImplD->instance_methods()) {
1732 if (MD->isDeprecated() ||
1733 MD->getMethodFamily() != OMF_init ||
1734 MD->isDesignatedInitializerForTheInterface())
1736 const ObjCMethodDecl *IFaceM = IFace->getMethod(MD->getSelector(),
1737 /*isInstance=*/true);
1740 if (hasSuperInitCall(MD)) {
1741 edit::Commit commit(*Editor);
1742 commit.insert(IFaceM->getLocEnd(), " NS_DESIGNATED_INITIALIZER");
1743 Editor->commit(commit);
1748 bool ObjCMigrateASTConsumer::InsertFoundation(ASTContext &Ctx,
1749 SourceLocation Loc) {
1750 if (FoundationIncluded)
1752 if (Loc.isInvalid())
1754 edit::Commit commit(*Editor);
1755 if (Ctx.getLangOpts().Modules)
1756 commit.insert(Loc, "#ifndef NS_ENUM\n@import Foundation;\n#endif\n");
1758 commit.insert(Loc, "#ifndef NS_ENUM\n#import <Foundation/Foundation.h>\n#endif\n");
1759 Editor->commit(commit);
1760 FoundationIncluded = true;
1766 class RewritesReceiver : public edit::EditsReceiver {
1770 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1772 void insert(SourceLocation loc, StringRef text) override {
1773 Rewrite.InsertText(loc, text);
1775 void replace(CharSourceRange range, StringRef text) override {
1776 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1780 class JSONEditWriter : public edit::EditsReceiver {
1781 SourceManager &SourceMgr;
1782 llvm::raw_ostream &OS;
1785 JSONEditWriter(SourceManager &SM, llvm::raw_ostream &OS)
1786 : SourceMgr(SM), OS(OS) {
1789 ~JSONEditWriter() override { OS << "]\n"; }
1792 struct EntryWriter {
1793 SourceManager &SourceMgr;
1794 llvm::raw_ostream &OS;
1796 EntryWriter(SourceManager &SM, llvm::raw_ostream &OS)
1797 : SourceMgr(SM), OS(OS) {
1804 void writeLoc(SourceLocation Loc) {
1807 std::tie(FID, Offset) = SourceMgr.getDecomposedLoc(Loc);
1808 assert(!FID.isInvalid());
1809 SmallString<200> Path =
1810 StringRef(SourceMgr.getFileEntryForID(FID)->getName());
1811 llvm::sys::fs::make_absolute(Path);
1812 OS << " \"file\": \"";
1813 OS.write_escaped(Path.str()) << "\",\n";
1814 OS << " \"offset\": " << Offset << ",\n";
1817 void writeRemove(CharSourceRange Range) {
1818 assert(Range.isCharRange());
1819 std::pair<FileID, unsigned> Begin =
1820 SourceMgr.getDecomposedLoc(Range.getBegin());
1821 std::pair<FileID, unsigned> End =
1822 SourceMgr.getDecomposedLoc(Range.getEnd());
1823 assert(Begin.first == End.first);
1824 assert(Begin.second <= End.second);
1825 unsigned Length = End.second - Begin.second;
1827 OS << " \"remove\": " << Length << ",\n";
1830 void writeText(StringRef Text) {
1831 OS << " \"text\": \"";
1832 OS.write_escaped(Text) << "\",\n";
1836 void insert(SourceLocation Loc, StringRef Text) override {
1837 EntryWriter Writer(SourceMgr, OS);
1838 Writer.writeLoc(Loc);
1839 Writer.writeText(Text);
1842 void replace(CharSourceRange Range, StringRef Text) override {
1843 EntryWriter Writer(SourceMgr, OS);
1844 Writer.writeLoc(Range.getBegin());
1845 Writer.writeRemove(Range);
1846 Writer.writeText(Text);
1849 void remove(CharSourceRange Range) override {
1850 EntryWriter Writer(SourceMgr, OS);
1851 Writer.writeLoc(Range.getBegin());
1852 Writer.writeRemove(Range);
1858 void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
1860 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
1861 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
1862 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1864 FileID FID = PP.getSourceManager().getFileID((*D)->getLocation());
1865 if (!FID.isInvalid())
1866 if (!FileId.isInvalid() && FileId != FID) {
1867 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1868 AnnotateImplicitBridging(Ctx);
1871 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1872 if (canModify(CDecl))
1873 migrateObjCContainerDecl(Ctx, CDecl);
1874 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) {
1875 if (canModify(CatDecl))
1876 migrateObjCContainerDecl(Ctx, CatDecl);
1878 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D)) {
1879 ObjCProtocolDecls.insert(PDecl->getCanonicalDecl());
1880 if (canModify(PDecl))
1881 migrateObjCContainerDecl(Ctx, PDecl);
1883 else if (const ObjCImplementationDecl *ImpDecl =
1884 dyn_cast<ObjCImplementationDecl>(*D)) {
1885 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) &&
1887 migrateProtocolConformance(Ctx, ImpDecl);
1889 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1890 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1894 DeclContext::decl_iterator N = D;
1896 const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
1897 if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
1901 migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */nullptr);
1903 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
1904 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1908 DeclContext::decl_iterator N = D;
1911 if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
1913 if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) {
1914 // prefer typedef-follows-enum to enum-follows-typedef pattern.
1915 if (migrateNSEnumDecl(Ctx, ED, TDF)) {
1917 CacheObjCNSIntegerTypedefed(TD);
1921 if (migrateNSEnumDecl(Ctx, ED, TD)) {
1926 CacheObjCNSIntegerTypedefed(TD);
1928 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
1929 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1931 migrateCFAnnotation(Ctx, FD);
1934 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1935 bool CanModify = canModify(CDecl);
1936 // migrate methods which can have instancetype as their result type.
1937 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) &&
1939 migrateAllMethodInstaceType(Ctx, CDecl);
1940 // annotate methods with CF annotations.
1941 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1943 migrateARCSafeAnnotation(Ctx, CDecl);
1946 if (const ObjCImplementationDecl *
1947 ImplD = dyn_cast<ObjCImplementationDecl>(*D)) {
1948 if ((ASTMigrateActions & FrontendOptions::ObjCMT_DesignatedInitializer) &&
1950 inferDesignatedInitializers(Ctx, ImplD);
1953 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1954 AnnotateImplicitBridging(Ctx);
1959 llvm::raw_fd_ostream OS(MigrateDir, EC, llvm::sys::fs::F_None);
1961 DiagnosticsEngine &Diags = Ctx.getDiagnostics();
1962 Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
1967 JSONEditWriter Writer(Ctx.getSourceManager(), OS);
1968 Editor->applyRewrites(Writer);
1972 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
1973 RewritesReceiver Rec(rewriter);
1974 Editor->applyRewrites(Rec);
1976 for (Rewriter::buffer_iterator
1977 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1978 FileID FID = I->first;
1979 RewriteBuffer &buf = I->second;
1980 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1982 SmallString<512> newText;
1983 llvm::raw_svector_ostream vecOS(newText);
1986 std::unique_ptr<llvm::MemoryBuffer> memBuf(
1987 llvm::MemoryBuffer::getMemBufferCopy(
1988 StringRef(newText.data(), newText.size()), file->getName()));
1989 SmallString<64> filePath(file->getName());
1990 FileMgr.FixupRelativePath(filePath);
1991 Remapper.remap(filePath.str(), std::move(memBuf));
1995 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1997 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
2001 bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
2002 CI.getDiagnostics().setIgnoreAllWarnings(true);
2006 static std::vector<std::string> getWhiteListFilenames(StringRef DirPath) {
2007 using namespace llvm::sys::fs;
2008 using namespace llvm::sys::path;
2010 std::vector<std::string> Filenames;
2011 if (DirPath.empty() || !is_directory(DirPath))
2015 directory_iterator DI = directory_iterator(DirPath, EC);
2016 directory_iterator DE;
2017 for (; !EC && DI != DE; DI = DI.increment(EC)) {
2018 if (is_regular_file(DI->path()))
2019 Filenames.push_back(filename(DI->path()));
2025 std::unique_ptr<ASTConsumer>
2026 MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
2027 PPConditionalDirectiveRecord *
2028 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
2029 unsigned ObjCMTAction = CI.getFrontendOpts().ObjCMTAction;
2030 unsigned ObjCMTOpts = ObjCMTAction;
2031 // These are companion flags, they do not enable transformations.
2032 ObjCMTOpts &= ~(FrontendOptions::ObjCMT_AtomicProperty |
2033 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty);
2034 if (ObjCMTOpts == FrontendOptions::ObjCMT_None) {
2035 // If no specific option was given, enable literals+subscripting transforms
2037 ObjCMTAction |= FrontendOptions::ObjCMT_Literals |
2038 FrontendOptions::ObjCMT_Subscripting;
2040 CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
2041 std::vector<std::string> WhiteList =
2042 getWhiteListFilenames(CI.getFrontendOpts().ObjCMTWhiteListPath);
2043 return llvm::make_unique<ObjCMigrateASTConsumer>(
2044 CI.getFrontendOpts().OutputFile, ObjCMTAction, Remapper,
2045 CI.getFileManager(), PPRec, CI.getPreprocessor(),
2046 /*isOutputFile=*/true, WhiteList);
2051 const FileEntry *File;
2056 EditEntry() : File(), Offset(), RemoveLen() {}
2061 template<> struct DenseMapInfo<EditEntry> {
2062 static inline EditEntry getEmptyKey() {
2064 Entry.Offset = unsigned(-1);
2067 static inline EditEntry getTombstoneKey() {
2069 Entry.Offset = unsigned(-2);
2072 static unsigned getHashValue(const EditEntry& Val) {
2073 llvm::FoldingSetNodeID ID;
2074 ID.AddPointer(Val.File);
2075 ID.AddInteger(Val.Offset);
2076 ID.AddInteger(Val.RemoveLen);
2077 ID.AddString(Val.Text);
2078 return ID.ComputeHash();
2080 static bool isEqual(const EditEntry &LHS, const EditEntry &RHS) {
2081 return LHS.File == RHS.File &&
2082 LHS.Offset == RHS.Offset &&
2083 LHS.RemoveLen == RHS.RemoveLen &&
2084 LHS.Text == RHS.Text;
2090 class RemapFileParser {
2091 FileManager &FileMgr;
2094 RemapFileParser(FileManager &FileMgr) : FileMgr(FileMgr) { }
2096 bool parse(StringRef File, SmallVectorImpl<EditEntry> &Entries) {
2097 using namespace llvm::yaml;
2099 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
2100 llvm::MemoryBuffer::getFile(File);
2105 Stream YAMLStream(FileBufOrErr.get()->getMemBufferRef(), SM);
2106 document_iterator I = YAMLStream.begin();
2107 if (I == YAMLStream.end())
2109 Node *Root = I->getRoot();
2113 SequenceNode *SeqNode = dyn_cast<SequenceNode>(Root);
2117 for (SequenceNode::iterator
2118 AI = SeqNode->begin(), AE = SeqNode->end(); AI != AE; ++AI) {
2119 MappingNode *MapNode = dyn_cast<MappingNode>(&*AI);
2122 parseEdit(MapNode, Entries);
2129 void parseEdit(llvm::yaml::MappingNode *Node,
2130 SmallVectorImpl<EditEntry> &Entries) {
2131 using namespace llvm::yaml;
2133 bool Ignore = false;
2135 for (MappingNode::iterator
2136 KVI = Node->begin(), KVE = Node->end(); KVI != KVE; ++KVI) {
2137 ScalarNode *KeyString = dyn_cast<ScalarNode>((*KVI).getKey());
2140 SmallString<10> KeyStorage;
2141 StringRef Key = KeyString->getValue(KeyStorage);
2143 ScalarNode *ValueString = dyn_cast<ScalarNode>((*KVI).getValue());
2146 SmallString<64> ValueStorage;
2147 StringRef Val = ValueString->getValue(ValueStorage);
2149 if (Key == "file") {
2150 const FileEntry *FE = FileMgr.getFile(Val);
2154 } else if (Key == "offset") {
2155 if (Val.getAsInteger(10, Entry.Offset))
2157 } else if (Key == "remove") {
2158 if (Val.getAsInteger(10, Entry.RemoveLen))
2160 } else if (Key == "text") {
2166 Entries.push_back(Entry);
2171 static bool reportDiag(const Twine &Err, DiagnosticsEngine &Diag) {
2172 Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
2177 static std::string applyEditsToTemp(const FileEntry *FE,
2178 ArrayRef<EditEntry> Edits,
2179 FileManager &FileMgr,
2180 DiagnosticsEngine &Diag) {
2181 using namespace llvm::sys;
2183 SourceManager SM(Diag, FileMgr);
2184 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
2185 LangOptions LangOpts;
2186 edit::EditedSource Editor(SM, LangOpts);
2187 for (ArrayRef<EditEntry>::iterator
2188 I = Edits.begin(), E = Edits.end(); I != E; ++I) {
2189 const EditEntry &Entry = *I;
2190 assert(Entry.File == FE);
2191 SourceLocation Loc =
2192 SM.getLocForStartOfFile(FID).getLocWithOffset(Entry.Offset);
2193 CharSourceRange Range;
2194 if (Entry.RemoveLen != 0) {
2195 Range = CharSourceRange::getCharRange(Loc,
2196 Loc.getLocWithOffset(Entry.RemoveLen));
2199 edit::Commit commit(Editor);
2200 if (Range.isInvalid()) {
2201 commit.insert(Loc, Entry.Text);
2202 } else if (Entry.Text.empty()) {
2203 commit.remove(Range);
2205 commit.replace(Range, Entry.Text);
2207 Editor.commit(commit);
2210 Rewriter rewriter(SM, LangOpts);
2211 RewritesReceiver Rec(rewriter);
2212 Editor.applyRewrites(Rec);
2214 const RewriteBuffer *Buf = rewriter.getRewriteBufferFor(FID);
2215 SmallString<512> NewText;
2216 llvm::raw_svector_ostream OS(NewText);
2220 SmallString<64> TempPath;
2222 if (fs::createTemporaryFile(path::filename(FE->getName()),
2223 path::extension(FE->getName()), FD,
2225 reportDiag("Could not create file: " + TempPath.str(), Diag);
2226 return std::string();
2229 llvm::raw_fd_ostream TmpOut(FD, /*shouldClose=*/true);
2230 TmpOut.write(NewText.data(), NewText.size());
2233 return TempPath.str();
2236 bool arcmt::getFileRemappingsFromFileList(
2237 std::vector<std::pair<std::string,std::string> > &remap,
2238 ArrayRef<StringRef> remapFiles,
2239 DiagnosticConsumer *DiagClient) {
2240 bool hasErrorOccurred = false;
2242 FileSystemOptions FSOpts;
2243 FileManager FileMgr(FSOpts);
2244 RemapFileParser Parser(FileMgr);
2246 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
2247 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
2248 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
2249 DiagClient, /*ShouldOwnClient=*/false));
2251 typedef llvm::DenseMap<const FileEntry *, std::vector<EditEntry> >
2253 FileEditEntriesTy FileEditEntries;
2255 llvm::DenseSet<EditEntry> EntriesSet;
2257 for (ArrayRef<StringRef>::iterator
2258 I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
2259 SmallVector<EditEntry, 16> Entries;
2260 if (Parser.parse(*I, Entries))
2263 for (SmallVectorImpl<EditEntry>::iterator
2264 EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) {
2265 EditEntry &Entry = *EI;
2268 std::pair<llvm::DenseSet<EditEntry>::iterator, bool>
2269 Insert = EntriesSet.insert(Entry);
2273 FileEditEntries[Entry.File].push_back(Entry);
2277 for (FileEditEntriesTy::iterator
2278 I = FileEditEntries.begin(), E = FileEditEntries.end(); I != E; ++I) {
2279 std::string TempFile = applyEditsToTemp(I->first, I->second,
2281 if (TempFile.empty()) {
2282 hasErrorOccurred = true;
2286 remap.emplace_back(I->first->getName(), TempFile);
2289 return hasErrorOccurred;