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