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