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 return !(isa<ArraySubscriptExpr>(Expr) || isa<CallExpr>(Expr) ||
218 isa<DeclRefExpr>(Expr) || isa<CXXNamedCastExpr>(Expr) ||
219 isa<CXXConstructExpr>(Expr) || isa<CXXThisExpr>(Expr) ||
220 isa<CXXTypeidExpr>(Expr) ||
221 isa<CXXUnresolvedConstructExpr>(Expr) ||
222 isa<ObjCMessageExpr>(Expr) || isa<ObjCPropertyRefExpr>(Expr) ||
223 isa<ObjCProtocolExpr>(Expr) || isa<MemberExpr>(Expr) ||
224 isa<ObjCIvarRefExpr>(Expr) || isa<ParenExpr>(FullExpr) ||
225 isa<ParenListExpr>(Expr) || isa<SizeOfPackExpr>(Expr));
228 /// \brief - Rewrite message expression for Objective-C setter and getters into
229 /// property-dot syntax.
230 bool rewriteToPropertyDotSyntax(const ObjCMessageExpr *Msg,
232 const NSAPI &NS, edit::Commit &commit,
233 const ParentMap *PMap) {
234 if (!Msg || Msg->isImplicit() ||
235 (Msg->getReceiverKind() != ObjCMessageExpr::Instance &&
236 Msg->getReceiverKind() != ObjCMessageExpr::SuperInstance))
238 if (const Expr *Receiver = Msg->getInstanceReceiver())
239 if (Receiver->getType()->isObjCBuiltinType())
242 const ObjCMethodDecl *Method = Msg->getMethodDecl();
245 if (!Method->isPropertyAccessor())
248 const ObjCPropertyDecl *Prop = Method->findPropertyDecl();
252 SourceRange MsgRange = Msg->getSourceRange();
253 bool ReceiverIsSuper =
254 (Msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
255 // for 'super' receiver is nullptr.
256 const Expr *receiver = Msg->getInstanceReceiver();
258 ReceiverIsSuper ? false : subscriptOperatorNeedsParens(receiver);
259 bool IsGetter = (Msg->getNumArgs() == 0);
261 // Find space location range between receiver expression and getter method.
262 SourceLocation BegLoc =
263 ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
264 BegLoc = PP.getLocForEndOfToken(BegLoc);
265 SourceLocation EndLoc = Msg->getSelectorLoc(0);
266 SourceRange SpaceRange(BegLoc, EndLoc);
267 std::string PropertyDotString;
268 // rewrite getter method expression into: receiver.property or
269 // (receiver).property
271 commit.insertBefore(receiver->getLocStart(), "(");
272 PropertyDotString = ").";
275 PropertyDotString = ".";
276 PropertyDotString += Prop->getName();
277 commit.replace(SpaceRange, PropertyDotString);
280 commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
281 commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
284 commit.insertWrap("(", receiver->getSourceRange(), ")");
285 std::string PropertyDotString = ".";
286 PropertyDotString += Prop->getName();
287 PropertyDotString += " =";
288 const Expr*const* Args = Msg->getArgs();
289 const Expr *RHS = Args[0];
292 SourceLocation BegLoc =
293 ReceiverIsSuper ? Msg->getSuperLoc() : receiver->getLocEnd();
294 BegLoc = PP.getLocForEndOfToken(BegLoc);
295 SourceLocation EndLoc = RHS->getLocStart();
296 EndLoc = EndLoc.getLocWithOffset(-1);
297 const char *colon = PP.getSourceManager().getCharacterData(EndLoc);
298 // Add a space after '=' if there is no space between RHS and '='
299 if (colon && colon[0] == ':')
300 PropertyDotString += " ";
301 SourceRange Range(BegLoc, EndLoc);
302 commit.replace(Range, PropertyDotString);
304 commit.replace(SourceRange(MsgRange.getBegin(), MsgRange.getBegin()), "");
305 commit.replace(SourceRange(MsgRange.getEnd(), MsgRange.getEnd()), "");
311 class ObjCMigrator : public RecursiveASTVisitor<ObjCMigrator> {
312 ObjCMigrateASTConsumer &Consumer;
316 ObjCMigrator(ObjCMigrateASTConsumer &consumer, ParentMap &PMap)
317 : Consumer(consumer), PMap(PMap) { }
319 bool shouldVisitTemplateInstantiations() const { return false; }
320 bool shouldWalkTypesOfTypeLocs() const { return false; }
322 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
323 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Literals) {
324 edit::Commit commit(*Consumer.Editor);
325 edit::rewriteToObjCLiteralSyntax(E, *Consumer.NSAPIObj, commit, &PMap);
326 Consumer.Editor->commit(commit);
329 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_Subscripting) {
330 edit::Commit commit(*Consumer.Editor);
331 edit::rewriteToObjCSubscriptSyntax(E, *Consumer.NSAPIObj, commit);
332 Consumer.Editor->commit(commit);
335 if (Consumer.ASTMigrateActions & FrontendOptions::ObjCMT_PropertyDotSyntax) {
336 edit::Commit commit(*Consumer.Editor);
337 rewriteToPropertyDotSyntax(E, Consumer.PP, *Consumer.NSAPIObj,
339 Consumer.Editor->commit(commit);
345 bool TraverseObjCMessageExpr(ObjCMessageExpr *E) {
346 // Do depth first; we want to rewrite the subexpressions first so that if
347 // we have to move expressions we will move them already rewritten.
348 for (Stmt *SubStmt : E->children())
349 if (!TraverseStmt(SubStmt))
352 return WalkUpFromObjCMessageExpr(E);
356 class BodyMigrator : public RecursiveASTVisitor<BodyMigrator> {
357 ObjCMigrateASTConsumer &Consumer;
358 std::unique_ptr<ParentMap> PMap;
361 BodyMigrator(ObjCMigrateASTConsumer &consumer) : Consumer(consumer) { }
363 bool shouldVisitTemplateInstantiations() const { return false; }
364 bool shouldWalkTypesOfTypeLocs() const { return false; }
366 bool TraverseStmt(Stmt *S) {
367 PMap.reset(new ParentMap(S));
368 ObjCMigrator(Consumer, *PMap).TraverseStmt(S);
374 void ObjCMigrateASTConsumer::migrateDecl(Decl *D) {
377 if (isa<ObjCMethodDecl>(D))
378 return; // Wait for the ObjC container declaration.
380 BodyMigrator(*this).TraverseDecl(D);
383 static void append_attr(std::string &PropertyString, const char *attr,
386 PropertyString += "(";
390 PropertyString += ", ";
391 PropertyString += attr;
395 void MigrateBlockOrFunctionPointerTypeVariable(std::string & PropertyString,
396 const std::string& TypeString,
398 const char *argPtr = TypeString.c_str();
403 PropertyString += *argPtr;
407 PropertyString += *argPtr;
412 PropertyString += (*argPtr);
414 PropertyString += name;
419 PropertyString += *argPtr;
426 static const char *PropertyMemoryAttribute(ASTContext &Context, QualType ArgType) {
427 Qualifiers::ObjCLifetime propertyLifetime = ArgType.getObjCLifetime();
428 bool RetainableObject = ArgType->isObjCRetainableType();
429 if (RetainableObject &&
430 (propertyLifetime == Qualifiers::OCL_Strong
431 || propertyLifetime == Qualifiers::OCL_None)) {
432 if (const ObjCObjectPointerType *ObjPtrTy =
433 ArgType->getAs<ObjCObjectPointerType>()) {
434 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
436 IDecl->lookupNestedProtocol(&Context.Idents.get("NSCopying")))
441 else if (ArgType->isBlockPointerType())
443 } else if (propertyLifetime == Qualifiers::OCL_Weak)
444 // TODO. More precise determination of 'weak' attribute requires
445 // looking into setter's implementation for backing weak ivar.
447 else if (RetainableObject)
448 return ArgType->isBlockPointerType() ? "copy" : "strong";
452 static void rewriteToObjCProperty(const ObjCMethodDecl *Getter,
453 const ObjCMethodDecl *Setter,
454 const NSAPI &NS, edit::Commit &commit,
455 unsigned LengthOfPrefix,
456 bool Atomic, bool UseNsIosOnlyMacro,
457 bool AvailabilityArgsMatch) {
458 ASTContext &Context = NS.getASTContext();
459 bool LParenAdded = false;
460 std::string PropertyString = "@property ";
461 if (UseNsIosOnlyMacro && NS.isMacroDefined("NS_NONATOMIC_IOSONLY")) {
462 PropertyString += "(NS_NONATOMIC_IOSONLY";
464 } else if (!Atomic) {
465 PropertyString += "(nonatomic";
469 std::string PropertyNameString = Getter->getNameAsString();
470 StringRef PropertyName(PropertyNameString);
471 if (LengthOfPrefix > 0) {
473 PropertyString += "(getter=";
477 PropertyString += ", getter=";
478 PropertyString += PropertyNameString;
480 // Property with no setter may be suggested as a 'readonly' property.
482 append_attr(PropertyString, "readonly", LParenAdded);
485 // Short circuit 'delegate' properties that contain the name "delegate" or
486 // "dataSource", or have exact name "target" to have 'assign' attribute.
487 if (PropertyName.equals("target") ||
488 (PropertyName.find("delegate") != StringRef::npos) ||
489 (PropertyName.find("dataSource") != StringRef::npos)) {
490 QualType QT = Getter->getReturnType();
491 if (!QT->isRealType())
492 append_attr(PropertyString, "assign", LParenAdded);
493 } else if (!Setter) {
494 QualType ResType = Context.getCanonicalType(Getter->getReturnType());
495 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ResType))
496 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
498 const ParmVarDecl *argDecl = *Setter->param_begin();
499 QualType ArgType = Context.getCanonicalType(argDecl->getType());
500 if (const char *MemoryManagementAttr = PropertyMemoryAttribute(Context, ArgType))
501 append_attr(PropertyString, MemoryManagementAttr, LParenAdded);
504 PropertyString += ')';
505 QualType RT = Getter->getReturnType();
506 if (!isa<TypedefType>(RT)) {
507 // strip off any ARC lifetime qualifier.
508 QualType CanResultTy = Context.getCanonicalType(RT);
509 if (CanResultTy.getQualifiers().hasObjCLifetime()) {
510 Qualifiers Qs = CanResultTy.getQualifiers();
511 Qs.removeObjCLifetime();
512 RT = Context.getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
515 PropertyString += " ";
516 PrintingPolicy SubPolicy(Context.getPrintingPolicy());
517 SubPolicy.SuppressStrongLifetime = true;
518 SubPolicy.SuppressLifetimeQualifiers = true;
519 std::string TypeString = RT.getAsString(SubPolicy);
520 if (LengthOfPrefix > 0) {
521 // property name must strip off "is" and lower case the first character
522 // after that; e.g. isContinuous will become continuous.
523 StringRef PropertyNameStringRef(PropertyNameString);
524 PropertyNameStringRef = PropertyNameStringRef.drop_front(LengthOfPrefix);
525 PropertyNameString = PropertyNameStringRef;
526 bool NoLowering = (isUppercase(PropertyNameString[0]) &&
527 PropertyNameString.size() > 1 &&
528 isUppercase(PropertyNameString[1]));
530 PropertyNameString[0] = toLowercase(PropertyNameString[0]);
532 if (RT->isBlockPointerType() || RT->isFunctionPointerType())
533 MigrateBlockOrFunctionPointerTypeVariable(PropertyString,
535 PropertyNameString.c_str());
537 char LastChar = TypeString[TypeString.size()-1];
538 PropertyString += TypeString;
540 PropertyString += ' ';
541 PropertyString += PropertyNameString;
543 SourceLocation StartGetterSelectorLoc = Getter->getSelectorStartLoc();
544 Selector GetterSelector = Getter->getSelector();
546 SourceLocation EndGetterSelectorLoc =
547 StartGetterSelectorLoc.getLocWithOffset(GetterSelector.getNameForSlot(0).size());
548 commit.replace(CharSourceRange::getCharRange(Getter->getLocStart(),
549 EndGetterSelectorLoc),
551 if (Setter && AvailabilityArgsMatch) {
552 SourceLocation EndLoc = Setter->getDeclaratorEndLoc();
553 // Get location past ';'
554 EndLoc = EndLoc.getLocWithOffset(1);
555 SourceLocation BeginOfSetterDclLoc = Setter->getLocStart();
556 // FIXME. This assumes that setter decl; is immediately preceded by eoln.
557 // It is trying to remove the setter method decl. line entirely.
558 BeginOfSetterDclLoc = BeginOfSetterDclLoc.getLocWithOffset(-1);
559 commit.remove(SourceRange(BeginOfSetterDclLoc, EndLoc));
563 static bool IsCategoryNameWithDeprecatedSuffix(ObjCContainerDecl *D) {
564 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D)) {
565 StringRef Name = CatDecl->getName();
566 return Name.endswith("Deprecated");
571 void ObjCMigrateASTConsumer::migrateObjCContainerDecl(ASTContext &Ctx,
572 ObjCContainerDecl *D) {
573 if (D->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(D))
576 for (auto *Method : D->methods()) {
577 if (Method->isDeprecated())
579 bool PropertyInferred = migrateProperty(Ctx, D, Method);
580 // If a property is inferred, do not attempt to attach NS_RETURNS_INNER_POINTER to
581 // the getter method as it ends up on the property itself which we don't want
582 // to do unless -objcmt-returns-innerpointer-property option is on.
583 if (!PropertyInferred ||
584 (ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
585 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
586 migrateNsReturnsInnerPointer(Ctx, Method);
588 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_ReturnsInnerPointerProperty))
591 for (auto *Prop : D->properties()) {
592 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
593 !Prop->isDeprecated())
594 migratePropertyNsReturnsInnerPointer(Ctx, Prop);
599 ClassImplementsAllMethodsAndProperties(ASTContext &Ctx,
600 const ObjCImplementationDecl *ImpDecl,
601 const ObjCInterfaceDecl *IDecl,
602 ObjCProtocolDecl *Protocol) {
603 // In auto-synthesis, protocol properties are not synthesized. So,
604 // a conforming protocol must have its required properties declared
605 // in class interface.
606 bool HasAtleastOneRequiredProperty = false;
607 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition())
608 for (const auto *Property : PDecl->properties()) {
609 if (Property->getPropertyImplementation() == ObjCPropertyDecl::Optional)
611 HasAtleastOneRequiredProperty = true;
612 DeclContext::lookup_result R = IDecl->lookup(Property->getDeclName());
614 // Relax the rule and look into class's implementation for a synthesize
615 // or dynamic declaration. Class is implementing a property coming from
616 // another protocol. This still makes the target protocol as conforming.
617 if (!ImpDecl->FindPropertyImplDecl(
618 Property->getDeclName().getAsIdentifierInfo()))
621 else if (ObjCPropertyDecl *ClassProperty = dyn_cast<ObjCPropertyDecl>(R[0])) {
622 if ((ClassProperty->getPropertyAttributes()
623 != Property->getPropertyAttributes()) ||
624 !Ctx.hasSameType(ClassProperty->getType(), Property->getType()))
631 // At this point, all required properties in this protocol conform to those
632 // declared in the class.
633 // Check that class implements the required methods of the protocol too.
634 bool HasAtleastOneRequiredMethod = false;
635 if (const ObjCProtocolDecl *PDecl = Protocol->getDefinition()) {
636 if (PDecl->meth_begin() == PDecl->meth_end())
637 return HasAtleastOneRequiredProperty;
638 for (const auto *MD : PDecl->methods()) {
639 if (MD->isImplicit())
641 if (MD->getImplementationControl() == ObjCMethodDecl::Optional)
643 DeclContext::lookup_result R = ImpDecl->lookup(MD->getDeclName());
647 HasAtleastOneRequiredMethod = true;
648 for (unsigned I = 0, N = R.size(); I != N; ++I)
649 if (ObjCMethodDecl *ImpMD = dyn_cast<ObjCMethodDecl>(R[0]))
650 if (Ctx.ObjCMethodsAreEqual(MD, ImpMD)) {
658 return HasAtleastOneRequiredProperty || HasAtleastOneRequiredMethod;
661 static bool rewriteToObjCInterfaceDecl(const ObjCInterfaceDecl *IDecl,
662 llvm::SmallVectorImpl<ObjCProtocolDecl*> &ConformingProtocols,
663 const NSAPI &NS, edit::Commit &commit) {
664 const ObjCList<ObjCProtocolDecl> &Protocols = IDecl->getReferencedProtocols();
665 std::string ClassString;
666 SourceLocation EndLoc =
667 IDecl->getSuperClass() ? IDecl->getSuperClassLoc() : IDecl->getLocation();
669 if (Protocols.empty()) {
671 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
672 ClassString += ConformingProtocols[i]->getNameAsString();
680 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
681 ClassString += ConformingProtocols[i]->getNameAsString();
685 ObjCInterfaceDecl::protocol_loc_iterator PL = IDecl->protocol_loc_end() - 1;
689 commit.insertAfterToken(EndLoc, ClassString);
693 static StringRef GetUnsignedName(StringRef NSIntegerName) {
694 StringRef UnsignedName = llvm::StringSwitch<StringRef>(NSIntegerName)
695 .Case("int8_t", "uint8_t")
696 .Case("int16_t", "uint16_t")
697 .Case("int32_t", "uint32_t")
698 .Case("NSInteger", "NSUInteger")
699 .Case("int64_t", "uint64_t")
700 .Default(NSIntegerName);
704 static bool rewriteToNSEnumDecl(const EnumDecl *EnumDcl,
705 const TypedefDecl *TypedefDcl,
706 const NSAPI &NS, edit::Commit &commit,
707 StringRef NSIntegerName,
709 std::string ClassString;
711 ClassString = "typedef NS_OPTIONS(";
712 ClassString += GetUnsignedName(NSIntegerName);
715 ClassString = "typedef NS_ENUM(";
716 ClassString += NSIntegerName;
720 ClassString += TypedefDcl->getIdentifier()->getName();
722 SourceRange R(EnumDcl->getLocStart(), EnumDcl->getLocStart());
723 commit.replace(R, ClassString);
724 SourceLocation EndOfEnumDclLoc = EnumDcl->getLocEnd();
725 EndOfEnumDclLoc = trans::findSemiAfterLocation(EndOfEnumDclLoc,
726 NS.getASTContext(), /*IsDecl*/true);
727 if (EndOfEnumDclLoc.isValid()) {
728 SourceRange EnumDclRange(EnumDcl->getLocStart(), EndOfEnumDclLoc);
729 commit.insertFromRange(TypedefDcl->getLocStart(), EnumDclRange);
734 SourceLocation EndTypedefDclLoc = TypedefDcl->getLocEnd();
735 EndTypedefDclLoc = trans::findSemiAfterLocation(EndTypedefDclLoc,
736 NS.getASTContext(), /*IsDecl*/true);
737 if (EndTypedefDclLoc.isValid()) {
738 SourceRange TDRange(TypedefDcl->getLocStart(), EndTypedefDclLoc);
739 commit.remove(TDRange);
744 EndOfEnumDclLoc = trans::findLocationAfterSemi(EnumDcl->getLocEnd(), NS.getASTContext(),
746 if (EndOfEnumDclLoc.isValid()) {
747 SourceLocation BeginOfEnumDclLoc = EnumDcl->getLocStart();
748 // FIXME. This assumes that enum decl; is immediately preceded by eoln.
749 // It is trying to remove the enum decl. lines entirely.
750 BeginOfEnumDclLoc = BeginOfEnumDclLoc.getLocWithOffset(-1);
751 commit.remove(SourceRange(BeginOfEnumDclLoc, EndOfEnumDclLoc));
757 static void rewriteToNSMacroDecl(ASTContext &Ctx,
758 const EnumDecl *EnumDcl,
759 const TypedefDecl *TypedefDcl,
760 const NSAPI &NS, edit::Commit &commit,
761 bool IsNSIntegerType) {
762 QualType DesignatedEnumType = EnumDcl->getIntegerType();
763 assert(!DesignatedEnumType.isNull()
764 && "rewriteToNSMacroDecl - underlying enum type is null");
766 PrintingPolicy Policy(Ctx.getPrintingPolicy());
767 std::string TypeString = DesignatedEnumType.getAsString(Policy);
768 std::string ClassString = IsNSIntegerType ? "NS_ENUM(" : "NS_OPTIONS(";
769 ClassString += TypeString;
772 ClassString += TypedefDcl->getIdentifier()->getName();
774 SourceLocation EndLoc;
775 if (EnumDcl->getIntegerTypeSourceInfo()) {
776 TypeSourceInfo *TSourceInfo = EnumDcl->getIntegerTypeSourceInfo();
777 TypeLoc TLoc = TSourceInfo->getTypeLoc();
778 EndLoc = TLoc.getLocEnd();
779 const char *lbrace = Ctx.getSourceManager().getCharacterData(EndLoc);
782 while (lbrace[count] != '{')
785 EndLoc = EndLoc.getLocWithOffset(count-1);
788 EndLoc = EnumDcl->getLocStart();
789 SourceRange R(EnumDcl->getLocStart(), EndLoc);
790 commit.replace(R, ClassString);
791 // This is to remove spaces between '}' and typedef name.
792 SourceLocation StartTypedefLoc = EnumDcl->getLocEnd();
793 StartTypedefLoc = StartTypedefLoc.getLocWithOffset(+1);
794 SourceLocation EndTypedefLoc = TypedefDcl->getLocEnd();
796 commit.remove(SourceRange(StartTypedefLoc, EndTypedefLoc));
799 static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx,
800 const EnumDecl *EnumDcl) {
801 bool PowerOfTwo = true;
802 bool AllHexdecimalEnumerator = true;
803 uint64_t MaxPowerOfTwoVal = 0;
804 for (auto Enumerator : EnumDcl->enumerators()) {
805 const Expr *InitExpr = Enumerator->getInitExpr();
808 AllHexdecimalEnumerator = false;
811 InitExpr = InitExpr->IgnoreParenCasts();
812 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr))
813 if (BO->isShiftOp() || BO->isBitwiseOp())
816 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue();
817 if (PowerOfTwo && EnumVal) {
818 if (!llvm::isPowerOf2_64(EnumVal))
820 else if (EnumVal > MaxPowerOfTwoVal)
821 MaxPowerOfTwoVal = EnumVal;
823 if (AllHexdecimalEnumerator && EnumVal) {
824 bool FoundHexdecimalEnumerator = false;
825 SourceLocation EndLoc = Enumerator->getLocEnd();
827 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true))
828 if (Tok.isLiteral() && Tok.getLength() > 2) {
829 if (const char *StringLit = Tok.getLiteralData())
830 FoundHexdecimalEnumerator =
831 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x'));
833 if (!FoundHexdecimalEnumerator)
834 AllHexdecimalEnumerator = false;
837 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2));
840 void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx,
841 const ObjCImplementationDecl *ImpDecl) {
842 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface();
843 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated())
845 // Find all implicit conforming protocols for this class
846 // and make them explicit.
847 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols;
848 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols);
849 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols;
851 for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls)
852 if (!ExplicitProtocols.count(ProtDecl))
853 PotentialImplicitProtocols.push_back(ProtDecl);
855 if (PotentialImplicitProtocols.empty())
858 // go through list of non-optional methods and properties in each protocol
859 // in the PotentialImplicitProtocols list. If class implements every one of the
860 // methods and properties, then this class conforms to this protocol.
861 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols;
862 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++)
863 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl,
864 PotentialImplicitProtocols[i]))
865 ConformingProtocols.push_back(PotentialImplicitProtocols[i]);
867 if (ConformingProtocols.empty())
870 // Further reduce number of conforming protocols. If protocol P1 is in the list
871 // protocol P2 (P2<P1>), No need to include P1.
872 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols;
873 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) {
875 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i];
876 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) {
877 ObjCProtocolDecl *PDecl = ConformingProtocols[i1];
878 if (PDecl == TargetPDecl)
880 if (PDecl->lookupProtocolNamed(
881 TargetPDecl->getDeclName().getAsIdentifierInfo())) {
887 MinimalConformingProtocols.push_back(TargetPDecl);
889 if (MinimalConformingProtocols.empty())
891 edit::Commit commit(*Editor);
892 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols,
894 Editor->commit(commit);
897 void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed(
898 const TypedefDecl *TypedefDcl) {
900 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
901 if (NSAPIObj->isObjCNSIntegerType(qt))
902 NSIntegerTypedefed = TypedefDcl;
903 else if (NSAPIObj->isObjCNSUIntegerType(qt))
904 NSUIntegerTypedefed = TypedefDcl;
907 bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx,
908 const EnumDecl *EnumDcl,
909 const TypedefDecl *TypedefDcl) {
910 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() ||
911 EnumDcl->isDeprecated())
914 if (NSIntegerTypedefed) {
915 TypedefDcl = NSIntegerTypedefed;
916 NSIntegerTypedefed = nullptr;
918 else if (NSUIntegerTypedefed) {
919 TypedefDcl = NSUIntegerTypedefed;
920 NSUIntegerTypedefed = nullptr;
924 FileID FileIdOfTypedefDcl =
925 PP.getSourceManager().getFileID(TypedefDcl->getLocation());
926 FileID FileIdOfEnumDcl =
927 PP.getSourceManager().getFileID(EnumDcl->getLocation());
928 if (FileIdOfTypedefDcl != FileIdOfEnumDcl)
931 if (TypedefDcl->isDeprecated())
934 QualType qt = TypedefDcl->getTypeSourceInfo()->getType();
935 StringRef NSIntegerName = NSAPIObj->GetNSIntegralKind(qt);
937 if (NSIntegerName.empty()) {
938 // Also check for typedef enum {...} TD;
939 if (const EnumType *EnumTy = qt->getAs<EnumType>()) {
940 if (EnumTy->getDecl() == EnumDcl) {
941 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
942 if (!InsertFoundation(Ctx, TypedefDcl->getLocStart()))
944 edit::Commit commit(*Editor);
945 rewriteToNSMacroDecl(Ctx, EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions);
946 Editor->commit(commit);
953 // We may still use NS_OPTIONS based on what we find in the enumertor list.
954 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl);
955 if (!InsertFoundation(Ctx, TypedefDcl->getLocStart()))
957 edit::Commit commit(*Editor);
958 bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj,
959 commit, NSIntegerName, NSOptions);
960 Editor->commit(commit);
964 static void ReplaceWithInstancetype(ASTContext &Ctx,
965 const ObjCMigrateASTConsumer &ASTC,
966 ObjCMethodDecl *OM) {
967 if (OM->getReturnType() == Ctx.getObjCInstanceType())
968 return; // already has instancetype.
971 std::string ClassString;
972 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
973 TypeLoc TL = TSInfo->getTypeLoc();
974 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
975 ClassString = "instancetype";
978 R = SourceRange(OM->getLocStart(), OM->getLocStart());
979 ClassString = OM->isInstanceMethod() ? '-' : '+';
980 ClassString += " (instancetype)";
982 edit::Commit commit(*ASTC.Editor);
983 commit.replace(R, ClassString);
984 ASTC.Editor->commit(commit);
987 static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC,
988 ObjCMethodDecl *OM) {
989 ObjCInterfaceDecl *IDecl = OM->getClassInterface();
991 std::string ClassString;
992 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) {
993 TypeLoc TL = TSInfo->getTypeLoc();
994 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); {
995 ClassString = IDecl->getName();
1000 R = SourceRange(OM->getLocStart(), OM->getLocStart());
1001 ClassString = "+ (";
1002 ClassString += IDecl->getName(); ClassString += "*)";
1004 edit::Commit commit(*ASTC.Editor);
1005 commit.replace(R, ClassString);
1006 ASTC.Editor->commit(commit);
1009 void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx,
1010 ObjCContainerDecl *CDecl,
1011 ObjCMethodDecl *OM) {
1012 ObjCInstanceTypeFamily OIT_Family =
1013 Selector::getInstTypeMethodFamily(OM->getSelector());
1015 std::string ClassName;
1016 switch (OIT_Family) {
1018 migrateFactoryMethod(Ctx, CDecl, OM);
1021 ClassName = "NSArray";
1023 case OIT_Dictionary:
1024 ClassName = "NSDictionary";
1027 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton);
1030 if (OM->getReturnType()->isObjCIdType())
1031 ReplaceWithInstancetype(Ctx, *this, OM);
1033 case OIT_ReturnsSelf:
1034 migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf);
1037 if (!OM->getReturnType()->isObjCIdType())
1040 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1042 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1043 IDecl = CatDecl->getClassInterface();
1044 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1045 IDecl = ImpDecl->getClassInterface();
1048 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) {
1049 migrateFactoryMethod(Ctx, CDecl, OM);
1052 ReplaceWithInstancetype(Ctx, *this, OM);
1055 static bool TypeIsInnerPointer(QualType T) {
1056 if (!T->isAnyPointerType())
1058 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() ||
1059 T->isBlockPointerType() || T->isFunctionPointerType() ||
1060 ento::coreFoundation::isCFObjectRef(T))
1062 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume
1063 // is not an innter pointer type.
1065 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr()))
1066 T = TD->getDecl()->getUnderlyingType();
1067 if (OrigT == T || !T->isPointerType())
1069 const PointerType* PT = T->getAs<PointerType>();
1070 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType();
1071 if (UPointeeT->isRecordType()) {
1072 const RecordType *RecordTy = UPointeeT->getAs<RecordType>();
1073 if (!RecordTy->getDecl()->isCompleteDefinition())
1079 /// \brief Check whether the two versions match.
1080 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) {
1084 /// AvailabilityAttrsMatch - This routine checks that if comparing two
1085 /// availability attributes, all their components match. It returns
1086 /// true, if not dealing with availability or when all components of
1087 /// availability attributes match. This routine is only called when
1088 /// the attributes are of the same kind.
1089 static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) {
1090 const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1);
1093 const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2);
1095 VersionTuple Introduced1 = AA1->getIntroduced();
1096 VersionTuple Deprecated1 = AA1->getDeprecated();
1097 VersionTuple Obsoleted1 = AA1->getObsoleted();
1098 bool IsUnavailable1 = AA1->getUnavailable();
1099 VersionTuple Introduced2 = AA2->getIntroduced();
1100 VersionTuple Deprecated2 = AA2->getDeprecated();
1101 VersionTuple Obsoleted2 = AA2->getObsoleted();
1102 bool IsUnavailable2 = AA2->getUnavailable();
1103 return (versionsMatch(Introduced1, Introduced2) &&
1104 versionsMatch(Deprecated1, Deprecated2) &&
1105 versionsMatch(Obsoleted1, Obsoleted2) &&
1106 IsUnavailable1 == IsUnavailable2);
1110 static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2,
1111 bool &AvailabilityArgsMatch) {
1112 // This list is very small, so this need not be optimized.
1113 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) {
1115 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) {
1116 // Matching attribute kind only. Except for Availabilty attributes,
1117 // we are not getting into details of the attributes. For all practical purposes
1118 // this is sufficient.
1119 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) {
1120 if (AvailabilityArgsMatch)
1121 AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]);
1132 /// AttributesMatch - This routine checks list of attributes for two
1133 /// decls. It returns false, if there is a mismatch in kind of
1134 /// attributes seen in the decls. It returns true if the two decls
1135 /// have list of same kind of attributes. Furthermore, when there
1136 /// are availability attributes in the two decls, it sets the
1137 /// AvailabilityArgsMatch to false if availability attributes have
1138 /// different versions, etc.
1139 static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2,
1140 bool &AvailabilityArgsMatch) {
1141 if (!Decl1->hasAttrs() || !Decl2->hasAttrs()) {
1142 AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs());
1145 AvailabilityArgsMatch = true;
1146 const AttrVec &Attrs1 = Decl1->getAttrs();
1147 const AttrVec &Attrs2 = Decl2->getAttrs();
1148 bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch);
1149 if (match && (Attrs2.size() > Attrs1.size()))
1150 return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch);
1154 static bool IsValidIdentifier(ASTContext &Ctx,
1156 if (!isIdentifierHead(Name[0]))
1158 std::string NameString = Name;
1159 NameString[0] = toLowercase(NameString[0]);
1160 IdentifierInfo *II = &Ctx.Idents.get(NameString);
1161 return II->getTokenID() == tok::identifier;
1164 bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx,
1165 ObjCContainerDecl *D,
1166 ObjCMethodDecl *Method) {
1167 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() ||
1168 Method->param_size() != 0)
1170 // Is this method candidate to be a getter?
1171 QualType GRT = Method->getReturnType();
1172 if (GRT->isVoidType())
1175 Selector GetterSelector = Method->getSelector();
1176 ObjCInstanceTypeFamily OIT_Family =
1177 Selector::getInstTypeMethodFamily(GetterSelector);
1179 if (OIT_Family != OIT_None)
1182 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0);
1183 Selector SetterSelector =
1184 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1185 PP.getSelectorTable(),
1187 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector);
1188 unsigned LengthOfPrefix = 0;
1189 if (!SetterMethod) {
1190 // try a different naming convention for getter: isXxxxx
1191 StringRef getterNameString = getterName->getName();
1192 bool IsPrefix = getterNameString.startswith("is");
1193 // Note that we don't want to change an isXXX method of retainable object
1194 // type to property (readonly or otherwise).
1195 if (IsPrefix && GRT->isObjCRetainableType())
1197 if (IsPrefix || getterNameString.startswith("get")) {
1198 LengthOfPrefix = (IsPrefix ? 2 : 3);
1199 const char *CGetterName = getterNameString.data() + LengthOfPrefix;
1200 // Make sure that first character after "is" or "get" prefix can
1201 // start an identifier.
1202 if (!IsValidIdentifier(Ctx, CGetterName))
1204 if (CGetterName[0] && isUppercase(CGetterName[0])) {
1205 getterName = &Ctx.Idents.get(CGetterName);
1207 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1208 PP.getSelectorTable(),
1210 SetterMethod = D->getInstanceMethod(SetterSelector);
1216 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0)
1218 bool AvailabilityArgsMatch;
1219 if (SetterMethod->isDeprecated() ||
1220 !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch))
1223 // Is this a valid setter, matching the target getter?
1224 QualType SRT = SetterMethod->getReturnType();
1225 if (!SRT->isVoidType())
1227 const ParmVarDecl *argDecl = *SetterMethod->param_begin();
1228 QualType ArgType = argDecl->getType();
1229 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT))
1231 edit::Commit commit(*Editor);
1232 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit,
1234 (ASTMigrateActions &
1235 FrontendOptions::ObjCMT_AtomicProperty) != 0,
1236 (ASTMigrateActions &
1237 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
1238 AvailabilityArgsMatch);
1239 Editor->commit(commit);
1242 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) {
1243 // Try a non-void method with no argument (and no setter or property of same name
1244 // as a 'readonly' property.
1245 edit::Commit commit(*Editor);
1246 rewriteToObjCProperty(Method, nullptr /*SetterMethod*/, *NSAPIObj, commit,
1248 (ASTMigrateActions &
1249 FrontendOptions::ObjCMT_AtomicProperty) != 0,
1250 (ASTMigrateActions &
1251 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0,
1252 /*AvailabilityArgsMatch*/false);
1253 Editor->commit(commit);
1259 void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx,
1260 ObjCMethodDecl *OM) {
1261 if (OM->isImplicit() ||
1262 !OM->isInstanceMethod() ||
1263 OM->hasAttr<ObjCReturnsInnerPointerAttr>())
1266 QualType RT = OM->getReturnType();
1267 if (!TypeIsInnerPointer(RT) ||
1268 !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
1271 edit::Commit commit(*Editor);
1272 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER");
1273 Editor->commit(commit);
1276 void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx,
1277 ObjCPropertyDecl *P) {
1278 QualType T = P->getType();
1280 if (!TypeIsInnerPointer(T) ||
1281 !NSAPIObj->isMacroDefined("NS_RETURNS_INNER_POINTER"))
1283 edit::Commit commit(*Editor);
1284 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER ");
1285 Editor->commit(commit);
1288 void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx,
1289 ObjCContainerDecl *CDecl) {
1290 if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl))
1293 // migrate methods which can have instancetype as their result type.
1294 for (auto *Method : CDecl->methods()) {
1295 if (Method->isDeprecated())
1297 migrateMethodInstanceType(Ctx, CDecl, Method);
1301 void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx,
1302 ObjCContainerDecl *CDecl,
1304 ObjCInstanceTypeFamily OIT_Family) {
1305 if (OM->isInstanceMethod() ||
1306 OM->getReturnType() == Ctx.getObjCInstanceType() ||
1307 !OM->getReturnType()->isObjCIdType())
1310 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class
1311 // NSYYYNamE with matching names be at least 3 characters long.
1312 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1314 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
1315 IDecl = CatDecl->getClassInterface();
1316 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl))
1317 IDecl = ImpDecl->getClassInterface();
1322 std::string StringClassName = IDecl->getName();
1323 StringRef LoweredClassName(StringClassName);
1324 std::string StringLoweredClassName = LoweredClassName.lower();
1325 LoweredClassName = StringLoweredClassName;
1327 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0);
1328 // Handle method with no name at its first selector slot; e.g. + (id):(int)x.
1332 std::string MethodName = MethodIdName->getName();
1333 if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) {
1334 StringRef STRefMethodName(MethodName);
1336 if (STRefMethodName.startswith("standard"))
1337 len = strlen("standard");
1338 else if (STRefMethodName.startswith("shared"))
1339 len = strlen("shared");
1340 else if (STRefMethodName.startswith("default"))
1341 len = strlen("default");
1344 MethodName = STRefMethodName.substr(len);
1346 std::string MethodNameSubStr = MethodName.substr(0, 3);
1347 StringRef MethodNamePrefix(MethodNameSubStr);
1348 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower();
1349 MethodNamePrefix = StringLoweredMethodNamePrefix;
1350 size_t Ix = LoweredClassName.rfind(MethodNamePrefix);
1351 if (Ix == StringRef::npos)
1353 std::string ClassNamePostfix = LoweredClassName.substr(Ix);
1354 StringRef LoweredMethodName(MethodName);
1355 std::string StringLoweredMethodName = LoweredMethodName.lower();
1356 LoweredMethodName = StringLoweredMethodName;
1357 if (!LoweredMethodName.startswith(ClassNamePostfix))
1359 if (OIT_Family == OIT_ReturnsSelf)
1360 ReplaceWithClasstype(*this, OM);
1362 ReplaceWithInstancetype(Ctx, *this, OM);
1365 static bool IsVoidStarType(QualType Ty) {
1366 if (!Ty->isPointerType())
1369 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr()))
1370 Ty = TD->getDecl()->getUnderlyingType();
1372 // Is the type void*?
1373 const PointerType* PT = Ty->getAs<PointerType>();
1374 if (PT->getPointeeType().getUnqualifiedType()->isVoidType())
1376 return IsVoidStarType(PT->getPointeeType());
1379 /// AuditedType - This routine audits the type AT and returns false if it is one of known
1380 /// CF object types or of the "void *" variety. It returns true if we don't care about the type
1381 /// such as a non-pointer or pointers which have no ownership issues (such as "int *").
1382 static bool AuditedType (QualType AT) {
1383 if (!AT->isAnyPointerType() && !AT->isBlockPointerType())
1385 // FIXME. There isn't much we can say about CF pointer type; or is there?
1386 if (ento::coreFoundation::isCFObjectRef(AT) ||
1387 IsVoidStarType(AT) ||
1388 // If an ObjC object is type, assuming that it is not a CF function and
1389 // that it is an un-audited function.
1390 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType())
1392 // All other pointers are assumed audited as harmless.
1396 void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) {
1397 if (CFFunctionIBCandidates.empty())
1399 if (!NSAPIObj->isMacroDefined("CF_IMPLICIT_BRIDGING_ENABLED")) {
1400 CFFunctionIBCandidates.clear();
1404 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED
1405 const Decl *FirstFD = CFFunctionIBCandidates[0];
1406 const Decl *LastFD =
1407 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1];
1408 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n";
1409 edit::Commit commit(*Editor);
1410 commit.insertBefore(FirstFD->getLocStart(), PragmaString);
1411 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n";
1412 SourceLocation EndLoc = LastFD->getLocEnd();
1413 // get location just past end of function location.
1414 EndLoc = PP.getLocForEndOfToken(EndLoc);
1415 if (isa<FunctionDecl>(LastFD)) {
1416 // For Methods, EndLoc points to the ending semcolon. So,
1417 // not of these extra work is needed.
1419 // get locaiton of token that comes after end of function.
1420 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true);
1422 EndLoc = Tok.getLocation();
1424 commit.insertAfterToken(EndLoc, PragmaString);
1425 Editor->commit(commit);
1427 CFFunctionIBCandidates.clear();
1430 void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) {
1431 if (Decl->isDeprecated())
1434 if (Decl->hasAttr<CFAuditedTransferAttr>()) {
1435 assert(CFFunctionIBCandidates.empty() &&
1436 "Cannot have audited functions/methods inside user "
1437 "provided CF_IMPLICIT_BRIDGING_ENABLE");
1441 // Finction must be annotated first.
1442 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) {
1443 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl);
1444 if (AuditKind == CF_BRIDGING_ENABLE) {
1445 CFFunctionIBCandidates.push_back(Decl);
1446 if (FileId.isInvalid())
1447 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
1449 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) {
1450 if (!CFFunctionIBCandidates.empty()) {
1451 CFFunctionIBCandidates.push_back(Decl);
1452 if (FileId.isInvalid())
1453 FileId = PP.getSourceManager().getFileID(Decl->getLocation());
1457 AnnotateImplicitBridging(Ctx);
1460 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl));
1461 AnnotateImplicitBridging(Ctx);
1465 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1466 const CallEffects &CE,
1467 const FunctionDecl *FuncDecl,
1468 bool ResultAnnotated) {
1469 // Annotate function.
1470 if (!ResultAnnotated) {
1471 RetEffect Ret = CE.getReturnValue();
1472 const char *AnnotationString = nullptr;
1473 if (Ret.getObjKind() == RetEffect::CF) {
1474 if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
1475 AnnotationString = " CF_RETURNS_RETAINED";
1476 else if (Ret.notOwned() &&
1477 NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
1478 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1480 else if (Ret.getObjKind() == RetEffect::ObjC) {
1481 if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
1482 AnnotationString = " NS_RETURNS_RETAINED";
1485 if (AnnotationString) {
1486 edit::Commit commit(*Editor);
1487 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString);
1488 Editor->commit(commit);
1491 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1493 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1494 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1495 const ParmVarDecl *pd = *pi;
1496 ArgEffect AE = AEArgs[i];
1497 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
1498 NSAPIObj->isMacroDefined("CF_CONSUMED")) {
1499 edit::Commit commit(*Editor);
1500 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1501 Editor->commit(commit);
1503 else if (AE == DecRefMsg && !pd->hasAttr<NSConsumedAttr>() &&
1504 NSAPIObj->isMacroDefined("NS_CONSUMED")) {
1505 edit::Commit commit(*Editor);
1506 commit.insertBefore(pd->getLocation(), "NS_CONSUMED ");
1507 Editor->commit(commit);
1513 ObjCMigrateASTConsumer::CF_BRIDGING_KIND
1514 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation(
1516 const FunctionDecl *FuncDecl) {
1517 if (FuncDecl->hasBody())
1518 return CF_BRIDGING_NONE;
1520 CallEffects CE = CallEffects::getEffect(FuncDecl);
1521 bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() ||
1522 FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1523 FuncDecl->hasAttr<NSReturnsRetainedAttr>() ||
1524 FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1525 FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>());
1527 // Trivial case of when function is annotated and has no argument.
1528 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0)
1529 return CF_BRIDGING_NONE;
1531 bool ReturnCFAudited = false;
1532 if (!FuncIsReturnAnnotated) {
1533 RetEffect Ret = CE.getReturnValue();
1534 if (Ret.getObjKind() == RetEffect::CF &&
1535 (Ret.isOwned() || Ret.notOwned()))
1536 ReturnCFAudited = true;
1537 else if (!AuditedType(FuncDecl->getReturnType()))
1538 return CF_BRIDGING_NONE;
1541 // At this point result type is audited for potential inclusion.
1542 // Now, how about argument types.
1543 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1545 bool ArgCFAudited = false;
1546 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(),
1547 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) {
1548 const ParmVarDecl *pd = *pi;
1549 ArgEffect AE = AEArgs[i];
1550 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) {
1551 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>())
1552 ArgCFAudited = true;
1553 else if (AE == IncRef)
1554 ArgCFAudited = true;
1557 QualType AT = pd->getType();
1558 if (!AuditedType(AT)) {
1559 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated);
1560 return CF_BRIDGING_NONE;
1564 if (ReturnCFAudited || ArgCFAudited)
1565 return CF_BRIDGING_ENABLE;
1567 return CF_BRIDGING_MAY_INCLUDE;
1570 void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx,
1571 ObjCContainerDecl *CDecl) {
1572 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated())
1575 // migrate methods which can have instancetype as their result type.
1576 for (const auto *Method : CDecl->methods())
1577 migrateCFAnnotation(Ctx, Method);
1580 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx,
1581 const CallEffects &CE,
1582 const ObjCMethodDecl *MethodDecl,
1583 bool ResultAnnotated) {
1584 // Annotate function.
1585 if (!ResultAnnotated) {
1586 RetEffect Ret = CE.getReturnValue();
1587 const char *AnnotationString = nullptr;
1588 if (Ret.getObjKind() == RetEffect::CF) {
1589 if (Ret.isOwned() && NSAPIObj->isMacroDefined("CF_RETURNS_RETAINED"))
1590 AnnotationString = " CF_RETURNS_RETAINED";
1591 else if (Ret.notOwned() &&
1592 NSAPIObj->isMacroDefined("CF_RETURNS_NOT_RETAINED"))
1593 AnnotationString = " CF_RETURNS_NOT_RETAINED";
1595 else if (Ret.getObjKind() == RetEffect::ObjC) {
1596 ObjCMethodFamily OMF = MethodDecl->getMethodFamily();
1598 case clang::OMF_alloc:
1599 case clang::OMF_new:
1600 case clang::OMF_copy:
1601 case clang::OMF_init:
1602 case clang::OMF_mutableCopy:
1606 if (Ret.isOwned() && NSAPIObj->isMacroDefined("NS_RETURNS_RETAINED"))
1607 AnnotationString = " NS_RETURNS_RETAINED";
1612 if (AnnotationString) {
1613 edit::Commit commit(*Editor);
1614 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString);
1615 Editor->commit(commit);
1618 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1620 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1621 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1622 const ParmVarDecl *pd = *pi;
1623 ArgEffect AE = AEArgs[i];
1624 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() &&
1625 NSAPIObj->isMacroDefined("CF_CONSUMED")) {
1626 edit::Commit commit(*Editor);
1627 commit.insertBefore(pd->getLocation(), "CF_CONSUMED ");
1628 Editor->commit(commit);
1633 void ObjCMigrateASTConsumer::migrateAddMethodAnnotation(
1635 const ObjCMethodDecl *MethodDecl) {
1636 if (MethodDecl->hasBody() || MethodDecl->isImplicit())
1639 CallEffects CE = CallEffects::getEffect(MethodDecl);
1640 bool MethodIsReturnAnnotated = (MethodDecl->hasAttr<CFReturnsRetainedAttr>() ||
1641 MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() ||
1642 MethodDecl->hasAttr<NSReturnsRetainedAttr>() ||
1643 MethodDecl->hasAttr<NSReturnsNotRetainedAttr>() ||
1644 MethodDecl->hasAttr<NSReturnsAutoreleasedAttr>());
1646 if (CE.getReceiver() == DecRefMsg &&
1647 !MethodDecl->hasAttr<NSConsumesSelfAttr>() &&
1648 MethodDecl->getMethodFamily() != OMF_init &&
1649 MethodDecl->getMethodFamily() != OMF_release &&
1650 NSAPIObj->isMacroDefined("NS_CONSUMES_SELF")) {
1651 edit::Commit commit(*Editor);
1652 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF");
1653 Editor->commit(commit);
1656 // Trivial case of when function is annotated and has no argument.
1657 if (MethodIsReturnAnnotated &&
1658 (MethodDecl->param_begin() == MethodDecl->param_end()))
1661 if (!MethodIsReturnAnnotated) {
1662 RetEffect Ret = CE.getReturnValue();
1663 if ((Ret.getObjKind() == RetEffect::CF ||
1664 Ret.getObjKind() == RetEffect::ObjC) &&
1665 (Ret.isOwned() || Ret.notOwned())) {
1666 AddCFAnnotations(Ctx, CE, MethodDecl, false);
1668 } else if (!AuditedType(MethodDecl->getReturnType()))
1672 // At this point result type is either annotated or audited.
1673 // Now, how about argument types.
1674 ArrayRef<ArgEffect> AEArgs = CE.getArgs();
1676 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(),
1677 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) {
1678 const ParmVarDecl *pd = *pi;
1679 ArgEffect AE = AEArgs[i];
1680 if ((AE == DecRef && !pd->hasAttr<CFConsumedAttr>()) || AE == IncRef ||
1681 !AuditedType(pd->getType())) {
1682 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated);
1690 class SuperInitChecker : public RecursiveASTVisitor<SuperInitChecker> {
1692 bool shouldVisitTemplateInstantiations() const { return false; }
1693 bool shouldWalkTypesOfTypeLocs() const { return false; }
1695 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
1696 if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
1697 if (E->getMethodFamily() == OMF_init)
1703 } // anonymous namespace
1705 static bool hasSuperInitCall(const ObjCMethodDecl *MD) {
1706 return !SuperInitChecker().TraverseStmt(MD->getBody());
1709 void ObjCMigrateASTConsumer::inferDesignatedInitializers(
1711 const ObjCImplementationDecl *ImplD) {
1713 const ObjCInterfaceDecl *IFace = ImplD->getClassInterface();
1714 if (!IFace || IFace->hasDesignatedInitializers())
1716 if (!NSAPIObj->isMacroDefined("NS_DESIGNATED_INITIALIZER"))
1719 for (const auto *MD : ImplD->instance_methods()) {
1720 if (MD->isDeprecated() ||
1721 MD->getMethodFamily() != OMF_init ||
1722 MD->isDesignatedInitializerForTheInterface())
1724 const ObjCMethodDecl *IFaceM = IFace->getMethod(MD->getSelector(),
1725 /*isInstance=*/true);
1728 if (hasSuperInitCall(MD)) {
1729 edit::Commit commit(*Editor);
1730 commit.insert(IFaceM->getLocEnd(), " NS_DESIGNATED_INITIALIZER");
1731 Editor->commit(commit);
1736 bool ObjCMigrateASTConsumer::InsertFoundation(ASTContext &Ctx,
1737 SourceLocation Loc) {
1738 if (FoundationIncluded)
1740 if (Loc.isInvalid())
1742 edit::Commit commit(*Editor);
1743 if (Ctx.getLangOpts().Modules)
1744 commit.insert(Loc, "#ifndef NS_ENUM\n@import Foundation;\n#endif\n");
1746 commit.insert(Loc, "#ifndef NS_ENUM\n#import <Foundation/Foundation.h>\n#endif\n");
1747 Editor->commit(commit);
1748 FoundationIncluded = true;
1754 class RewritesReceiver : public edit::EditsReceiver {
1758 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { }
1760 void insert(SourceLocation loc, StringRef text) override {
1761 Rewrite.InsertText(loc, text);
1763 void replace(CharSourceRange range, StringRef text) override {
1764 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text);
1768 class JSONEditWriter : public edit::EditsReceiver {
1769 SourceManager &SourceMgr;
1770 llvm::raw_ostream &OS;
1773 JSONEditWriter(SourceManager &SM, llvm::raw_ostream &OS)
1774 : SourceMgr(SM), OS(OS) {
1777 ~JSONEditWriter() override { OS << "]\n"; }
1780 struct EntryWriter {
1781 SourceManager &SourceMgr;
1782 llvm::raw_ostream &OS;
1784 EntryWriter(SourceManager &SM, llvm::raw_ostream &OS)
1785 : SourceMgr(SM), OS(OS) {
1792 void writeLoc(SourceLocation Loc) {
1795 std::tie(FID, Offset) = SourceMgr.getDecomposedLoc(Loc);
1796 assert(FID.isValid());
1797 SmallString<200> Path =
1798 StringRef(SourceMgr.getFileEntryForID(FID)->getName());
1799 llvm::sys::fs::make_absolute(Path);
1800 OS << " \"file\": \"";
1801 OS.write_escaped(Path.str()) << "\",\n";
1802 OS << " \"offset\": " << Offset << ",\n";
1805 void writeRemove(CharSourceRange Range) {
1806 assert(Range.isCharRange());
1807 std::pair<FileID, unsigned> Begin =
1808 SourceMgr.getDecomposedLoc(Range.getBegin());
1809 std::pair<FileID, unsigned> End =
1810 SourceMgr.getDecomposedLoc(Range.getEnd());
1811 assert(Begin.first == End.first);
1812 assert(Begin.second <= End.second);
1813 unsigned Length = End.second - Begin.second;
1815 OS << " \"remove\": " << Length << ",\n";
1818 void writeText(StringRef Text) {
1819 OS << " \"text\": \"";
1820 OS.write_escaped(Text) << "\",\n";
1824 void insert(SourceLocation Loc, StringRef Text) override {
1825 EntryWriter Writer(SourceMgr, OS);
1826 Writer.writeLoc(Loc);
1827 Writer.writeText(Text);
1830 void replace(CharSourceRange Range, StringRef Text) override {
1831 EntryWriter Writer(SourceMgr, OS);
1832 Writer.writeLoc(Range.getBegin());
1833 Writer.writeRemove(Range);
1834 Writer.writeText(Text);
1837 void remove(CharSourceRange Range) override {
1838 EntryWriter Writer(SourceMgr, OS);
1839 Writer.writeLoc(Range.getBegin());
1840 Writer.writeRemove(Range);
1846 void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) {
1848 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl();
1849 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) {
1850 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end();
1852 FileID FID = PP.getSourceManager().getFileID((*D)->getLocation());
1854 if (FileId.isValid() && FileId != FID) {
1855 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1856 AnnotateImplicitBridging(Ctx);
1859 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D))
1860 if (canModify(CDecl))
1861 migrateObjCContainerDecl(Ctx, CDecl);
1862 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) {
1863 if (canModify(CatDecl))
1864 migrateObjCContainerDecl(Ctx, CatDecl);
1866 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D)) {
1867 ObjCProtocolDecls.insert(PDecl->getCanonicalDecl());
1868 if (canModify(PDecl))
1869 migrateObjCContainerDecl(Ctx, PDecl);
1871 else if (const ObjCImplementationDecl *ImpDecl =
1872 dyn_cast<ObjCImplementationDecl>(*D)) {
1873 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) &&
1875 migrateProtocolConformance(Ctx, ImpDecl);
1877 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) {
1878 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1882 DeclContext::decl_iterator N = D;
1884 const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N);
1885 if (migrateNSEnumDecl(Ctx, ED, TD) && TD)
1889 migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */nullptr);
1891 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) {
1892 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros))
1896 DeclContext::decl_iterator N = D;
1899 if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) {
1901 if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) {
1902 // prefer typedef-follows-enum to enum-follows-typedef pattern.
1903 if (migrateNSEnumDecl(Ctx, ED, TDF)) {
1905 CacheObjCNSIntegerTypedefed(TD);
1909 if (migrateNSEnumDecl(Ctx, ED, TD)) {
1914 CacheObjCNSIntegerTypedefed(TD);
1916 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) {
1917 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1919 migrateCFAnnotation(Ctx, FD);
1922 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) {
1923 bool CanModify = canModify(CDecl);
1924 // migrate methods which can have instancetype as their result type.
1925 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) &&
1927 migrateAllMethodInstaceType(Ctx, CDecl);
1928 // annotate methods with CF annotations.
1929 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) &&
1931 migrateARCSafeAnnotation(Ctx, CDecl);
1934 if (const ObjCImplementationDecl *
1935 ImplD = dyn_cast<ObjCImplementationDecl>(*D)) {
1936 if ((ASTMigrateActions & FrontendOptions::ObjCMT_DesignatedInitializer) &&
1938 inferDesignatedInitializers(Ctx, ImplD);
1941 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation)
1942 AnnotateImplicitBridging(Ctx);
1947 llvm::raw_fd_ostream OS(MigrateDir, EC, llvm::sys::fs::F_None);
1949 DiagnosticsEngine &Diags = Ctx.getDiagnostics();
1950 Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
1955 JSONEditWriter Writer(Ctx.getSourceManager(), OS);
1956 Editor->applyRewrites(Writer);
1960 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts());
1961 RewritesReceiver Rec(rewriter);
1962 Editor->applyRewrites(Rec);
1964 for (Rewriter::buffer_iterator
1965 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) {
1966 FileID FID = I->first;
1967 RewriteBuffer &buf = I->second;
1968 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID);
1970 SmallString<512> newText;
1971 llvm::raw_svector_ostream vecOS(newText);
1973 std::unique_ptr<llvm::MemoryBuffer> memBuf(
1974 llvm::MemoryBuffer::getMemBufferCopy(
1975 StringRef(newText.data(), newText.size()), file->getName()));
1976 SmallString<64> filePath(file->getName());
1977 FileMgr.FixupRelativePath(filePath);
1978 Remapper.remap(filePath.str(), std::move(memBuf));
1982 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics());
1984 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics());
1988 bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) {
1989 CI.getDiagnostics().setIgnoreAllWarnings(true);
1993 static std::vector<std::string> getWhiteListFilenames(StringRef DirPath) {
1994 using namespace llvm::sys::fs;
1995 using namespace llvm::sys::path;
1997 std::vector<std::string> Filenames;
1998 if (DirPath.empty() || !is_directory(DirPath))
2002 directory_iterator DI = directory_iterator(DirPath, EC);
2003 directory_iterator DE;
2004 for (; !EC && DI != DE; DI = DI.increment(EC)) {
2005 if (is_regular_file(DI->path()))
2006 Filenames.push_back(filename(DI->path()));
2012 std::unique_ptr<ASTConsumer>
2013 MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
2014 PPConditionalDirectiveRecord *
2015 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager());
2016 unsigned ObjCMTAction = CI.getFrontendOpts().ObjCMTAction;
2017 unsigned ObjCMTOpts = ObjCMTAction;
2018 // These are companion flags, they do not enable transformations.
2019 ObjCMTOpts &= ~(FrontendOptions::ObjCMT_AtomicProperty |
2020 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty);
2021 if (ObjCMTOpts == FrontendOptions::ObjCMT_None) {
2022 // If no specific option was given, enable literals+subscripting transforms
2024 ObjCMTAction |= FrontendOptions::ObjCMT_Literals |
2025 FrontendOptions::ObjCMT_Subscripting;
2027 CI.getPreprocessor().addPPCallbacks(std::unique_ptr<PPCallbacks>(PPRec));
2028 std::vector<std::string> WhiteList =
2029 getWhiteListFilenames(CI.getFrontendOpts().ObjCMTWhiteListPath);
2030 return llvm::make_unique<ObjCMigrateASTConsumer>(
2031 CI.getFrontendOpts().OutputFile, ObjCMTAction, Remapper,
2032 CI.getFileManager(), PPRec, CI.getPreprocessor(),
2033 /*isOutputFile=*/true, WhiteList);
2038 const FileEntry *File;
2043 EditEntry() : File(), Offset(), RemoveLen() {}
2048 template<> struct DenseMapInfo<EditEntry> {
2049 static inline EditEntry getEmptyKey() {
2051 Entry.Offset = unsigned(-1);
2054 static inline EditEntry getTombstoneKey() {
2056 Entry.Offset = unsigned(-2);
2059 static unsigned getHashValue(const EditEntry& Val) {
2060 llvm::FoldingSetNodeID ID;
2061 ID.AddPointer(Val.File);
2062 ID.AddInteger(Val.Offset);
2063 ID.AddInteger(Val.RemoveLen);
2064 ID.AddString(Val.Text);
2065 return ID.ComputeHash();
2067 static bool isEqual(const EditEntry &LHS, const EditEntry &RHS) {
2068 return LHS.File == RHS.File &&
2069 LHS.Offset == RHS.Offset &&
2070 LHS.RemoveLen == RHS.RemoveLen &&
2071 LHS.Text == RHS.Text;
2077 class RemapFileParser {
2078 FileManager &FileMgr;
2081 RemapFileParser(FileManager &FileMgr) : FileMgr(FileMgr) { }
2083 bool parse(StringRef File, SmallVectorImpl<EditEntry> &Entries) {
2084 using namespace llvm::yaml;
2086 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
2087 llvm::MemoryBuffer::getFile(File);
2092 Stream YAMLStream(FileBufOrErr.get()->getMemBufferRef(), SM);
2093 document_iterator I = YAMLStream.begin();
2094 if (I == YAMLStream.end())
2096 Node *Root = I->getRoot();
2100 SequenceNode *SeqNode = dyn_cast<SequenceNode>(Root);
2104 for (SequenceNode::iterator
2105 AI = SeqNode->begin(), AE = SeqNode->end(); AI != AE; ++AI) {
2106 MappingNode *MapNode = dyn_cast<MappingNode>(&*AI);
2109 parseEdit(MapNode, Entries);
2116 void parseEdit(llvm::yaml::MappingNode *Node,
2117 SmallVectorImpl<EditEntry> &Entries) {
2118 using namespace llvm::yaml;
2120 bool Ignore = false;
2122 for (MappingNode::iterator
2123 KVI = Node->begin(), KVE = Node->end(); KVI != KVE; ++KVI) {
2124 ScalarNode *KeyString = dyn_cast<ScalarNode>((*KVI).getKey());
2127 SmallString<10> KeyStorage;
2128 StringRef Key = KeyString->getValue(KeyStorage);
2130 ScalarNode *ValueString = dyn_cast<ScalarNode>((*KVI).getValue());
2133 SmallString<64> ValueStorage;
2134 StringRef Val = ValueString->getValue(ValueStorage);
2136 if (Key == "file") {
2137 const FileEntry *FE = FileMgr.getFile(Val);
2141 } else if (Key == "offset") {
2142 if (Val.getAsInteger(10, Entry.Offset))
2144 } else if (Key == "remove") {
2145 if (Val.getAsInteger(10, Entry.RemoveLen))
2147 } else if (Key == "text") {
2153 Entries.push_back(Entry);
2158 static bool reportDiag(const Twine &Err, DiagnosticsEngine &Diag) {
2159 Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0"))
2164 static std::string applyEditsToTemp(const FileEntry *FE,
2165 ArrayRef<EditEntry> Edits,
2166 FileManager &FileMgr,
2167 DiagnosticsEngine &Diag) {
2168 using namespace llvm::sys;
2170 SourceManager SM(Diag, FileMgr);
2171 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);
2172 LangOptions LangOpts;
2173 edit::EditedSource Editor(SM, LangOpts);
2174 for (ArrayRef<EditEntry>::iterator
2175 I = Edits.begin(), E = Edits.end(); I != E; ++I) {
2176 const EditEntry &Entry = *I;
2177 assert(Entry.File == FE);
2178 SourceLocation Loc =
2179 SM.getLocForStartOfFile(FID).getLocWithOffset(Entry.Offset);
2180 CharSourceRange Range;
2181 if (Entry.RemoveLen != 0) {
2182 Range = CharSourceRange::getCharRange(Loc,
2183 Loc.getLocWithOffset(Entry.RemoveLen));
2186 edit::Commit commit(Editor);
2187 if (Range.isInvalid()) {
2188 commit.insert(Loc, Entry.Text);
2189 } else if (Entry.Text.empty()) {
2190 commit.remove(Range);
2192 commit.replace(Range, Entry.Text);
2194 Editor.commit(commit);
2197 Rewriter rewriter(SM, LangOpts);
2198 RewritesReceiver Rec(rewriter);
2199 Editor.applyRewrites(Rec);
2201 const RewriteBuffer *Buf = rewriter.getRewriteBufferFor(FID);
2202 SmallString<512> NewText;
2203 llvm::raw_svector_ostream OS(NewText);
2206 SmallString<64> TempPath;
2208 if (fs::createTemporaryFile(path::filename(FE->getName()),
2209 path::extension(FE->getName()).drop_front(), FD,
2211 reportDiag("Could not create file: " + TempPath.str(), Diag);
2212 return std::string();
2215 llvm::raw_fd_ostream TmpOut(FD, /*shouldClose=*/true);
2216 TmpOut.write(NewText.data(), NewText.size());
2219 return TempPath.str();
2222 bool arcmt::getFileRemappingsFromFileList(
2223 std::vector<std::pair<std::string,std::string> > &remap,
2224 ArrayRef<StringRef> remapFiles,
2225 DiagnosticConsumer *DiagClient) {
2226 bool hasErrorOccurred = false;
2228 FileSystemOptions FSOpts;
2229 FileManager FileMgr(FSOpts);
2230 RemapFileParser Parser(FileMgr);
2232 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs());
2233 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
2234 new DiagnosticsEngine(DiagID, new DiagnosticOptions,
2235 DiagClient, /*ShouldOwnClient=*/false));
2237 typedef llvm::DenseMap<const FileEntry *, std::vector<EditEntry> >
2239 FileEditEntriesTy FileEditEntries;
2241 llvm::DenseSet<EditEntry> EntriesSet;
2243 for (ArrayRef<StringRef>::iterator
2244 I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) {
2245 SmallVector<EditEntry, 16> Entries;
2246 if (Parser.parse(*I, Entries))
2249 for (SmallVectorImpl<EditEntry>::iterator
2250 EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) {
2251 EditEntry &Entry = *EI;
2254 std::pair<llvm::DenseSet<EditEntry>::iterator, bool>
2255 Insert = EntriesSet.insert(Entry);
2259 FileEditEntries[Entry.File].push_back(Entry);
2263 for (FileEditEntriesTy::iterator
2264 I = FileEditEntries.begin(), E = FileEditEntries.end(); I != E; ++I) {
2265 std::string TempFile = applyEditsToTemp(I->first, I->second,
2267 if (TempFile.empty()) {
2268 hasErrorOccurred = true;
2272 remap.emplace_back(I->first->getName(), TempFile);
2275 return hasErrorOccurred;