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 CompInst->getPreprocessor().addPPCallbacks(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 SourceLocation TypedefLoc = TypedefDcl->getLocEnd(); 648 commit.remove(SourceRange(TypedefLoc, TypedefLoc)); 649 } 650 651 static bool UseNSOptionsMacro(Preprocessor &PP, ASTContext &Ctx, 652 const EnumDecl *EnumDcl) { 653 bool PowerOfTwo = true; 654 bool AllHexdecimalEnumerator = true; 655 uint64_t MaxPowerOfTwoVal = 0; 656 for (auto Enumerator : EnumDcl->enumerators()) { 657 const Expr *InitExpr = Enumerator->getInitExpr(); 658 if (!InitExpr) { 659 PowerOfTwo = false; 660 AllHexdecimalEnumerator = false; 661 continue; 662 } 663 InitExpr = InitExpr->IgnoreParenCasts(); 664 if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) 665 if (BO->isShiftOp() || BO->isBitwiseOp()) 666 return true; 667 668 uint64_t EnumVal = Enumerator->getInitVal().getZExtValue(); 669 if (PowerOfTwo && EnumVal) { 670 if (!llvm::isPowerOf2_64(EnumVal)) 671 PowerOfTwo = false; 672 else if (EnumVal > MaxPowerOfTwoVal) 673 MaxPowerOfTwoVal = EnumVal; 674 } 675 if (AllHexdecimalEnumerator && EnumVal) { 676 bool FoundHexdecimalEnumerator = false; 677 SourceLocation EndLoc = Enumerator->getLocEnd(); 678 Token Tok; 679 if (!PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true)) 680 if (Tok.isLiteral() && Tok.getLength() > 2) { 681 if (const char *StringLit = Tok.getLiteralData()) 682 FoundHexdecimalEnumerator = 683 (StringLit[0] == '0' && (toLowercase(StringLit[1]) == 'x')); 684 } 685 if (!FoundHexdecimalEnumerator) 686 AllHexdecimalEnumerator = false; 687 } 688 } 689 return AllHexdecimalEnumerator || (PowerOfTwo && (MaxPowerOfTwoVal > 2)); 690 } 691 692 void ObjCMigrateASTConsumer::migrateProtocolConformance(ASTContext &Ctx, 693 const ObjCImplementationDecl *ImpDecl) { 694 const ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface(); 695 if (!IDecl || ObjCProtocolDecls.empty() || IDecl->isDeprecated()) 696 return; 697 // Find all implicit conforming protocols for this class 698 // and make them explicit. 699 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ExplicitProtocols; 700 Ctx.CollectInheritedProtocols(IDecl, ExplicitProtocols); 701 llvm::SmallVector<ObjCProtocolDecl *, 8> PotentialImplicitProtocols; 702 703 for (ObjCProtocolDecl *ProtDecl : ObjCProtocolDecls) 704 if (!ExplicitProtocols.count(ProtDecl)) 705 PotentialImplicitProtocols.push_back(ProtDecl); 706 707 if (PotentialImplicitProtocols.empty()) 708 return; 709 710 // go through list of non-optional methods and properties in each protocol 711 // in the PotentialImplicitProtocols list. If class implements every one of the 712 // methods and properties, then this class conforms to this protocol. 713 llvm::SmallVector<ObjCProtocolDecl*, 8> ConformingProtocols; 714 for (unsigned i = 0, e = PotentialImplicitProtocols.size(); i != e; i++) 715 if (ClassImplementsAllMethodsAndProperties(Ctx, ImpDecl, IDecl, 716 PotentialImplicitProtocols[i])) 717 ConformingProtocols.push_back(PotentialImplicitProtocols[i]); 718 719 if (ConformingProtocols.empty()) 720 return; 721 722 // Further reduce number of conforming protocols. If protocol P1 is in the list 723 // protocol P2 (P2<P1>), No need to include P1. 724 llvm::SmallVector<ObjCProtocolDecl*, 8> MinimalConformingProtocols; 725 for (unsigned i = 0, e = ConformingProtocols.size(); i != e; i++) { 726 bool DropIt = false; 727 ObjCProtocolDecl *TargetPDecl = ConformingProtocols[i]; 728 for (unsigned i1 = 0, e1 = ConformingProtocols.size(); i1 != e1; i1++) { 729 ObjCProtocolDecl *PDecl = ConformingProtocols[i1]; 730 if (PDecl == TargetPDecl) 731 continue; 732 if (PDecl->lookupProtocolNamed( 733 TargetPDecl->getDeclName().getAsIdentifierInfo())) { 734 DropIt = true; 735 break; 736 } 737 } 738 if (!DropIt) 739 MinimalConformingProtocols.push_back(TargetPDecl); 740 } 741 if (MinimalConformingProtocols.empty()) 742 return; 743 edit::Commit commit(*Editor); 744 rewriteToObjCInterfaceDecl(IDecl, MinimalConformingProtocols, 745 *NSAPIObj, commit); 746 Editor->commit(commit); 747 } 748 749 void ObjCMigrateASTConsumer::CacheObjCNSIntegerTypedefed( 750 const TypedefDecl *TypedefDcl) { 751 752 QualType qt = TypedefDcl->getTypeSourceInfo()->getType(); 753 if (NSAPIObj->isObjCNSIntegerType(qt)) 754 NSIntegerTypedefed = TypedefDcl; 755 else if (NSAPIObj->isObjCNSUIntegerType(qt)) 756 NSUIntegerTypedefed = TypedefDcl; 757 } 758 759 bool ObjCMigrateASTConsumer::migrateNSEnumDecl(ASTContext &Ctx, 760 const EnumDecl *EnumDcl, 761 const TypedefDecl *TypedefDcl) { 762 if (!EnumDcl->isCompleteDefinition() || EnumDcl->getIdentifier() || 763 EnumDcl->isDeprecated()) 764 return false; 765 if (!TypedefDcl) { 766 if (NSIntegerTypedefed) { 767 TypedefDcl = NSIntegerTypedefed; 768 NSIntegerTypedefed = nullptr; 769 } 770 else if (NSUIntegerTypedefed) { 771 TypedefDcl = NSUIntegerTypedefed; 772 NSUIntegerTypedefed = nullptr; 773 } 774 else 775 return false; 776 FileID FileIdOfTypedefDcl = 777 PP.getSourceManager().getFileID(TypedefDcl->getLocation()); 778 FileID FileIdOfEnumDcl = 779 PP.getSourceManager().getFileID(EnumDcl->getLocation()); 780 if (FileIdOfTypedefDcl != FileIdOfEnumDcl) 781 return false; 782 } 783 if (TypedefDcl->isDeprecated()) 784 return false; 785 786 QualType qt = TypedefDcl->getTypeSourceInfo()->getType(); 787 bool IsNSIntegerType = NSAPIObj->isObjCNSIntegerType(qt); 788 bool IsNSUIntegerType = !IsNSIntegerType && NSAPIObj->isObjCNSUIntegerType(qt); 789 790 if (!IsNSIntegerType && !IsNSUIntegerType) { 791 // Also check for typedef enum {...} TD; 792 if (const EnumType *EnumTy = qt->getAs<EnumType>()) { 793 if (EnumTy->getDecl() == EnumDcl) { 794 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl); 795 if (NSOptions) { 796 if (!Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition()) 797 return false; 798 } 799 else if (!Ctx.Idents.get("NS_ENUM").hasMacroDefinition()) 800 return false; 801 edit::Commit commit(*Editor); 802 rewriteToNSMacroDecl(EnumDcl, TypedefDcl, *NSAPIObj, commit, !NSOptions); 803 Editor->commit(commit); 804 return true; 805 } 806 } 807 return false; 808 } 809 810 // We may still use NS_OPTIONS based on what we find in the enumertor list. 811 bool NSOptions = UseNSOptionsMacro(PP, Ctx, EnumDcl); 812 // NS_ENUM must be available. 813 if (IsNSIntegerType && !Ctx.Idents.get("NS_ENUM").hasMacroDefinition()) 814 return false; 815 // NS_OPTIONS must be available. 816 if (IsNSUIntegerType && !Ctx.Idents.get("NS_OPTIONS").hasMacroDefinition()) 817 return false; 818 edit::Commit commit(*Editor); 819 bool Res = rewriteToNSEnumDecl(EnumDcl, TypedefDcl, *NSAPIObj, 820 commit, IsNSIntegerType, NSOptions); 821 Editor->commit(commit); 822 return Res; 823 } 824 825 static void ReplaceWithInstancetype(ASTContext &Ctx, 826 const ObjCMigrateASTConsumer &ASTC, 827 ObjCMethodDecl *OM) { 828 if (OM->getReturnType() == Ctx.getObjCInstanceType()) 829 return; // already has instancetype. 830 831 SourceRange R; 832 std::string ClassString; 833 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) { 834 TypeLoc TL = TSInfo->getTypeLoc(); 835 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); 836 ClassString = "instancetype"; 837 } 838 else { 839 R = SourceRange(OM->getLocStart(), OM->getLocStart()); 840 ClassString = OM->isInstanceMethod() ? '-' : '+'; 841 ClassString += " (instancetype)"; 842 } 843 edit::Commit commit(*ASTC.Editor); 844 commit.replace(R, ClassString); 845 ASTC.Editor->commit(commit); 846 } 847 848 static void ReplaceWithClasstype(const ObjCMigrateASTConsumer &ASTC, 849 ObjCMethodDecl *OM) { 850 ObjCInterfaceDecl *IDecl = OM->getClassInterface(); 851 SourceRange R; 852 std::string ClassString; 853 if (TypeSourceInfo *TSInfo = OM->getReturnTypeSourceInfo()) { 854 TypeLoc TL = TSInfo->getTypeLoc(); 855 R = SourceRange(TL.getBeginLoc(), TL.getEndLoc()); { 856 ClassString = IDecl->getName(); 857 ClassString += "*"; 858 } 859 } 860 else { 861 R = SourceRange(OM->getLocStart(), OM->getLocStart()); 862 ClassString = "+ ("; 863 ClassString += IDecl->getName(); ClassString += "*)"; 864 } 865 edit::Commit commit(*ASTC.Editor); 866 commit.replace(R, ClassString); 867 ASTC.Editor->commit(commit); 868 } 869 870 void ObjCMigrateASTConsumer::migrateMethodInstanceType(ASTContext &Ctx, 871 ObjCContainerDecl *CDecl, 872 ObjCMethodDecl *OM) { 873 ObjCInstanceTypeFamily OIT_Family = 874 Selector::getInstTypeMethodFamily(OM->getSelector()); 875 876 std::string ClassName; 877 switch (OIT_Family) { 878 case OIT_None: 879 migrateFactoryMethod(Ctx, CDecl, OM); 880 return; 881 case OIT_Array: 882 ClassName = "NSArray"; 883 break; 884 case OIT_Dictionary: 885 ClassName = "NSDictionary"; 886 break; 887 case OIT_Singleton: 888 migrateFactoryMethod(Ctx, CDecl, OM, OIT_Singleton); 889 return; 890 case OIT_Init: 891 if (OM->getReturnType()->isObjCIdType()) 892 ReplaceWithInstancetype(Ctx, *this, OM); 893 return; 894 case OIT_ReturnsSelf: 895 migrateFactoryMethod(Ctx, CDecl, OM, OIT_ReturnsSelf); 896 return; 897 } 898 if (!OM->getReturnType()->isObjCIdType()) 899 return; 900 901 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); 902 if (!IDecl) { 903 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) 904 IDecl = CatDecl->getClassInterface(); 905 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl)) 906 IDecl = ImpDecl->getClassInterface(); 907 } 908 if (!IDecl || 909 !IDecl->lookupInheritedClass(&Ctx.Idents.get(ClassName))) { 910 migrateFactoryMethod(Ctx, CDecl, OM); 911 return; 912 } 913 ReplaceWithInstancetype(Ctx, *this, OM); 914 } 915 916 static bool TypeIsInnerPointer(QualType T) { 917 if (!T->isAnyPointerType()) 918 return false; 919 if (T->isObjCObjectPointerType() || T->isObjCBuiltinType() || 920 T->isBlockPointerType() || T->isFunctionPointerType() || 921 ento::coreFoundation::isCFObjectRef(T)) 922 return false; 923 // Also, typedef-of-pointer-to-incomplete-struct is something that we assume 924 // is not an innter pointer type. 925 QualType OrigT = T; 926 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) 927 T = TD->getDecl()->getUnderlyingType(); 928 if (OrigT == T || !T->isPointerType()) 929 return true; 930 const PointerType* PT = T->getAs<PointerType>(); 931 QualType UPointeeT = PT->getPointeeType().getUnqualifiedType(); 932 if (UPointeeT->isRecordType()) { 933 const RecordType *RecordTy = UPointeeT->getAs<RecordType>(); 934 if (!RecordTy->getDecl()->isCompleteDefinition()) 935 return false; 936 } 937 return true; 938 } 939 940 /// \brief Check whether the two versions match. 941 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y) { 942 return (X == Y); 943 } 944 945 /// AvailabilityAttrsMatch - This routine checks that if comparing two 946 /// availability attributes, all their components match. It returns 947 /// true, if not dealing with availability or when all components of 948 /// availability attributes match. This routine is only called when 949 /// the attributes are of the same kind. 950 static bool AvailabilityAttrsMatch(Attr *At1, Attr *At2) { 951 const AvailabilityAttr *AA1 = dyn_cast<AvailabilityAttr>(At1); 952 if (!AA1) 953 return true; 954 const AvailabilityAttr *AA2 = dyn_cast<AvailabilityAttr>(At2); 955 956 VersionTuple Introduced1 = AA1->getIntroduced(); 957 VersionTuple Deprecated1 = AA1->getDeprecated(); 958 VersionTuple Obsoleted1 = AA1->getObsoleted(); 959 bool IsUnavailable1 = AA1->getUnavailable(); 960 VersionTuple Introduced2 = AA2->getIntroduced(); 961 VersionTuple Deprecated2 = AA2->getDeprecated(); 962 VersionTuple Obsoleted2 = AA2->getObsoleted(); 963 bool IsUnavailable2 = AA2->getUnavailable(); 964 return (versionsMatch(Introduced1, Introduced2) && 965 versionsMatch(Deprecated1, Deprecated2) && 966 versionsMatch(Obsoleted1, Obsoleted2) && 967 IsUnavailable1 == IsUnavailable2); 968 969 } 970 971 static bool MatchTwoAttributeLists(const AttrVec &Attrs1, const AttrVec &Attrs2, 972 bool &AvailabilityArgsMatch) { 973 // This list is very small, so this need not be optimized. 974 for (unsigned i = 0, e = Attrs1.size(); i != e; i++) { 975 bool match = false; 976 for (unsigned j = 0, f = Attrs2.size(); j != f; j++) { 977 // Matching attribute kind only. Except for Availabilty attributes, 978 // we are not getting into details of the attributes. For all practical purposes 979 // this is sufficient. 980 if (Attrs1[i]->getKind() == Attrs2[j]->getKind()) { 981 if (AvailabilityArgsMatch) 982 AvailabilityArgsMatch = AvailabilityAttrsMatch(Attrs1[i], Attrs2[j]); 983 match = true; 984 break; 985 } 986 } 987 if (!match) 988 return false; 989 } 990 return true; 991 } 992 993 /// AttributesMatch - This routine checks list of attributes for two 994 /// decls. It returns false, if there is a mismatch in kind of 995 /// attributes seen in the decls. It returns true if the two decls 996 /// have list of same kind of attributes. Furthermore, when there 997 /// are availability attributes in the two decls, it sets the 998 /// AvailabilityArgsMatch to false if availability attributes have 999 /// different versions, etc. 1000 static bool AttributesMatch(const Decl *Decl1, const Decl *Decl2, 1001 bool &AvailabilityArgsMatch) { 1002 if (!Decl1->hasAttrs() || !Decl2->hasAttrs()) { 1003 AvailabilityArgsMatch = (Decl1->hasAttrs() == Decl2->hasAttrs()); 1004 return true; 1005 } 1006 AvailabilityArgsMatch = true; 1007 const AttrVec &Attrs1 = Decl1->getAttrs(); 1008 const AttrVec &Attrs2 = Decl2->getAttrs(); 1009 bool match = MatchTwoAttributeLists(Attrs1, Attrs2, AvailabilityArgsMatch); 1010 if (match && (Attrs2.size() > Attrs1.size())) 1011 return MatchTwoAttributeLists(Attrs2, Attrs1, AvailabilityArgsMatch); 1012 return match; 1013 } 1014 1015 static bool IsValidIdentifier(ASTContext &Ctx, 1016 const char *Name) { 1017 if (!isIdentifierHead(Name[0])) 1018 return false; 1019 std::string NameString = Name; 1020 NameString[0] = toLowercase(NameString[0]); 1021 IdentifierInfo *II = &Ctx.Idents.get(NameString); 1022 return II->getTokenID() == tok::identifier; 1023 } 1024 1025 bool ObjCMigrateASTConsumer::migrateProperty(ASTContext &Ctx, 1026 ObjCContainerDecl *D, 1027 ObjCMethodDecl *Method) { 1028 if (Method->isPropertyAccessor() || !Method->isInstanceMethod() || 1029 Method->param_size() != 0) 1030 return false; 1031 // Is this method candidate to be a getter? 1032 QualType GRT = Method->getReturnType(); 1033 if (GRT->isVoidType()) 1034 return false; 1035 1036 Selector GetterSelector = Method->getSelector(); 1037 ObjCInstanceTypeFamily OIT_Family = 1038 Selector::getInstTypeMethodFamily(GetterSelector); 1039 1040 if (OIT_Family != OIT_None) 1041 return false; 1042 1043 IdentifierInfo *getterName = GetterSelector.getIdentifierInfoForSlot(0); 1044 Selector SetterSelector = 1045 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 1046 PP.getSelectorTable(), 1047 getterName); 1048 ObjCMethodDecl *SetterMethod = D->getInstanceMethod(SetterSelector); 1049 unsigned LengthOfPrefix = 0; 1050 if (!SetterMethod) { 1051 // try a different naming convention for getter: isXxxxx 1052 StringRef getterNameString = getterName->getName(); 1053 bool IsPrefix = getterNameString.startswith("is"); 1054 // Note that we don't want to change an isXXX method of retainable object 1055 // type to property (readonly or otherwise). 1056 if (IsPrefix && GRT->isObjCRetainableType()) 1057 return false; 1058 if (IsPrefix || getterNameString.startswith("get")) { 1059 LengthOfPrefix = (IsPrefix ? 2 : 3); 1060 const char *CGetterName = getterNameString.data() + LengthOfPrefix; 1061 // Make sure that first character after "is" or "get" prefix can 1062 // start an identifier. 1063 if (!IsValidIdentifier(Ctx, CGetterName)) 1064 return false; 1065 if (CGetterName[0] && isUppercase(CGetterName[0])) { 1066 getterName = &Ctx.Idents.get(CGetterName); 1067 SetterSelector = 1068 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 1069 PP.getSelectorTable(), 1070 getterName); 1071 SetterMethod = D->getInstanceMethod(SetterSelector); 1072 } 1073 } 1074 } 1075 1076 if (SetterMethod) { 1077 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ReadwriteProperty) == 0) 1078 return false; 1079 bool AvailabilityArgsMatch; 1080 if (SetterMethod->isDeprecated() || 1081 !AttributesMatch(Method, SetterMethod, AvailabilityArgsMatch)) 1082 return false; 1083 1084 // Is this a valid setter, matching the target getter? 1085 QualType SRT = SetterMethod->getReturnType(); 1086 if (!SRT->isVoidType()) 1087 return false; 1088 const ParmVarDecl *argDecl = *SetterMethod->param_begin(); 1089 QualType ArgType = argDecl->getType(); 1090 if (!Ctx.hasSameUnqualifiedType(ArgType, GRT)) 1091 return false; 1092 edit::Commit commit(*Editor); 1093 rewriteToObjCProperty(Method, SetterMethod, *NSAPIObj, commit, 1094 LengthOfPrefix, 1095 (ASTMigrateActions & 1096 FrontendOptions::ObjCMT_AtomicProperty) != 0, 1097 (ASTMigrateActions & 1098 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0, 1099 AvailabilityArgsMatch); 1100 Editor->commit(commit); 1101 return true; 1102 } 1103 else if (ASTMigrateActions & FrontendOptions::ObjCMT_ReadonlyProperty) { 1104 // Try a non-void method with no argument (and no setter or property of same name 1105 // as a 'readonly' property. 1106 edit::Commit commit(*Editor); 1107 rewriteToObjCProperty(Method, nullptr /*SetterMethod*/, *NSAPIObj, commit, 1108 LengthOfPrefix, 1109 (ASTMigrateActions & 1110 FrontendOptions::ObjCMT_AtomicProperty) != 0, 1111 (ASTMigrateActions & 1112 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty) != 0, 1113 /*AvailabilityArgsMatch*/false); 1114 Editor->commit(commit); 1115 return true; 1116 } 1117 return false; 1118 } 1119 1120 void ObjCMigrateASTConsumer::migrateNsReturnsInnerPointer(ASTContext &Ctx, 1121 ObjCMethodDecl *OM) { 1122 if (OM->isImplicit() || 1123 !OM->isInstanceMethod() || 1124 OM->hasAttr<ObjCReturnsInnerPointerAttr>()) 1125 return; 1126 1127 QualType RT = OM->getReturnType(); 1128 if (!TypeIsInnerPointer(RT) || 1129 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition()) 1130 return; 1131 1132 edit::Commit commit(*Editor); 1133 commit.insertBefore(OM->getLocEnd(), " NS_RETURNS_INNER_POINTER"); 1134 Editor->commit(commit); 1135 } 1136 1137 void ObjCMigrateASTConsumer::migratePropertyNsReturnsInnerPointer(ASTContext &Ctx, 1138 ObjCPropertyDecl *P) { 1139 QualType T = P->getType(); 1140 1141 if (!TypeIsInnerPointer(T) || 1142 !Ctx.Idents.get("NS_RETURNS_INNER_POINTER").hasMacroDefinition()) 1143 return; 1144 edit::Commit commit(*Editor); 1145 commit.insertBefore(P->getLocEnd(), " NS_RETURNS_INNER_POINTER "); 1146 Editor->commit(commit); 1147 } 1148 1149 void ObjCMigrateASTConsumer::migrateAllMethodInstaceType(ASTContext &Ctx, 1150 ObjCContainerDecl *CDecl) { 1151 if (CDecl->isDeprecated() || IsCategoryNameWithDeprecatedSuffix(CDecl)) 1152 return; 1153 1154 // migrate methods which can have instancetype as their result type. 1155 for (auto *Method : CDecl->methods()) { 1156 if (Method->isDeprecated()) 1157 continue; 1158 migrateMethodInstanceType(Ctx, CDecl, Method); 1159 } 1160 } 1161 1162 void ObjCMigrateASTConsumer::migrateFactoryMethod(ASTContext &Ctx, 1163 ObjCContainerDecl *CDecl, 1164 ObjCMethodDecl *OM, 1165 ObjCInstanceTypeFamily OIT_Family) { 1166 if (OM->isInstanceMethod() || 1167 OM->getReturnType() == Ctx.getObjCInstanceType() || 1168 !OM->getReturnType()->isObjCIdType()) 1169 return; 1170 1171 // Candidate factory methods are + (id) NaMeXXX : ... which belong to a class 1172 // NSYYYNamE with matching names be at least 3 characters long. 1173 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); 1174 if (!IDecl) { 1175 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) 1176 IDecl = CatDecl->getClassInterface(); 1177 else if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(CDecl)) 1178 IDecl = ImpDecl->getClassInterface(); 1179 } 1180 if (!IDecl) 1181 return; 1182 1183 std::string StringClassName = IDecl->getName(); 1184 StringRef LoweredClassName(StringClassName); 1185 std::string StringLoweredClassName = LoweredClassName.lower(); 1186 LoweredClassName = StringLoweredClassName; 1187 1188 IdentifierInfo *MethodIdName = OM->getSelector().getIdentifierInfoForSlot(0); 1189 // Handle method with no name at its first selector slot; e.g. + (id):(int)x. 1190 if (!MethodIdName) 1191 return; 1192 1193 std::string MethodName = MethodIdName->getName(); 1194 if (OIT_Family == OIT_Singleton || OIT_Family == OIT_ReturnsSelf) { 1195 StringRef STRefMethodName(MethodName); 1196 size_t len = 0; 1197 if (STRefMethodName.startswith("standard")) 1198 len = strlen("standard"); 1199 else if (STRefMethodName.startswith("shared")) 1200 len = strlen("shared"); 1201 else if (STRefMethodName.startswith("default")) 1202 len = strlen("default"); 1203 else 1204 return; 1205 MethodName = STRefMethodName.substr(len); 1206 } 1207 std::string MethodNameSubStr = MethodName.substr(0, 3); 1208 StringRef MethodNamePrefix(MethodNameSubStr); 1209 std::string StringLoweredMethodNamePrefix = MethodNamePrefix.lower(); 1210 MethodNamePrefix = StringLoweredMethodNamePrefix; 1211 size_t Ix = LoweredClassName.rfind(MethodNamePrefix); 1212 if (Ix == StringRef::npos) 1213 return; 1214 std::string ClassNamePostfix = LoweredClassName.substr(Ix); 1215 StringRef LoweredMethodName(MethodName); 1216 std::string StringLoweredMethodName = LoweredMethodName.lower(); 1217 LoweredMethodName = StringLoweredMethodName; 1218 if (!LoweredMethodName.startswith(ClassNamePostfix)) 1219 return; 1220 if (OIT_Family == OIT_ReturnsSelf) 1221 ReplaceWithClasstype(*this, OM); 1222 else 1223 ReplaceWithInstancetype(Ctx, *this, OM); 1224 } 1225 1226 static bool IsVoidStarType(QualType Ty) { 1227 if (!Ty->isPointerType()) 1228 return false; 1229 1230 while (const TypedefType *TD = dyn_cast<TypedefType>(Ty.getTypePtr())) 1231 Ty = TD->getDecl()->getUnderlyingType(); 1232 1233 // Is the type void*? 1234 const PointerType* PT = Ty->getAs<PointerType>(); 1235 if (PT->getPointeeType().getUnqualifiedType()->isVoidType()) 1236 return true; 1237 return IsVoidStarType(PT->getPointeeType()); 1238 } 1239 1240 /// AuditedType - This routine audits the type AT and returns false if it is one of known 1241 /// CF object types or of the "void *" variety. It returns true if we don't care about the type 1242 /// such as a non-pointer or pointers which have no ownership issues (such as "int *"). 1243 static bool AuditedType (QualType AT) { 1244 if (!AT->isAnyPointerType() && !AT->isBlockPointerType()) 1245 return true; 1246 // FIXME. There isn't much we can say about CF pointer type; or is there? 1247 if (ento::coreFoundation::isCFObjectRef(AT) || 1248 IsVoidStarType(AT) || 1249 // If an ObjC object is type, assuming that it is not a CF function and 1250 // that it is an un-audited function. 1251 AT->isObjCObjectPointerType() || AT->isObjCBuiltinType()) 1252 return false; 1253 // All other pointers are assumed audited as harmless. 1254 return true; 1255 } 1256 1257 void ObjCMigrateASTConsumer::AnnotateImplicitBridging(ASTContext &Ctx) { 1258 if (CFFunctionIBCandidates.empty()) 1259 return; 1260 if (!Ctx.Idents.get("CF_IMPLICIT_BRIDGING_ENABLED").hasMacroDefinition()) { 1261 CFFunctionIBCandidates.clear(); 1262 FileId = FileID(); 1263 return; 1264 } 1265 // Insert CF_IMPLICIT_BRIDGING_ENABLE/CF_IMPLICIT_BRIDGING_DISABLED 1266 const Decl *FirstFD = CFFunctionIBCandidates[0]; 1267 const Decl *LastFD = 1268 CFFunctionIBCandidates[CFFunctionIBCandidates.size()-1]; 1269 const char *PragmaString = "\nCF_IMPLICIT_BRIDGING_ENABLED\n\n"; 1270 edit::Commit commit(*Editor); 1271 commit.insertBefore(FirstFD->getLocStart(), PragmaString); 1272 PragmaString = "\n\nCF_IMPLICIT_BRIDGING_DISABLED\n"; 1273 SourceLocation EndLoc = LastFD->getLocEnd(); 1274 // get location just past end of function location. 1275 EndLoc = PP.getLocForEndOfToken(EndLoc); 1276 if (isa<FunctionDecl>(LastFD)) { 1277 // For Methods, EndLoc points to the ending semcolon. So, 1278 // not of these extra work is needed. 1279 Token Tok; 1280 // get locaiton of token that comes after end of function. 1281 bool Failed = PP.getRawToken(EndLoc, Tok, /*IgnoreWhiteSpace=*/true); 1282 if (!Failed) 1283 EndLoc = Tok.getLocation(); 1284 } 1285 commit.insertAfterToken(EndLoc, PragmaString); 1286 Editor->commit(commit); 1287 FileId = FileID(); 1288 CFFunctionIBCandidates.clear(); 1289 } 1290 1291 void ObjCMigrateASTConsumer::migrateCFAnnotation(ASTContext &Ctx, const Decl *Decl) { 1292 if (Decl->isDeprecated()) 1293 return; 1294 1295 if (Decl->hasAttr<CFAuditedTransferAttr>()) { 1296 assert(CFFunctionIBCandidates.empty() && 1297 "Cannot have audited functions/methods inside user " 1298 "provided CF_IMPLICIT_BRIDGING_ENABLE"); 1299 return; 1300 } 1301 1302 // Finction must be annotated first. 1303 if (const FunctionDecl *FuncDecl = dyn_cast<FunctionDecl>(Decl)) { 1304 CF_BRIDGING_KIND AuditKind = migrateAddFunctionAnnotation(Ctx, FuncDecl); 1305 if (AuditKind == CF_BRIDGING_ENABLE) { 1306 CFFunctionIBCandidates.push_back(Decl); 1307 if (FileId.isInvalid()) 1308 FileId = PP.getSourceManager().getFileID(Decl->getLocation()); 1309 } 1310 else if (AuditKind == CF_BRIDGING_MAY_INCLUDE) { 1311 if (!CFFunctionIBCandidates.empty()) { 1312 CFFunctionIBCandidates.push_back(Decl); 1313 if (FileId.isInvalid()) 1314 FileId = PP.getSourceManager().getFileID(Decl->getLocation()); 1315 } 1316 } 1317 else 1318 AnnotateImplicitBridging(Ctx); 1319 } 1320 else { 1321 migrateAddMethodAnnotation(Ctx, cast<ObjCMethodDecl>(Decl)); 1322 AnnotateImplicitBridging(Ctx); 1323 } 1324 } 1325 1326 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx, 1327 const CallEffects &CE, 1328 const FunctionDecl *FuncDecl, 1329 bool ResultAnnotated) { 1330 // Annotate function. 1331 if (!ResultAnnotated) { 1332 RetEffect Ret = CE.getReturnValue(); 1333 const char *AnnotationString = nullptr; 1334 if (Ret.getObjKind() == RetEffect::CF) { 1335 if (Ret.isOwned() && 1336 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition()) 1337 AnnotationString = " CF_RETURNS_RETAINED"; 1338 else if (Ret.notOwned() && 1339 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition()) 1340 AnnotationString = " CF_RETURNS_NOT_RETAINED"; 1341 } 1342 else if (Ret.getObjKind() == RetEffect::ObjC) { 1343 if (Ret.isOwned() && 1344 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition()) 1345 AnnotationString = " NS_RETURNS_RETAINED"; 1346 } 1347 1348 if (AnnotationString) { 1349 edit::Commit commit(*Editor); 1350 commit.insertAfterToken(FuncDecl->getLocEnd(), AnnotationString); 1351 Editor->commit(commit); 1352 } 1353 } 1354 ArrayRef<ArgEffect> AEArgs = CE.getArgs(); 1355 unsigned i = 0; 1356 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(), 1357 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) { 1358 const ParmVarDecl *pd = *pi; 1359 ArgEffect AE = AEArgs[i]; 1360 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() && 1361 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) { 1362 edit::Commit commit(*Editor); 1363 commit.insertBefore(pd->getLocation(), "CF_CONSUMED "); 1364 Editor->commit(commit); 1365 } 1366 else if (AE == DecRefMsg && !pd->hasAttr<NSConsumedAttr>() && 1367 Ctx.Idents.get("NS_CONSUMED").hasMacroDefinition()) { 1368 edit::Commit commit(*Editor); 1369 commit.insertBefore(pd->getLocation(), "NS_CONSUMED "); 1370 Editor->commit(commit); 1371 } 1372 } 1373 } 1374 1375 1376 ObjCMigrateASTConsumer::CF_BRIDGING_KIND 1377 ObjCMigrateASTConsumer::migrateAddFunctionAnnotation( 1378 ASTContext &Ctx, 1379 const FunctionDecl *FuncDecl) { 1380 if (FuncDecl->hasBody()) 1381 return CF_BRIDGING_NONE; 1382 1383 CallEffects CE = CallEffects::getEffect(FuncDecl); 1384 bool FuncIsReturnAnnotated = (FuncDecl->hasAttr<CFReturnsRetainedAttr>() || 1385 FuncDecl->hasAttr<CFReturnsNotRetainedAttr>() || 1386 FuncDecl->hasAttr<NSReturnsRetainedAttr>() || 1387 FuncDecl->hasAttr<NSReturnsNotRetainedAttr>() || 1388 FuncDecl->hasAttr<NSReturnsAutoreleasedAttr>()); 1389 1390 // Trivial case of when funciton is annotated and has no argument. 1391 if (FuncIsReturnAnnotated && FuncDecl->getNumParams() == 0) 1392 return CF_BRIDGING_NONE; 1393 1394 bool ReturnCFAudited = false; 1395 if (!FuncIsReturnAnnotated) { 1396 RetEffect Ret = CE.getReturnValue(); 1397 if (Ret.getObjKind() == RetEffect::CF && 1398 (Ret.isOwned() || Ret.notOwned())) 1399 ReturnCFAudited = true; 1400 else if (!AuditedType(FuncDecl->getReturnType())) 1401 return CF_BRIDGING_NONE; 1402 } 1403 1404 // At this point result type is audited for potential inclusion. 1405 // Now, how about argument types. 1406 ArrayRef<ArgEffect> AEArgs = CE.getArgs(); 1407 unsigned i = 0; 1408 bool ArgCFAudited = false; 1409 for (FunctionDecl::param_const_iterator pi = FuncDecl->param_begin(), 1410 pe = FuncDecl->param_end(); pi != pe; ++pi, ++i) { 1411 const ParmVarDecl *pd = *pi; 1412 ArgEffect AE = AEArgs[i]; 1413 if (AE == DecRef /*CFConsumed annotated*/ || AE == IncRef) { 1414 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>()) 1415 ArgCFAudited = true; 1416 else if (AE == IncRef) 1417 ArgCFAudited = true; 1418 } 1419 else { 1420 QualType AT = pd->getType(); 1421 if (!AuditedType(AT)) { 1422 AddCFAnnotations(Ctx, CE, FuncDecl, FuncIsReturnAnnotated); 1423 return CF_BRIDGING_NONE; 1424 } 1425 } 1426 } 1427 if (ReturnCFAudited || ArgCFAudited) 1428 return CF_BRIDGING_ENABLE; 1429 1430 return CF_BRIDGING_MAY_INCLUDE; 1431 } 1432 1433 void ObjCMigrateASTConsumer::migrateARCSafeAnnotation(ASTContext &Ctx, 1434 ObjCContainerDecl *CDecl) { 1435 if (!isa<ObjCInterfaceDecl>(CDecl) || CDecl->isDeprecated()) 1436 return; 1437 1438 // migrate methods which can have instancetype as their result type. 1439 for (const auto *Method : CDecl->methods()) 1440 migrateCFAnnotation(Ctx, Method); 1441 } 1442 1443 void ObjCMigrateASTConsumer::AddCFAnnotations(ASTContext &Ctx, 1444 const CallEffects &CE, 1445 const ObjCMethodDecl *MethodDecl, 1446 bool ResultAnnotated) { 1447 // Annotate function. 1448 if (!ResultAnnotated) { 1449 RetEffect Ret = CE.getReturnValue(); 1450 const char *AnnotationString = nullptr; 1451 if (Ret.getObjKind() == RetEffect::CF) { 1452 if (Ret.isOwned() && 1453 Ctx.Idents.get("CF_RETURNS_RETAINED").hasMacroDefinition()) 1454 AnnotationString = " CF_RETURNS_RETAINED"; 1455 else if (Ret.notOwned() && 1456 Ctx.Idents.get("CF_RETURNS_NOT_RETAINED").hasMacroDefinition()) 1457 AnnotationString = " CF_RETURNS_NOT_RETAINED"; 1458 } 1459 else if (Ret.getObjKind() == RetEffect::ObjC) { 1460 ObjCMethodFamily OMF = MethodDecl->getMethodFamily(); 1461 switch (OMF) { 1462 case clang::OMF_alloc: 1463 case clang::OMF_new: 1464 case clang::OMF_copy: 1465 case clang::OMF_init: 1466 case clang::OMF_mutableCopy: 1467 break; 1468 1469 default: 1470 if (Ret.isOwned() && 1471 Ctx.Idents.get("NS_RETURNS_RETAINED").hasMacroDefinition()) 1472 AnnotationString = " NS_RETURNS_RETAINED"; 1473 break; 1474 } 1475 } 1476 1477 if (AnnotationString) { 1478 edit::Commit commit(*Editor); 1479 commit.insertBefore(MethodDecl->getLocEnd(), AnnotationString); 1480 Editor->commit(commit); 1481 } 1482 } 1483 ArrayRef<ArgEffect> AEArgs = CE.getArgs(); 1484 unsigned i = 0; 1485 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(), 1486 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) { 1487 const ParmVarDecl *pd = *pi; 1488 ArgEffect AE = AEArgs[i]; 1489 if (AE == DecRef && !pd->hasAttr<CFConsumedAttr>() && 1490 Ctx.Idents.get("CF_CONSUMED").hasMacroDefinition()) { 1491 edit::Commit commit(*Editor); 1492 commit.insertBefore(pd->getLocation(), "CF_CONSUMED "); 1493 Editor->commit(commit); 1494 } 1495 } 1496 } 1497 1498 void ObjCMigrateASTConsumer::migrateAddMethodAnnotation( 1499 ASTContext &Ctx, 1500 const ObjCMethodDecl *MethodDecl) { 1501 if (MethodDecl->hasBody() || MethodDecl->isImplicit()) 1502 return; 1503 1504 CallEffects CE = CallEffects::getEffect(MethodDecl); 1505 bool MethodIsReturnAnnotated = (MethodDecl->hasAttr<CFReturnsRetainedAttr>() || 1506 MethodDecl->hasAttr<CFReturnsNotRetainedAttr>() || 1507 MethodDecl->hasAttr<NSReturnsRetainedAttr>() || 1508 MethodDecl->hasAttr<NSReturnsNotRetainedAttr>() || 1509 MethodDecl->hasAttr<NSReturnsAutoreleasedAttr>()); 1510 1511 if (CE.getReceiver() == DecRefMsg && 1512 !MethodDecl->hasAttr<NSConsumesSelfAttr>() && 1513 MethodDecl->getMethodFamily() != OMF_init && 1514 MethodDecl->getMethodFamily() != OMF_release && 1515 Ctx.Idents.get("NS_CONSUMES_SELF").hasMacroDefinition()) { 1516 edit::Commit commit(*Editor); 1517 commit.insertBefore(MethodDecl->getLocEnd(), " NS_CONSUMES_SELF"); 1518 Editor->commit(commit); 1519 } 1520 1521 // Trivial case of when funciton is annotated and has no argument. 1522 if (MethodIsReturnAnnotated && 1523 (MethodDecl->param_begin() == MethodDecl->param_end())) 1524 return; 1525 1526 if (!MethodIsReturnAnnotated) { 1527 RetEffect Ret = CE.getReturnValue(); 1528 if ((Ret.getObjKind() == RetEffect::CF || 1529 Ret.getObjKind() == RetEffect::ObjC) && 1530 (Ret.isOwned() || Ret.notOwned())) { 1531 AddCFAnnotations(Ctx, CE, MethodDecl, false); 1532 return; 1533 } else if (!AuditedType(MethodDecl->getReturnType())) 1534 return; 1535 } 1536 1537 // At this point result type is either annotated or audited. 1538 // Now, how about argument types. 1539 ArrayRef<ArgEffect> AEArgs = CE.getArgs(); 1540 unsigned i = 0; 1541 for (ObjCMethodDecl::param_const_iterator pi = MethodDecl->param_begin(), 1542 pe = MethodDecl->param_end(); pi != pe; ++pi, ++i) { 1543 const ParmVarDecl *pd = *pi; 1544 ArgEffect AE = AEArgs[i]; 1545 if ((AE == DecRef && !pd->hasAttr<CFConsumedAttr>()) || AE == IncRef || 1546 !AuditedType(pd->getType())) { 1547 AddCFAnnotations(Ctx, CE, MethodDecl, MethodIsReturnAnnotated); 1548 return; 1549 } 1550 } 1551 return; 1552 } 1553 1554 namespace { 1555 class SuperInitChecker : public RecursiveASTVisitor<SuperInitChecker> { 1556 public: 1557 bool shouldVisitTemplateInstantiations() const { return false; } 1558 bool shouldWalkTypesOfTypeLocs() const { return false; } 1559 1560 bool VisitObjCMessageExpr(ObjCMessageExpr *E) { 1561 if (E->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 1562 if (E->getMethodFamily() == OMF_init) 1563 return false; 1564 } 1565 return true; 1566 } 1567 }; 1568 } // anonymous namespace 1569 1570 static bool hasSuperInitCall(const ObjCMethodDecl *MD) { 1571 return !SuperInitChecker().TraverseStmt(MD->getBody()); 1572 } 1573 1574 void ObjCMigrateASTConsumer::inferDesignatedInitializers( 1575 ASTContext &Ctx, 1576 const ObjCImplementationDecl *ImplD) { 1577 1578 const ObjCInterfaceDecl *IFace = ImplD->getClassInterface(); 1579 if (!IFace || IFace->hasDesignatedInitializers()) 1580 return; 1581 if (!Ctx.Idents.get("NS_DESIGNATED_INITIALIZER").hasMacroDefinition()) 1582 return; 1583 1584 for (const auto *MD : ImplD->instance_methods()) { 1585 if (MD->isDeprecated() || 1586 MD->getMethodFamily() != OMF_init || 1587 MD->isDesignatedInitializerForTheInterface()) 1588 continue; 1589 const ObjCMethodDecl *IFaceM = IFace->getMethod(MD->getSelector(), 1590 /*isInstance=*/true); 1591 if (!IFaceM) 1592 continue; 1593 if (hasSuperInitCall(MD)) { 1594 edit::Commit commit(*Editor); 1595 commit.insert(IFaceM->getLocEnd(), " NS_DESIGNATED_INITIALIZER"); 1596 Editor->commit(commit); 1597 } 1598 } 1599 } 1600 1601 namespace { 1602 1603 class RewritesReceiver : public edit::EditsReceiver { 1604 Rewriter &Rewrite; 1605 1606 public: 1607 RewritesReceiver(Rewriter &Rewrite) : Rewrite(Rewrite) { } 1608 1609 void insert(SourceLocation loc, StringRef text) override { 1610 Rewrite.InsertText(loc, text); 1611 } 1612 void replace(CharSourceRange range, StringRef text) override { 1613 Rewrite.ReplaceText(range.getBegin(), Rewrite.getRangeSize(range), text); 1614 } 1615 }; 1616 1617 class JSONEditWriter : public edit::EditsReceiver { 1618 SourceManager &SourceMgr; 1619 llvm::raw_ostream &OS; 1620 1621 public: 1622 JSONEditWriter(SourceManager &SM, llvm::raw_ostream &OS) 1623 : SourceMgr(SM), OS(OS) { 1624 OS << "[\n"; 1625 } 1626 ~JSONEditWriter() { 1627 OS << "]\n"; 1628 } 1629 1630 private: 1631 struct EntryWriter { 1632 SourceManager &SourceMgr; 1633 llvm::raw_ostream &OS; 1634 1635 EntryWriter(SourceManager &SM, llvm::raw_ostream &OS) 1636 : SourceMgr(SM), OS(OS) { 1637 OS << " {\n"; 1638 } 1639 ~EntryWriter() { 1640 OS << " },\n"; 1641 } 1642 1643 void writeLoc(SourceLocation Loc) { 1644 FileID FID; 1645 unsigned Offset; 1646 std::tie(FID, Offset) = SourceMgr.getDecomposedLoc(Loc); 1647 assert(!FID.isInvalid()); 1648 SmallString<200> Path = 1649 StringRef(SourceMgr.getFileEntryForID(FID)->getName()); 1650 llvm::sys::fs::make_absolute(Path); 1651 OS << " \"file\": \""; 1652 OS.write_escaped(Path.str()) << "\",\n"; 1653 OS << " \"offset\": " << Offset << ",\n"; 1654 } 1655 1656 void writeRemove(CharSourceRange Range) { 1657 assert(Range.isCharRange()); 1658 std::pair<FileID, unsigned> Begin = 1659 SourceMgr.getDecomposedLoc(Range.getBegin()); 1660 std::pair<FileID, unsigned> End = 1661 SourceMgr.getDecomposedLoc(Range.getEnd()); 1662 assert(Begin.first == End.first); 1663 assert(Begin.second <= End.second); 1664 unsigned Length = End.second - Begin.second; 1665 1666 OS << " \"remove\": " << Length << ",\n"; 1667 } 1668 1669 void writeText(StringRef Text) { 1670 OS << " \"text\": \""; 1671 OS.write_escaped(Text) << "\",\n"; 1672 } 1673 }; 1674 1675 void insert(SourceLocation Loc, StringRef Text) override { 1676 EntryWriter Writer(SourceMgr, OS); 1677 Writer.writeLoc(Loc); 1678 Writer.writeText(Text); 1679 } 1680 1681 void replace(CharSourceRange Range, StringRef Text) override { 1682 EntryWriter Writer(SourceMgr, OS); 1683 Writer.writeLoc(Range.getBegin()); 1684 Writer.writeRemove(Range); 1685 Writer.writeText(Text); 1686 } 1687 1688 void remove(CharSourceRange Range) override { 1689 EntryWriter Writer(SourceMgr, OS); 1690 Writer.writeLoc(Range.getBegin()); 1691 Writer.writeRemove(Range); 1692 } 1693 }; 1694 1695 } 1696 1697 void ObjCMigrateASTConsumer::HandleTranslationUnit(ASTContext &Ctx) { 1698 1699 TranslationUnitDecl *TU = Ctx.getTranslationUnitDecl(); 1700 if (ASTMigrateActions & FrontendOptions::ObjCMT_MigrateDecls) { 1701 for (DeclContext::decl_iterator D = TU->decls_begin(), DEnd = TU->decls_end(); 1702 D != DEnd; ++D) { 1703 FileID FID = PP.getSourceManager().getFileID((*D)->getLocation()); 1704 if (!FID.isInvalid()) 1705 if (!FileId.isInvalid() && FileId != FID) { 1706 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) 1707 AnnotateImplicitBridging(Ctx); 1708 } 1709 1710 if (ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(*D)) 1711 if (canModify(CDecl)) 1712 migrateObjCInterfaceDecl(Ctx, CDecl); 1713 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(*D)) { 1714 if (canModify(CatDecl)) 1715 migrateObjCInterfaceDecl(Ctx, CatDecl); 1716 } 1717 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(*D)) 1718 ObjCProtocolDecls.insert(PDecl->getCanonicalDecl()); 1719 else if (const ObjCImplementationDecl *ImpDecl = 1720 dyn_cast<ObjCImplementationDecl>(*D)) { 1721 if ((ASTMigrateActions & FrontendOptions::ObjCMT_ProtocolConformance) && 1722 canModify(ImpDecl)) 1723 migrateProtocolConformance(Ctx, ImpDecl); 1724 } 1725 else if (const EnumDecl *ED = dyn_cast<EnumDecl>(*D)) { 1726 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros)) 1727 continue; 1728 if (!canModify(ED)) 1729 continue; 1730 DeclContext::decl_iterator N = D; 1731 if (++N != DEnd) { 1732 const TypedefDecl *TD = dyn_cast<TypedefDecl>(*N); 1733 if (migrateNSEnumDecl(Ctx, ED, TD) && TD) 1734 D++; 1735 } 1736 else 1737 migrateNSEnumDecl(Ctx, ED, /*TypedefDecl */nullptr); 1738 } 1739 else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(*D)) { 1740 if (!(ASTMigrateActions & FrontendOptions::ObjCMT_NsMacros)) 1741 continue; 1742 if (!canModify(TD)) 1743 continue; 1744 DeclContext::decl_iterator N = D; 1745 if (++N == DEnd) 1746 continue; 1747 if (const EnumDecl *ED = dyn_cast<EnumDecl>(*N)) { 1748 if (++N != DEnd) 1749 if (const TypedefDecl *TDF = dyn_cast<TypedefDecl>(*N)) { 1750 // prefer typedef-follows-enum to enum-follows-typedef pattern. 1751 if (migrateNSEnumDecl(Ctx, ED, TDF)) { 1752 ++D; ++D; 1753 CacheObjCNSIntegerTypedefed(TD); 1754 continue; 1755 } 1756 } 1757 if (migrateNSEnumDecl(Ctx, ED, TD)) { 1758 ++D; 1759 continue; 1760 } 1761 } 1762 CacheObjCNSIntegerTypedefed(TD); 1763 } 1764 else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*D)) { 1765 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) && 1766 canModify(FD)) 1767 migrateCFAnnotation(Ctx, FD); 1768 } 1769 1770 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(*D)) { 1771 bool CanModify = canModify(CDecl); 1772 // migrate methods which can have instancetype as their result type. 1773 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Instancetype) && 1774 CanModify) 1775 migrateAllMethodInstaceType(Ctx, CDecl); 1776 // annotate methods with CF annotations. 1777 if ((ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) && 1778 CanModify) 1779 migrateARCSafeAnnotation(Ctx, CDecl); 1780 } 1781 1782 if (const ObjCImplementationDecl * 1783 ImplD = dyn_cast<ObjCImplementationDecl>(*D)) { 1784 if ((ASTMigrateActions & FrontendOptions::ObjCMT_DesignatedInitializer) && 1785 canModify(ImplD)) 1786 inferDesignatedInitializers(Ctx, ImplD); 1787 } 1788 } 1789 if (ASTMigrateActions & FrontendOptions::ObjCMT_Annotation) 1790 AnnotateImplicitBridging(Ctx); 1791 } 1792 1793 if (IsOutputFile) { 1794 std::error_code EC; 1795 llvm::raw_fd_ostream OS(MigrateDir, EC, llvm::sys::fs::F_None); 1796 if (EC) { 1797 DiagnosticsEngine &Diags = Ctx.getDiagnostics(); 1798 Diags.Report(Diags.getCustomDiagID(DiagnosticsEngine::Error, "%0")) 1799 << EC.message(); 1800 return; 1801 } 1802 1803 JSONEditWriter Writer(Ctx.getSourceManager(), OS); 1804 Editor->applyRewrites(Writer); 1805 return; 1806 } 1807 1808 Rewriter rewriter(Ctx.getSourceManager(), Ctx.getLangOpts()); 1809 RewritesReceiver Rec(rewriter); 1810 Editor->applyRewrites(Rec); 1811 1812 for (Rewriter::buffer_iterator 1813 I = rewriter.buffer_begin(), E = rewriter.buffer_end(); I != E; ++I) { 1814 FileID FID = I->first; 1815 RewriteBuffer &buf = I->second; 1816 const FileEntry *file = Ctx.getSourceManager().getFileEntryForID(FID); 1817 assert(file); 1818 SmallString<512> newText; 1819 llvm::raw_svector_ostream vecOS(newText); 1820 buf.write(vecOS); 1821 vecOS.flush(); 1822 std::unique_ptr<llvm::MemoryBuffer> memBuf( 1823 llvm::MemoryBuffer::getMemBufferCopy( 1824 StringRef(newText.data(), newText.size()), file->getName())); 1825 SmallString<64> filePath(file->getName()); 1826 FileMgr.FixupRelativePath(filePath); 1827 Remapper.remap(filePath.str(), std::move(memBuf)); 1828 } 1829 1830 if (IsOutputFile) { 1831 Remapper.flushToFile(MigrateDir, Ctx.getDiagnostics()); 1832 } else { 1833 Remapper.flushToDisk(MigrateDir, Ctx.getDiagnostics()); 1834 } 1835 } 1836 1837 bool MigrateSourceAction::BeginInvocation(CompilerInstance &CI) { 1838 CI.getDiagnostics().setIgnoreAllWarnings(true); 1839 return true; 1840 } 1841 1842 static std::vector<std::string> getWhiteListFilenames(StringRef DirPath) { 1843 using namespace llvm::sys::fs; 1844 using namespace llvm::sys::path; 1845 1846 std::vector<std::string> Filenames; 1847 if (DirPath.empty() || !is_directory(DirPath)) 1848 return Filenames; 1849 1850 std::error_code EC; 1851 directory_iterator DI = directory_iterator(DirPath, EC); 1852 directory_iterator DE; 1853 for (; !EC && DI != DE; DI = DI.increment(EC)) { 1854 if (is_regular_file(DI->path())) 1855 Filenames.push_back(filename(DI->path())); 1856 } 1857 1858 return Filenames; 1859 } 1860 1861 std::unique_ptr<ASTConsumer> 1862 MigrateSourceAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 1863 PPConditionalDirectiveRecord * 1864 PPRec = new PPConditionalDirectiveRecord(CI.getSourceManager()); 1865 unsigned ObjCMTAction = CI.getFrontendOpts().ObjCMTAction; 1866 unsigned ObjCMTOpts = ObjCMTAction; 1867 // These are companion flags, they do not enable transformations. 1868 ObjCMTOpts &= ~(FrontendOptions::ObjCMT_AtomicProperty | 1869 FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty); 1870 if (ObjCMTOpts == FrontendOptions::ObjCMT_None) { 1871 // If no specific option was given, enable literals+subscripting transforms 1872 // by default. 1873 ObjCMTAction |= FrontendOptions::ObjCMT_Literals | 1874 FrontendOptions::ObjCMT_Subscripting; 1875 } 1876 CI.getPreprocessor().addPPCallbacks(PPRec); 1877 std::vector<std::string> WhiteList = 1878 getWhiteListFilenames(CI.getFrontendOpts().ObjCMTWhiteListPath); 1879 return llvm::make_unique<ObjCMigrateASTConsumer>( 1880 CI.getFrontendOpts().OutputFile, ObjCMTAction, Remapper, 1881 CI.getFileManager(), PPRec, CI.getPreprocessor(), 1882 /*isOutputFile=*/true, WhiteList); 1883 } 1884 1885 namespace { 1886 struct EditEntry { 1887 const FileEntry *File; 1888 unsigned Offset; 1889 unsigned RemoveLen; 1890 std::string Text; 1891 1892 EditEntry() : File(), Offset(), RemoveLen() {} 1893 }; 1894 } 1895 1896 namespace llvm { 1897 template<> struct DenseMapInfo<EditEntry> { 1898 static inline EditEntry getEmptyKey() { 1899 EditEntry Entry; 1900 Entry.Offset = unsigned(-1); 1901 return Entry; 1902 } 1903 static inline EditEntry getTombstoneKey() { 1904 EditEntry Entry; 1905 Entry.Offset = unsigned(-2); 1906 return Entry; 1907 } 1908 static unsigned getHashValue(const EditEntry& Val) { 1909 llvm::FoldingSetNodeID ID; 1910 ID.AddPointer(Val.File); 1911 ID.AddInteger(Val.Offset); 1912 ID.AddInteger(Val.RemoveLen); 1913 ID.AddString(Val.Text); 1914 return ID.ComputeHash(); 1915 } 1916 static bool isEqual(const EditEntry &LHS, const EditEntry &RHS) { 1917 return LHS.File == RHS.File && 1918 LHS.Offset == RHS.Offset && 1919 LHS.RemoveLen == RHS.RemoveLen && 1920 LHS.Text == RHS.Text; 1921 } 1922 }; 1923 } 1924 1925 namespace { 1926 class RemapFileParser { 1927 FileManager &FileMgr; 1928 1929 public: 1930 RemapFileParser(FileManager &FileMgr) : FileMgr(FileMgr) { } 1931 1932 bool parse(StringRef File, SmallVectorImpl<EditEntry> &Entries) { 1933 using namespace llvm::yaml; 1934 1935 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr = 1936 llvm::MemoryBuffer::getFile(File); 1937 if (!FileBufOrErr) 1938 return true; 1939 1940 llvm::SourceMgr SM; 1941 Stream YAMLStream(std::move(*FileBufOrErr), SM); 1942 document_iterator I = YAMLStream.begin(); 1943 if (I == YAMLStream.end()) 1944 return true; 1945 Node *Root = I->getRoot(); 1946 if (!Root) 1947 return true; 1948 1949 SequenceNode *SeqNode = dyn_cast<SequenceNode>(Root); 1950 if (!SeqNode) 1951 return true; 1952 1953 for (SequenceNode::iterator 1954 AI = SeqNode->begin(), AE = SeqNode->end(); AI != AE; ++AI) { 1955 MappingNode *MapNode = dyn_cast<MappingNode>(&*AI); 1956 if (!MapNode) 1957 continue; 1958 parseEdit(MapNode, Entries); 1959 } 1960 1961 return false; 1962 } 1963 1964 private: 1965 void parseEdit(llvm::yaml::MappingNode *Node, 1966 SmallVectorImpl<EditEntry> &Entries) { 1967 using namespace llvm::yaml; 1968 EditEntry Entry; 1969 bool Ignore = false; 1970 1971 for (MappingNode::iterator 1972 KVI = Node->begin(), KVE = Node->end(); KVI != KVE; ++KVI) { 1973 ScalarNode *KeyString = dyn_cast<ScalarNode>((*KVI).getKey()); 1974 if (!KeyString) 1975 continue; 1976 SmallString<10> KeyStorage; 1977 StringRef Key = KeyString->getValue(KeyStorage); 1978 1979 ScalarNode *ValueString = dyn_cast<ScalarNode>((*KVI).getValue()); 1980 if (!ValueString) 1981 continue; 1982 SmallString<64> ValueStorage; 1983 StringRef Val = ValueString->getValue(ValueStorage); 1984 1985 if (Key == "file") { 1986 const FileEntry *FE = FileMgr.getFile(Val); 1987 if (!FE) 1988 Ignore = true; 1989 Entry.File = FE; 1990 } else if (Key == "offset") { 1991 if (Val.getAsInteger(10, Entry.Offset)) 1992 Ignore = true; 1993 } else if (Key == "remove") { 1994 if (Val.getAsInteger(10, Entry.RemoveLen)) 1995 Ignore = true; 1996 } else if (Key == "text") { 1997 Entry.Text = Val; 1998 } 1999 } 2000 2001 if (!Ignore) 2002 Entries.push_back(Entry); 2003 } 2004 }; 2005 } 2006 2007 static bool reportDiag(const Twine &Err, DiagnosticsEngine &Diag) { 2008 Diag.Report(Diag.getCustomDiagID(DiagnosticsEngine::Error, "%0")) 2009 << Err.str(); 2010 return true; 2011 } 2012 2013 static std::string applyEditsToTemp(const FileEntry *FE, 2014 ArrayRef<EditEntry> Edits, 2015 FileManager &FileMgr, 2016 DiagnosticsEngine &Diag) { 2017 using namespace llvm::sys; 2018 2019 SourceManager SM(Diag, FileMgr); 2020 FileID FID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User); 2021 LangOptions LangOpts; 2022 edit::EditedSource Editor(SM, LangOpts); 2023 for (ArrayRef<EditEntry>::iterator 2024 I = Edits.begin(), E = Edits.end(); I != E; ++I) { 2025 const EditEntry &Entry = *I; 2026 assert(Entry.File == FE); 2027 SourceLocation Loc = 2028 SM.getLocForStartOfFile(FID).getLocWithOffset(Entry.Offset); 2029 CharSourceRange Range; 2030 if (Entry.RemoveLen != 0) { 2031 Range = CharSourceRange::getCharRange(Loc, 2032 Loc.getLocWithOffset(Entry.RemoveLen)); 2033 } 2034 2035 edit::Commit commit(Editor); 2036 if (Range.isInvalid()) { 2037 commit.insert(Loc, Entry.Text); 2038 } else if (Entry.Text.empty()) { 2039 commit.remove(Range); 2040 } else { 2041 commit.replace(Range, Entry.Text); 2042 } 2043 Editor.commit(commit); 2044 } 2045 2046 Rewriter rewriter(SM, LangOpts); 2047 RewritesReceiver Rec(rewriter); 2048 Editor.applyRewrites(Rec); 2049 2050 const RewriteBuffer *Buf = rewriter.getRewriteBufferFor(FID); 2051 SmallString<512> NewText; 2052 llvm::raw_svector_ostream OS(NewText); 2053 Buf->write(OS); 2054 OS.flush(); 2055 2056 SmallString<64> TempPath; 2057 int FD; 2058 if (fs::createTemporaryFile(path::filename(FE->getName()), 2059 path::extension(FE->getName()), FD, 2060 TempPath)) { 2061 reportDiag("Could not create file: " + TempPath.str(), Diag); 2062 return std::string(); 2063 } 2064 2065 llvm::raw_fd_ostream TmpOut(FD, /*shouldClose=*/true); 2066 TmpOut.write(NewText.data(), NewText.size()); 2067 TmpOut.close(); 2068 2069 return TempPath.str(); 2070 } 2071 2072 bool arcmt::getFileRemappingsFromFileList( 2073 std::vector<std::pair<std::string,std::string> > &remap, 2074 ArrayRef<StringRef> remapFiles, 2075 DiagnosticConsumer *DiagClient) { 2076 bool hasErrorOccurred = false; 2077 2078 FileSystemOptions FSOpts; 2079 FileManager FileMgr(FSOpts); 2080 RemapFileParser Parser(FileMgr); 2081 2082 IntrusiveRefCntPtr<DiagnosticIDs> DiagID(new DiagnosticIDs()); 2083 IntrusiveRefCntPtr<DiagnosticsEngine> Diags( 2084 new DiagnosticsEngine(DiagID, new DiagnosticOptions, 2085 DiagClient, /*ShouldOwnClient=*/false)); 2086 2087 typedef llvm::DenseMap<const FileEntry *, std::vector<EditEntry> > 2088 FileEditEntriesTy; 2089 FileEditEntriesTy FileEditEntries; 2090 2091 llvm::DenseSet<EditEntry> EntriesSet; 2092 2093 for (ArrayRef<StringRef>::iterator 2094 I = remapFiles.begin(), E = remapFiles.end(); I != E; ++I) { 2095 SmallVector<EditEntry, 16> Entries; 2096 if (Parser.parse(*I, Entries)) 2097 continue; 2098 2099 for (SmallVectorImpl<EditEntry>::iterator 2100 EI = Entries.begin(), EE = Entries.end(); EI != EE; ++EI) { 2101 EditEntry &Entry = *EI; 2102 if (!Entry.File) 2103 continue; 2104 std::pair<llvm::DenseSet<EditEntry>::iterator, bool> 2105 Insert = EntriesSet.insert(Entry); 2106 if (!Insert.second) 2107 continue; 2108 2109 FileEditEntries[Entry.File].push_back(Entry); 2110 } 2111 } 2112 2113 for (FileEditEntriesTy::iterator 2114 I = FileEditEntries.begin(), E = FileEditEntries.end(); I != E; ++I) { 2115 std::string TempFile = applyEditsToTemp(I->first, I->second, 2116 FileMgr, *Diags); 2117 if (TempFile.empty()) { 2118 hasErrorOccurred = true; 2119 continue; 2120 } 2121 2122 remap.push_back(std::make_pair(I->first->getName(), TempFile)); 2123 } 2124 2125 return hasErrorOccurred; 2126 } 2127