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