1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===// 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 // This file implements semantic analysis for Objective C declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/DataRecursiveASTVisitor.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprObjC.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "clang/Sema/DeclSpec.h" 25 #include "clang/Sema/ExternalSemaSource.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/Scope.h" 28 #include "clang/Sema/ScopeInfo.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "TypeLocBuilder.h" 32 33 using namespace clang; 34 35 /// Check whether the given method, which must be in the 'init' 36 /// family, is a valid member of that family. 37 /// 38 /// \param receiverTypeIfCall - if null, check this as if declaring it; 39 /// if non-null, check this as if making a call to it with the given 40 /// receiver type 41 /// 42 /// \return true to indicate that there was an error and appropriate 43 /// actions were taken 44 bool Sema::checkInitMethod(ObjCMethodDecl *method, 45 QualType receiverTypeIfCall) { 46 if (method->isInvalidDecl()) return true; 47 48 // This castAs is safe: methods that don't return an object 49 // pointer won't be inferred as inits and will reject an explicit 50 // objc_method_family(init). 51 52 // We ignore protocols here. Should we? What about Class? 53 54 const ObjCObjectType *result = 55 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType(); 56 57 if (result->isObjCId()) { 58 return false; 59 } else if (result->isObjCClass()) { 60 // fall through: always an error 61 } else { 62 ObjCInterfaceDecl *resultClass = result->getInterface(); 63 assert(resultClass && "unexpected object type!"); 64 65 // It's okay for the result type to still be a forward declaration 66 // if we're checking an interface declaration. 67 if (!resultClass->hasDefinition()) { 68 if (receiverTypeIfCall.isNull() && 69 !isa<ObjCImplementationDecl>(method->getDeclContext())) 70 return false; 71 72 // Otherwise, we try to compare class types. 73 } else { 74 // If this method was declared in a protocol, we can't check 75 // anything unless we have a receiver type that's an interface. 76 const ObjCInterfaceDecl *receiverClass = nullptr; 77 if (isa<ObjCProtocolDecl>(method->getDeclContext())) { 78 if (receiverTypeIfCall.isNull()) 79 return false; 80 81 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>() 82 ->getInterfaceDecl(); 83 84 // This can be null for calls to e.g. id<Foo>. 85 if (!receiverClass) return false; 86 } else { 87 receiverClass = method->getClassInterface(); 88 assert(receiverClass && "method not associated with a class!"); 89 } 90 91 // If either class is a subclass of the other, it's fine. 92 if (receiverClass->isSuperClassOf(resultClass) || 93 resultClass->isSuperClassOf(receiverClass)) 94 return false; 95 } 96 } 97 98 SourceLocation loc = method->getLocation(); 99 100 // If we're in a system header, and this is not a call, just make 101 // the method unusable. 102 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) { 103 method->addAttr(UnavailableAttr::CreateImplicit(Context, 104 "init method returns a type unrelated to its receiver type", 105 loc)); 106 return true; 107 } 108 109 // Otherwise, it's an error. 110 Diag(loc, diag::err_arc_init_method_unrelated_result_type); 111 method->setInvalidDecl(); 112 return true; 113 } 114 115 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 116 const ObjCMethodDecl *Overridden) { 117 if (Overridden->hasRelatedResultType() && 118 !NewMethod->hasRelatedResultType()) { 119 // This can only happen when the method follows a naming convention that 120 // implies a related result type, and the original (overridden) method has 121 // a suitable return type, but the new (overriding) method does not have 122 // a suitable return type. 123 QualType ResultType = NewMethod->getReturnType(); 124 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange(); 125 126 // Figure out which class this method is part of, if any. 127 ObjCInterfaceDecl *CurrentClass 128 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext()); 129 if (!CurrentClass) { 130 DeclContext *DC = NewMethod->getDeclContext(); 131 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC)) 132 CurrentClass = Cat->getClassInterface(); 133 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC)) 134 CurrentClass = Impl->getClassInterface(); 135 else if (ObjCCategoryImplDecl *CatImpl 136 = dyn_cast<ObjCCategoryImplDecl>(DC)) 137 CurrentClass = CatImpl->getClassInterface(); 138 } 139 140 if (CurrentClass) { 141 Diag(NewMethod->getLocation(), 142 diag::warn_related_result_type_compatibility_class) 143 << Context.getObjCInterfaceType(CurrentClass) 144 << ResultType 145 << ResultTypeRange; 146 } else { 147 Diag(NewMethod->getLocation(), 148 diag::warn_related_result_type_compatibility_protocol) 149 << ResultType 150 << ResultTypeRange; 151 } 152 153 if (ObjCMethodFamily Family = Overridden->getMethodFamily()) 154 Diag(Overridden->getLocation(), 155 diag::note_related_result_type_family) 156 << /*overridden method*/ 0 157 << Family; 158 else 159 Diag(Overridden->getLocation(), 160 diag::note_related_result_type_overridden); 161 } 162 if (getLangOpts().ObjCAutoRefCount) { 163 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() != 164 Overridden->hasAttr<NSReturnsRetainedAttr>())) { 165 Diag(NewMethod->getLocation(), 166 diag::err_nsreturns_retained_attribute_mismatch) << 1; 167 Diag(Overridden->getLocation(), diag::note_previous_decl) 168 << "method"; 169 } 170 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() != 171 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) { 172 Diag(NewMethod->getLocation(), 173 diag::err_nsreturns_retained_attribute_mismatch) << 0; 174 Diag(Overridden->getLocation(), diag::note_previous_decl) 175 << "method"; 176 } 177 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(), 178 oe = Overridden->param_end(); 179 for (ObjCMethodDecl::param_iterator 180 ni = NewMethod->param_begin(), ne = NewMethod->param_end(); 181 ni != ne && oi != oe; ++ni, ++oi) { 182 const ParmVarDecl *oldDecl = (*oi); 183 ParmVarDecl *newDecl = (*ni); 184 if (newDecl->hasAttr<NSConsumedAttr>() != 185 oldDecl->hasAttr<NSConsumedAttr>()) { 186 Diag(newDecl->getLocation(), 187 diag::err_nsconsumed_attribute_mismatch); 188 Diag(oldDecl->getLocation(), diag::note_previous_decl) 189 << "parameter"; 190 } 191 } 192 } 193 } 194 195 /// \brief Check a method declaration for compatibility with the Objective-C 196 /// ARC conventions. 197 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) { 198 ObjCMethodFamily family = method->getMethodFamily(); 199 switch (family) { 200 case OMF_None: 201 case OMF_finalize: 202 case OMF_retain: 203 case OMF_release: 204 case OMF_autorelease: 205 case OMF_retainCount: 206 case OMF_self: 207 case OMF_initialize: 208 case OMF_performSelector: 209 return false; 210 211 case OMF_dealloc: 212 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) { 213 SourceRange ResultTypeRange = method->getReturnTypeSourceRange(); 214 if (ResultTypeRange.isInvalid()) 215 Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 216 << method->getReturnType() 217 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)"); 218 else 219 Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 220 << method->getReturnType() 221 << FixItHint::CreateReplacement(ResultTypeRange, "void"); 222 return true; 223 } 224 return false; 225 226 case OMF_init: 227 // If the method doesn't obey the init rules, don't bother annotating it. 228 if (checkInitMethod(method, QualType())) 229 return true; 230 231 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context)); 232 233 // Don't add a second copy of this attribute, but otherwise don't 234 // let it be suppressed. 235 if (method->hasAttr<NSReturnsRetainedAttr>()) 236 return false; 237 break; 238 239 case OMF_alloc: 240 case OMF_copy: 241 case OMF_mutableCopy: 242 case OMF_new: 243 if (method->hasAttr<NSReturnsRetainedAttr>() || 244 method->hasAttr<NSReturnsNotRetainedAttr>() || 245 method->hasAttr<NSReturnsAutoreleasedAttr>()) 246 return false; 247 break; 248 } 249 250 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context)); 251 return false; 252 } 253 254 static void DiagnoseObjCImplementedDeprecations(Sema &S, 255 NamedDecl *ND, 256 SourceLocation ImplLoc, 257 int select) { 258 if (ND && ND->isDeprecated()) { 259 S.Diag(ImplLoc, diag::warn_deprecated_def) << select; 260 if (select == 0) 261 S.Diag(ND->getLocation(), diag::note_method_declared_at) 262 << ND->getDeclName(); 263 else 264 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class"; 265 } 266 } 267 268 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 269 /// pool. 270 void Sema::AddAnyMethodToGlobalPool(Decl *D) { 271 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 272 273 // If we don't have a valid method decl, simply return. 274 if (!MDecl) 275 return; 276 if (MDecl->isInstanceMethod()) 277 AddInstanceMethodToGlobalPool(MDecl, true); 278 else 279 AddFactoryMethodToGlobalPool(MDecl, true); 280 } 281 282 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer 283 /// has explicit ownership attribute; false otherwise. 284 static bool 285 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { 286 QualType T = Param->getType(); 287 288 if (const PointerType *PT = T->getAs<PointerType>()) { 289 T = PT->getPointeeType(); 290 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 291 T = RT->getPointeeType(); 292 } else { 293 return true; 294 } 295 296 // If we have a lifetime qualifier, but it's local, we must have 297 // inferred it. So, it is implicit. 298 return !T.getLocalQualifiers().hasObjCLifetime(); 299 } 300 301 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible 302 /// and user declared, in the method definition's AST. 303 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { 304 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused"); 305 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 306 307 // If we don't have a valid method decl, simply return. 308 if (!MDecl) 309 return; 310 311 // Allow all of Sema to see that we are entering a method definition. 312 PushDeclContext(FnBodyScope, MDecl); 313 PushFunctionScope(); 314 315 // Create Decl objects for each parameter, entrring them in the scope for 316 // binding to their use. 317 318 // Insert the invisible arguments, self and _cmd! 319 MDecl->createImplicitParams(Context, MDecl->getClassInterface()); 320 321 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope); 322 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope); 323 324 // The ObjC parser requires parameter names so there's no need to check. 325 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(), 326 /*CheckParameterNames=*/false); 327 328 // Introduce all of the other parameters into this scope. 329 for (auto *Param : MDecl->params()) { 330 if (!Param->isInvalidDecl() && 331 getLangOpts().ObjCAutoRefCount && 332 !HasExplicitOwnershipAttr(*this, Param)) 333 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) << 334 Param->getType(); 335 336 if (Param->getIdentifier()) 337 PushOnScopeChains(Param, FnBodyScope); 338 } 339 340 // In ARC, disallow definition of retain/release/autorelease/retainCount 341 if (getLangOpts().ObjCAutoRefCount) { 342 switch (MDecl->getMethodFamily()) { 343 case OMF_retain: 344 case OMF_retainCount: 345 case OMF_release: 346 case OMF_autorelease: 347 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def) 348 << 0 << MDecl->getSelector(); 349 break; 350 351 case OMF_None: 352 case OMF_dealloc: 353 case OMF_finalize: 354 case OMF_alloc: 355 case OMF_init: 356 case OMF_mutableCopy: 357 case OMF_copy: 358 case OMF_new: 359 case OMF_self: 360 case OMF_initialize: 361 case OMF_performSelector: 362 break; 363 } 364 } 365 366 // Warn on deprecated methods under -Wdeprecated-implementations, 367 // and prepare for warning on missing super calls. 368 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) { 369 ObjCMethodDecl *IMD = 370 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()); 371 372 if (IMD) { 373 ObjCImplDecl *ImplDeclOfMethodDef = 374 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext()); 375 ObjCContainerDecl *ContDeclOfMethodDecl = 376 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext()); 377 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr; 378 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl)) 379 ImplDeclOfMethodDecl = OID->getImplementation(); 380 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) { 381 if (CD->IsClassExtension()) { 382 if (ObjCInterfaceDecl *OID = CD->getClassInterface()) 383 ImplDeclOfMethodDecl = OID->getImplementation(); 384 } else 385 ImplDeclOfMethodDecl = CD->getImplementation(); 386 } 387 // No need to issue deprecated warning if deprecated mehod in class/category 388 // is being implemented in its own implementation (no overriding is involved). 389 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef) 390 DiagnoseObjCImplementedDeprecations(*this, 391 dyn_cast<NamedDecl>(IMD), 392 MDecl->getLocation(), 0); 393 } 394 395 if (MDecl->getMethodFamily() == OMF_init) { 396 if (MDecl->isDesignatedInitializerForTheInterface()) { 397 getCurFunction()->ObjCIsDesignatedInit = true; 398 getCurFunction()->ObjCWarnForNoDesignatedInitChain = 399 IC->getSuperClass() != nullptr; 400 } else if (IC->hasDesignatedInitializers()) { 401 getCurFunction()->ObjCIsSecondaryInit = true; 402 getCurFunction()->ObjCWarnForNoInitDelegation = true; 403 } 404 } 405 406 // If this is "dealloc" or "finalize", set some bit here. 407 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false. 408 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set. 409 // Only do this if the current class actually has a superclass. 410 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) { 411 ObjCMethodFamily Family = MDecl->getMethodFamily(); 412 if (Family == OMF_dealloc) { 413 if (!(getLangOpts().ObjCAutoRefCount || 414 getLangOpts().getGC() == LangOptions::GCOnly)) 415 getCurFunction()->ObjCShouldCallSuper = true; 416 417 } else if (Family == OMF_finalize) { 418 if (Context.getLangOpts().getGC() != LangOptions::NonGC) 419 getCurFunction()->ObjCShouldCallSuper = true; 420 421 } else { 422 const ObjCMethodDecl *SuperMethod = 423 SuperClass->lookupMethod(MDecl->getSelector(), 424 MDecl->isInstanceMethod()); 425 getCurFunction()->ObjCShouldCallSuper = 426 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>()); 427 } 428 } 429 } 430 } 431 432 namespace { 433 434 // Callback to only accept typo corrections that are Objective-C classes. 435 // If an ObjCInterfaceDecl* is given to the constructor, then the validation 436 // function will reject corrections to that class. 437 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback { 438 public: 439 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {} 440 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl) 441 : CurrentIDecl(IDecl) {} 442 443 bool ValidateCandidate(const TypoCorrection &candidate) override { 444 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>(); 445 return ID && !declaresSameEntity(ID, CurrentIDecl); 446 } 447 448 private: 449 ObjCInterfaceDecl *CurrentIDecl; 450 }; 451 452 } 453 454 static void diagnoseUseOfProtocols(Sema &TheSema, 455 ObjCContainerDecl *CD, 456 ObjCProtocolDecl *const *ProtoRefs, 457 unsigned NumProtoRefs, 458 const SourceLocation *ProtoLocs) { 459 assert(ProtoRefs); 460 // Diagnose availability in the context of the ObjC container. 461 Sema::ContextRAII SavedContext(TheSema, CD); 462 for (unsigned i = 0; i < NumProtoRefs; ++i) { 463 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i]); 464 } 465 } 466 467 void Sema:: 468 ActOnSuperClassOfClassInterface(Scope *S, 469 SourceLocation AtInterfaceLoc, 470 ObjCInterfaceDecl *IDecl, 471 IdentifierInfo *ClassName, 472 SourceLocation ClassLoc, 473 IdentifierInfo *SuperName, 474 SourceLocation SuperLoc, 475 ArrayRef<ParsedType> SuperTypeArgs, 476 SourceRange SuperTypeArgsRange) { 477 // Check if a different kind of symbol declared in this scope. 478 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 479 LookupOrdinaryName); 480 481 if (!PrevDecl) { 482 // Try to correct for a typo in the superclass name without correcting 483 // to the class we're defining. 484 if (TypoCorrection Corrected = CorrectTypo( 485 DeclarationNameInfo(SuperName, SuperLoc), 486 LookupOrdinaryName, TUScope, 487 NULL, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl), 488 CTK_ErrorRecovery)) { 489 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest) 490 << SuperName << ClassName); 491 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>(); 492 } 493 } 494 495 if (declaresSameEntity(PrevDecl, IDecl)) { 496 Diag(SuperLoc, diag::err_recursive_superclass) 497 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 498 IDecl->setEndOfDefinitionLoc(ClassLoc); 499 } else { 500 ObjCInterfaceDecl *SuperClassDecl = 501 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 502 QualType SuperClassType; 503 504 // Diagnose classes that inherit from deprecated classes. 505 if (SuperClassDecl) { 506 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc); 507 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl); 508 } 509 510 if (PrevDecl && SuperClassDecl == 0) { 511 // The previous declaration was not a class decl. Check if we have a 512 // typedef. If we do, get the underlying class type. 513 if (const TypedefNameDecl *TDecl = 514 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 515 QualType T = TDecl->getUnderlyingType(); 516 if (T->isObjCObjectType()) { 517 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) { 518 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl); 519 SuperClassType = Context.getTypeDeclType(TDecl); 520 521 // This handles the following case: 522 // @interface NewI @end 523 // typedef NewI DeprI __attribute__((deprecated("blah"))) 524 // @interface SI : DeprI /* warn here */ @end 525 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc); 526 } 527 } 528 } 529 530 // This handles the following case: 531 // 532 // typedef int SuperClass; 533 // @interface MyClass : SuperClass {} @end 534 // 535 if (!SuperClassDecl) { 536 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName; 537 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 538 } 539 } 540 541 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 542 if (!SuperClassDecl) 543 Diag(SuperLoc, diag::err_undef_superclass) 544 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 545 else if (RequireCompleteType(SuperLoc, 546 SuperClassType, 547 diag::err_forward_superclass, 548 SuperClassDecl->getDeclName(), 549 ClassName, 550 SourceRange(AtInterfaceLoc, ClassLoc))) { 551 SuperClassDecl = 0; 552 SuperClassType = QualType(); 553 } 554 } 555 556 if (SuperClassType.isNull()) { 557 assert(!SuperClassDecl && "Failed to set SuperClassType?"); 558 return; 559 } 560 561 // Handle type arguments on the superclass. 562 TypeSourceInfo *SuperClassTInfo = nullptr; 563 if (!SuperTypeArgs.empty()) { 564 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers( 565 S, 566 SuperLoc, 567 CreateParsedType(SuperClassType, 568 nullptr), 569 SuperTypeArgsRange.getBegin(), 570 SuperTypeArgs, 571 SuperTypeArgsRange.getEnd(), 572 SourceLocation(), 573 { }, 574 { }, 575 SourceLocation()); 576 if (!fullSuperClassType.isUsable()) 577 return; 578 579 SuperClassType = GetTypeFromParser(fullSuperClassType.get(), 580 &SuperClassTInfo); 581 } 582 583 if (!SuperClassTInfo) { 584 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType, 585 SuperLoc); 586 } 587 588 IDecl->setSuperClass(SuperClassTInfo); 589 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd()); 590 } 591 } 592 593 DeclResult Sema::actOnObjCTypeParam(Scope *S, 594 ObjCTypeParamVariance variance, 595 SourceLocation varianceLoc, 596 unsigned index, 597 IdentifierInfo *paramName, 598 SourceLocation paramLoc, 599 SourceLocation colonLoc, 600 ParsedType parsedTypeBound) { 601 // If there was an explicitly-provided type bound, check it. 602 TypeSourceInfo *typeBoundInfo = nullptr; 603 if (parsedTypeBound) { 604 // The type bound can be any Objective-C pointer type. 605 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo); 606 if (typeBound->isObjCObjectPointerType()) { 607 // okay 608 } else if (typeBound->isObjCObjectType()) { 609 // The user forgot the * on an Objective-C pointer type, e.g., 610 // "T : NSView". 611 SourceLocation starLoc = PP.getLocForEndOfToken( 612 typeBoundInfo->getTypeLoc().getEndLoc()); 613 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(), 614 diag::err_objc_type_param_bound_missing_pointer) 615 << typeBound << paramName 616 << FixItHint::CreateInsertion(starLoc, " *"); 617 618 // Create a new type location builder so we can update the type 619 // location information we have. 620 TypeLocBuilder builder; 621 builder.pushFullCopy(typeBoundInfo->getTypeLoc()); 622 623 // Create the Objective-C pointer type. 624 typeBound = Context.getObjCObjectPointerType(typeBound); 625 ObjCObjectPointerTypeLoc newT 626 = builder.push<ObjCObjectPointerTypeLoc>(typeBound); 627 newT.setStarLoc(starLoc); 628 629 // Form the new type source information. 630 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound); 631 } else { 632 // Not a valid type bound. 633 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(), 634 diag::err_objc_type_param_bound_nonobject) 635 << typeBound << paramName; 636 637 // Forget the bound; we'll default to id later. 638 typeBoundInfo = nullptr; 639 } 640 641 // Type bounds cannot have qualifiers (even indirectly) or explicit 642 // nullability. 643 if (typeBoundInfo) { 644 QualType typeBound = typeBoundInfo->getType(); 645 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc(); 646 if (qual || typeBound.hasQualifiers()) { 647 bool diagnosed = false; 648 SourceRange rangeToRemove; 649 if (qual) { 650 if (auto attr = qual.getAs<AttributedTypeLoc>()) { 651 rangeToRemove = attr.getLocalSourceRange(); 652 if (attr.getTypePtr()->getImmediateNullability()) { 653 Diag(attr.getLocStart(), 654 diag::err_objc_type_param_bound_explicit_nullability) 655 << paramName << typeBound 656 << FixItHint::CreateRemoval(rangeToRemove); 657 diagnosed = true; 658 } 659 } 660 } 661 662 if (!diagnosed) { 663 Diag(qual ? qual.getLocStart() 664 : typeBoundInfo->getTypeLoc().getLocStart(), 665 diag::err_objc_type_param_bound_qualified) 666 << paramName << typeBound << typeBound.getQualifiers().getAsString() 667 << FixItHint::CreateRemoval(rangeToRemove); 668 } 669 670 // If the type bound has qualifiers other than CVR, we need to strip 671 // them or we'll probably assert later when trying to apply new 672 // qualifiers. 673 Qualifiers quals = typeBound.getQualifiers(); 674 quals.removeCVRQualifiers(); 675 if (!quals.empty()) { 676 typeBoundInfo = 677 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType()); 678 } 679 } 680 } 681 } 682 683 // If there was no explicit type bound (or we removed it due to an error), 684 // use 'id' instead. 685 if (!typeBoundInfo) { 686 colonLoc = SourceLocation(); 687 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType()); 688 } 689 690 // Create the type parameter. 691 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc, 692 index, paramLoc, paramName, colonLoc, 693 typeBoundInfo); 694 } 695 696 ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S, 697 SourceLocation lAngleLoc, 698 ArrayRef<Decl *> typeParamsIn, 699 SourceLocation rAngleLoc) { 700 // We know that the array only contains Objective-C type parameters. 701 ArrayRef<ObjCTypeParamDecl *> 702 typeParams( 703 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()), 704 typeParamsIn.size()); 705 706 // Diagnose redeclarations of type parameters. 707 // We do this now because Objective-C type parameters aren't pushed into 708 // scope until later (after the instance variable block), but we want the 709 // diagnostics to occur right after we parse the type parameter list. 710 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams; 711 for (auto typeParam : typeParams) { 712 auto known = knownParams.find(typeParam->getIdentifier()); 713 if (known != knownParams.end()) { 714 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl) 715 << typeParam->getIdentifier() 716 << SourceRange(known->second->getLocation()); 717 718 typeParam->setInvalidDecl(); 719 } else { 720 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam)); 721 722 // Push the type parameter into scope. 723 PushOnScopeChains(typeParam, S, /*AddToContext=*/false); 724 } 725 } 726 727 // Create the parameter list. 728 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc); 729 } 730 731 void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) { 732 for (auto typeParam : *typeParamList) { 733 if (!typeParam->isInvalidDecl()) { 734 S->RemoveDecl(typeParam); 735 IdResolver.RemoveDecl(typeParam); 736 } 737 } 738 } 739 740 namespace { 741 /// The context in which an Objective-C type parameter list occurs, for use 742 /// in diagnostics. 743 enum class TypeParamListContext { 744 ForwardDeclaration, 745 Definition, 746 Category, 747 Extension 748 }; 749 } 750 751 /// Check consistency between two Objective-C type parameter lists, e.g., 752 /// between a category/extension and an \@interface or between an \@class and an 753 /// \@interface. 754 static bool checkTypeParamListConsistency(Sema &S, 755 ObjCTypeParamList *prevTypeParams, 756 ObjCTypeParamList *newTypeParams, 757 TypeParamListContext newContext) { 758 // If the sizes don't match, complain about that. 759 if (prevTypeParams->size() != newTypeParams->size()) { 760 SourceLocation diagLoc; 761 if (newTypeParams->size() > prevTypeParams->size()) { 762 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation(); 763 } else { 764 diagLoc = S.PP.getLocForEndOfToken(newTypeParams->back()->getLocEnd()); 765 } 766 767 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch) 768 << static_cast<unsigned>(newContext) 769 << (newTypeParams->size() > prevTypeParams->size()) 770 << prevTypeParams->size() 771 << newTypeParams->size(); 772 773 return true; 774 } 775 776 // Match up the type parameters. 777 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) { 778 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i]; 779 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i]; 780 781 // Check for consistency of the variance. 782 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) { 783 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant && 784 newContext != TypeParamListContext::Definition) { 785 // When the new type parameter is invariant and is not part 786 // of the definition, just propagate the variance. 787 newTypeParam->setVariance(prevTypeParam->getVariance()); 788 } else if (prevTypeParam->getVariance() 789 == ObjCTypeParamVariance::Invariant && 790 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) && 791 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) 792 ->getDefinition() == prevTypeParam->getDeclContext())) { 793 // When the old parameter is invariant and was not part of the 794 // definition, just ignore the difference because it doesn't 795 // matter. 796 } else { 797 { 798 // Diagnose the conflict and update the second declaration. 799 SourceLocation diagLoc = newTypeParam->getVarianceLoc(); 800 if (diagLoc.isInvalid()) 801 diagLoc = newTypeParam->getLocStart(); 802 803 auto diag = S.Diag(diagLoc, 804 diag::err_objc_type_param_variance_conflict) 805 << static_cast<unsigned>(newTypeParam->getVariance()) 806 << newTypeParam->getDeclName() 807 << static_cast<unsigned>(prevTypeParam->getVariance()) 808 << prevTypeParam->getDeclName(); 809 switch (prevTypeParam->getVariance()) { 810 case ObjCTypeParamVariance::Invariant: 811 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc()); 812 break; 813 814 case ObjCTypeParamVariance::Covariant: 815 case ObjCTypeParamVariance::Contravariant: { 816 StringRef newVarianceStr 817 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant 818 ? "__covariant" 819 : "__contravariant"; 820 if (newTypeParam->getVariance() 821 == ObjCTypeParamVariance::Invariant) { 822 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(), 823 (newVarianceStr + " ").str()); 824 } else { 825 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(), 826 newVarianceStr); 827 } 828 } 829 } 830 } 831 832 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 833 << prevTypeParam->getDeclName(); 834 835 // Override the variance. 836 newTypeParam->setVariance(prevTypeParam->getVariance()); 837 } 838 } 839 840 // If the bound types match, there's nothing to do. 841 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(), 842 newTypeParam->getUnderlyingType())) 843 continue; 844 845 // If the new type parameter's bound was explicit, complain about it being 846 // different from the original. 847 if (newTypeParam->hasExplicitBound()) { 848 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo() 849 ->getTypeLoc().getSourceRange(); 850 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict) 851 << newTypeParam->getUnderlyingType() 852 << newTypeParam->getDeclName() 853 << prevTypeParam->hasExplicitBound() 854 << prevTypeParam->getUnderlyingType() 855 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName()) 856 << prevTypeParam->getDeclName() 857 << FixItHint::CreateReplacement( 858 newBoundRange, 859 prevTypeParam->getUnderlyingType().getAsString( 860 S.Context.getPrintingPolicy())); 861 862 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 863 << prevTypeParam->getDeclName(); 864 865 // Override the new type parameter's bound type with the previous type, 866 // so that it's consistent. 867 newTypeParam->setTypeSourceInfo( 868 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType())); 869 continue; 870 } 871 872 // The new type parameter got the implicit bound of 'id'. That's okay for 873 // categories and extensions (overwrite it later), but not for forward 874 // declarations and @interfaces, because those must be standalone. 875 if (newContext == TypeParamListContext::ForwardDeclaration || 876 newContext == TypeParamListContext::Definition) { 877 // Diagnose this problem for forward declarations and definitions. 878 SourceLocation insertionLoc 879 = S.PP.getLocForEndOfToken(newTypeParam->getLocation()); 880 std::string newCode 881 = " : " + prevTypeParam->getUnderlyingType().getAsString( 882 S.Context.getPrintingPolicy()); 883 S.Diag(newTypeParam->getLocation(), 884 diag::err_objc_type_param_bound_missing) 885 << prevTypeParam->getUnderlyingType() 886 << newTypeParam->getDeclName() 887 << (newContext == TypeParamListContext::ForwardDeclaration) 888 << FixItHint::CreateInsertion(insertionLoc, newCode); 889 890 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 891 << prevTypeParam->getDeclName(); 892 } 893 894 // Update the new type parameter's bound to match the previous one. 895 newTypeParam->setTypeSourceInfo( 896 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType())); 897 } 898 899 return false; 900 } 901 902 Decl *Sema:: 903 ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc, 904 IdentifierInfo *ClassName, SourceLocation ClassLoc, 905 ObjCTypeParamList *typeParamList, 906 IdentifierInfo *SuperName, SourceLocation SuperLoc, 907 ArrayRef<ParsedType> SuperTypeArgs, 908 SourceRange SuperTypeArgsRange, 909 Decl * const *ProtoRefs, unsigned NumProtoRefs, 910 const SourceLocation *ProtoLocs, 911 SourceLocation EndProtoLoc, AttributeList *AttrList) { 912 assert(ClassName && "Missing class identifier"); 913 914 // Check for another declaration kind with the same name. 915 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc, 916 LookupOrdinaryName, ForRedeclaration); 917 918 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 919 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 920 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 921 } 922 923 // Create a declaration to describe this @interface. 924 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 925 926 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 927 // A previous decl with a different name is because of 928 // @compatibility_alias, for example: 929 // \code 930 // @class NewImage; 931 // @compatibility_alias OldImage NewImage; 932 // \endcode 933 // A lookup for 'OldImage' will return the 'NewImage' decl. 934 // 935 // In such a case use the real declaration name, instead of the alias one, 936 // otherwise we will break IdentifierResolver and redecls-chain invariants. 937 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 938 // has been aliased. 939 ClassName = PrevIDecl->getIdentifier(); 940 } 941 942 // If there was a forward declaration with type parameters, check 943 // for consistency. 944 if (PrevIDecl) { 945 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) { 946 if (typeParamList) { 947 // Both have type parameter lists; check for consistency. 948 if (checkTypeParamListConsistency(*this, prevTypeParamList, 949 typeParamList, 950 TypeParamListContext::Definition)) { 951 typeParamList = nullptr; 952 } 953 } else { 954 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first) 955 << ClassName; 956 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl) 957 << ClassName; 958 959 // Clone the type parameter list. 960 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams; 961 for (auto typeParam : *prevTypeParamList) { 962 clonedTypeParams.push_back( 963 ObjCTypeParamDecl::Create( 964 Context, 965 CurContext, 966 typeParam->getVariance(), 967 SourceLocation(), 968 typeParam->getIndex(), 969 SourceLocation(), 970 typeParam->getIdentifier(), 971 SourceLocation(), 972 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType()))); 973 } 974 975 typeParamList = ObjCTypeParamList::create(Context, 976 SourceLocation(), 977 clonedTypeParams, 978 SourceLocation()); 979 } 980 } 981 } 982 983 ObjCInterfaceDecl *IDecl 984 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName, 985 typeParamList, PrevIDecl, ClassLoc); 986 if (PrevIDecl) { 987 // Class already seen. Was it a definition? 988 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 989 Diag(AtInterfaceLoc, diag::err_duplicate_class_def) 990 << PrevIDecl->getDeclName(); 991 Diag(Def->getLocation(), diag::note_previous_definition); 992 IDecl->setInvalidDecl(); 993 } 994 } 995 996 if (AttrList) 997 ProcessDeclAttributeList(TUScope, IDecl, AttrList); 998 PushOnScopeChains(IDecl, TUScope); 999 1000 // Start the definition of this class. If we're in a redefinition case, there 1001 // may already be a definition, so we'll end up adding to it. 1002 if (!IDecl->hasDefinition()) 1003 IDecl->startDefinition(); 1004 1005 if (SuperName) { 1006 // Diagnose availability in the context of the @interface. 1007 ContextRAII SavedContext(*this, IDecl); 1008 1009 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl, 1010 ClassName, ClassLoc, 1011 SuperName, SuperLoc, SuperTypeArgs, 1012 SuperTypeArgsRange); 1013 } else { // we have a root class. 1014 IDecl->setEndOfDefinitionLoc(ClassLoc); 1015 } 1016 1017 // Check then save referenced protocols. 1018 if (NumProtoRefs) { 1019 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1020 NumProtoRefs, ProtoLocs); 1021 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1022 ProtoLocs, Context); 1023 IDecl->setEndOfDefinitionLoc(EndProtoLoc); 1024 } 1025 1026 CheckObjCDeclScope(IDecl); 1027 return ActOnObjCContainerStartDefinition(IDecl); 1028 } 1029 1030 /// ActOnTypedefedProtocols - this action finds protocol list as part of the 1031 /// typedef'ed use for a qualified super class and adds them to the list 1032 /// of the protocols. 1033 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 1034 IdentifierInfo *SuperName, 1035 SourceLocation SuperLoc) { 1036 if (!SuperName) 1037 return; 1038 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 1039 LookupOrdinaryName); 1040 if (!IDecl) 1041 return; 1042 1043 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) { 1044 QualType T = TDecl->getUnderlyingType(); 1045 if (T->isObjCObjectType()) 1046 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) 1047 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end()); 1048 } 1049 } 1050 1051 /// ActOnCompatibilityAlias - this action is called after complete parsing of 1052 /// a \@compatibility_alias declaration. It sets up the alias relationships. 1053 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc, 1054 IdentifierInfo *AliasName, 1055 SourceLocation AliasLocation, 1056 IdentifierInfo *ClassName, 1057 SourceLocation ClassLocation) { 1058 // Look for previous declaration of alias name 1059 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation, 1060 LookupOrdinaryName, ForRedeclaration); 1061 if (ADecl) { 1062 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName; 1063 Diag(ADecl->getLocation(), diag::note_previous_declaration); 1064 return nullptr; 1065 } 1066 // Check for class declaration 1067 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 1068 LookupOrdinaryName, ForRedeclaration); 1069 if (const TypedefNameDecl *TDecl = 1070 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) { 1071 QualType T = TDecl->getUnderlyingType(); 1072 if (T->isObjCObjectType()) { 1073 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) { 1074 ClassName = IDecl->getIdentifier(); 1075 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 1076 LookupOrdinaryName, ForRedeclaration); 1077 } 1078 } 1079 } 1080 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU); 1081 if (!CDecl) { 1082 Diag(ClassLocation, diag::warn_undef_interface) << ClassName; 1083 if (CDeclU) 1084 Diag(CDeclU->getLocation(), diag::note_previous_declaration); 1085 return nullptr; 1086 } 1087 1088 // Everything checked out, instantiate a new alias declaration AST. 1089 ObjCCompatibleAliasDecl *AliasDecl = 1090 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl); 1091 1092 if (!CheckObjCDeclScope(AliasDecl)) 1093 PushOnScopeChains(AliasDecl, TUScope); 1094 1095 return AliasDecl; 1096 } 1097 1098 bool Sema::CheckForwardProtocolDeclarationForCircularDependency( 1099 IdentifierInfo *PName, 1100 SourceLocation &Ploc, SourceLocation PrevLoc, 1101 const ObjCList<ObjCProtocolDecl> &PList) { 1102 1103 bool res = false; 1104 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(), 1105 E = PList.end(); I != E; ++I) { 1106 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(), 1107 Ploc)) { 1108 if (PDecl->getIdentifier() == PName) { 1109 Diag(Ploc, diag::err_protocol_has_circular_dependency); 1110 Diag(PrevLoc, diag::note_previous_definition); 1111 res = true; 1112 } 1113 1114 if (!PDecl->hasDefinition()) 1115 continue; 1116 1117 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc, 1118 PDecl->getLocation(), PDecl->getReferencedProtocols())) 1119 res = true; 1120 } 1121 } 1122 return res; 1123 } 1124 1125 Decl * 1126 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc, 1127 IdentifierInfo *ProtocolName, 1128 SourceLocation ProtocolLoc, 1129 Decl * const *ProtoRefs, 1130 unsigned NumProtoRefs, 1131 const SourceLocation *ProtoLocs, 1132 SourceLocation EndProtoLoc, 1133 AttributeList *AttrList) { 1134 bool err = false; 1135 // FIXME: Deal with AttrList. 1136 assert(ProtocolName && "Missing protocol identifier"); 1137 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc, 1138 ForRedeclaration); 1139 ObjCProtocolDecl *PDecl = nullptr; 1140 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) { 1141 // If we already have a definition, complain. 1142 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName; 1143 Diag(Def->getLocation(), diag::note_previous_definition); 1144 1145 // Create a new protocol that is completely distinct from previous 1146 // declarations, and do not make this protocol available for name lookup. 1147 // That way, we'll end up completely ignoring the duplicate. 1148 // FIXME: Can we turn this into an error? 1149 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 1150 ProtocolLoc, AtProtoInterfaceLoc, 1151 /*PrevDecl=*/nullptr); 1152 PDecl->startDefinition(); 1153 } else { 1154 if (PrevDecl) { 1155 // Check for circular dependencies among protocol declarations. This can 1156 // only happen if this protocol was forward-declared. 1157 ObjCList<ObjCProtocolDecl> PList; 1158 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context); 1159 err = CheckForwardProtocolDeclarationForCircularDependency( 1160 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList); 1161 } 1162 1163 // Create the new declaration. 1164 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 1165 ProtocolLoc, AtProtoInterfaceLoc, 1166 /*PrevDecl=*/PrevDecl); 1167 1168 PushOnScopeChains(PDecl, TUScope); 1169 PDecl->startDefinition(); 1170 } 1171 1172 if (AttrList) 1173 ProcessDeclAttributeList(TUScope, PDecl, AttrList); 1174 1175 // Merge attributes from previous declarations. 1176 if (PrevDecl) 1177 mergeDeclAttributes(PDecl, PrevDecl); 1178 1179 if (!err && NumProtoRefs ) { 1180 /// Check then save referenced protocols. 1181 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1182 NumProtoRefs, ProtoLocs); 1183 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1184 ProtoLocs, Context); 1185 } 1186 1187 CheckObjCDeclScope(PDecl); 1188 return ActOnObjCContainerStartDefinition(PDecl); 1189 } 1190 1191 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl, 1192 ObjCProtocolDecl *&UndefinedProtocol) { 1193 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) { 1194 UndefinedProtocol = PDecl; 1195 return true; 1196 } 1197 1198 for (auto *PI : PDecl->protocols()) 1199 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) { 1200 UndefinedProtocol = PI; 1201 return true; 1202 } 1203 return false; 1204 } 1205 1206 /// FindProtocolDeclaration - This routine looks up protocols and 1207 /// issues an error if they are not declared. It returns list of 1208 /// protocol declarations in its 'Protocols' argument. 1209 void 1210 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, 1211 const IdentifierLocPair *ProtocolId, 1212 unsigned NumProtocols, 1213 SmallVectorImpl<Decl *> &Protocols) { 1214 for (unsigned i = 0; i != NumProtocols; ++i) { 1215 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first, 1216 ProtocolId[i].second); 1217 if (!PDecl) { 1218 TypoCorrection Corrected = CorrectTypo( 1219 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second), 1220 LookupObjCProtocolName, TUScope, nullptr, 1221 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(), 1222 CTK_ErrorRecovery); 1223 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) 1224 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest) 1225 << ProtocolId[i].first); 1226 } 1227 1228 if (!PDecl) { 1229 Diag(ProtocolId[i].second, diag::err_undeclared_protocol) 1230 << ProtocolId[i].first; 1231 continue; 1232 } 1233 // If this is a forward protocol declaration, get its definition. 1234 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition()) 1235 PDecl = PDecl->getDefinition(); 1236 1237 // For an objc container, delay protocol reference checking until after we 1238 // can set the objc decl as the availability context, otherwise check now. 1239 if (!ForObjCContainer) { 1240 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second); 1241 } 1242 1243 // If this is a forward declaration and we are supposed to warn in this 1244 // case, do it. 1245 // FIXME: Recover nicely in the hidden case. 1246 ObjCProtocolDecl *UndefinedProtocol; 1247 1248 if (WarnOnDeclarations && 1249 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) { 1250 Diag(ProtocolId[i].second, diag::warn_undef_protocolref) 1251 << ProtocolId[i].first; 1252 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined) 1253 << UndefinedProtocol; 1254 } 1255 Protocols.push_back(PDecl); 1256 } 1257 } 1258 1259 namespace { 1260 // Callback to only accept typo corrections that are either 1261 // Objective-C protocols or valid Objective-C type arguments. 1262 class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback { 1263 ASTContext &Context; 1264 Sema::LookupNameKind LookupKind; 1265 public: 1266 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context, 1267 Sema::LookupNameKind lookupKind) 1268 : Context(context), LookupKind(lookupKind) { } 1269 1270 bool ValidateCandidate(const TypoCorrection &candidate) override { 1271 // If we're allowed to find protocols and we have a protocol, accept it. 1272 if (LookupKind != Sema::LookupOrdinaryName) { 1273 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>()) 1274 return true; 1275 } 1276 1277 // If we're allowed to find type names and we have one, accept it. 1278 if (LookupKind != Sema::LookupObjCProtocolName) { 1279 // If we have a type declaration, we might accept this result. 1280 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) { 1281 // If we found a tag declaration outside of C++, skip it. This 1282 // can happy because we look for any name when there is no 1283 // bias to protocol or type names. 1284 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus) 1285 return false; 1286 1287 // Make sure the type is something we would accept as a type 1288 // argument. 1289 auto type = Context.getTypeDeclType(typeDecl); 1290 if (type->isObjCObjectPointerType() || 1291 type->isBlockPointerType() || 1292 type->isDependentType() || 1293 type->isObjCObjectType()) 1294 return true; 1295 1296 return false; 1297 } 1298 1299 // If we have an Objective-C class type, accept it; there will 1300 // be another fix to add the '*'. 1301 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>()) 1302 return true; 1303 1304 return false; 1305 } 1306 1307 return false; 1308 } 1309 }; 1310 } // end anonymous namespace 1311 1312 void Sema::actOnObjCTypeArgsOrProtocolQualifiers( 1313 Scope *S, 1314 ParsedType baseType, 1315 SourceLocation lAngleLoc, 1316 ArrayRef<IdentifierInfo *> identifiers, 1317 ArrayRef<SourceLocation> identifierLocs, 1318 SourceLocation rAngleLoc, 1319 SourceLocation &typeArgsLAngleLoc, 1320 SmallVectorImpl<ParsedType> &typeArgs, 1321 SourceLocation &typeArgsRAngleLoc, 1322 SourceLocation &protocolLAngleLoc, 1323 SmallVectorImpl<Decl *> &protocols, 1324 SourceLocation &protocolRAngleLoc, 1325 bool warnOnIncompleteProtocols) { 1326 // Local function that updates the declaration specifiers with 1327 // protocol information. 1328 unsigned numProtocolsResolved = 0; 1329 auto resolvedAsProtocols = [&] { 1330 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols"); 1331 1332 // Determine whether the base type is a parameterized class, in 1333 // which case we want to warn about typos such as 1334 // "NSArray<NSObject>" (that should be NSArray<NSObject *>). 1335 ObjCInterfaceDecl *baseClass = nullptr; 1336 QualType base = GetTypeFromParser(baseType, nullptr); 1337 bool allAreTypeNames = false; 1338 SourceLocation firstClassNameLoc; 1339 if (!base.isNull()) { 1340 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) { 1341 baseClass = objcObjectType->getInterface(); 1342 if (baseClass) { 1343 if (auto typeParams = baseClass->getTypeParamList()) { 1344 if (typeParams->size() == numProtocolsResolved) { 1345 // Note that we should be looking for type names, too. 1346 allAreTypeNames = true; 1347 } 1348 } 1349 } 1350 } 1351 } 1352 1353 for (unsigned i = 0, n = protocols.size(); i != n; ++i) { 1354 ObjCProtocolDecl *&proto 1355 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]); 1356 // For an objc container, delay protocol reference checking until after we 1357 // can set the objc decl as the availability context, otherwise check now. 1358 if (!warnOnIncompleteProtocols) { 1359 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]); 1360 } 1361 1362 // If this is a forward protocol declaration, get its definition. 1363 if (!proto->isThisDeclarationADefinition() && proto->getDefinition()) 1364 proto = proto->getDefinition(); 1365 1366 // If this is a forward declaration and we are supposed to warn in this 1367 // case, do it. 1368 // FIXME: Recover nicely in the hidden case. 1369 ObjCProtocolDecl *forwardDecl = nullptr; 1370 if (warnOnIncompleteProtocols && 1371 NestedProtocolHasNoDefinition(proto, forwardDecl)) { 1372 Diag(identifierLocs[i], diag::warn_undef_protocolref) 1373 << proto->getDeclName(); 1374 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined) 1375 << forwardDecl; 1376 } 1377 1378 // If everything this far has been a type name (and we care 1379 // about such things), check whether this name refers to a type 1380 // as well. 1381 if (allAreTypeNames) { 1382 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i], 1383 LookupOrdinaryName)) { 1384 if (isa<ObjCInterfaceDecl>(decl)) { 1385 if (firstClassNameLoc.isInvalid()) 1386 firstClassNameLoc = identifierLocs[i]; 1387 } else if (!isa<TypeDecl>(decl)) { 1388 // Not a type. 1389 allAreTypeNames = false; 1390 } 1391 } else { 1392 allAreTypeNames = false; 1393 } 1394 } 1395 } 1396 1397 // All of the protocols listed also have type names, and at least 1398 // one is an Objective-C class name. Check whether all of the 1399 // protocol conformances are declared by the base class itself, in 1400 // which case we warn. 1401 if (allAreTypeNames && firstClassNameLoc.isValid()) { 1402 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols; 1403 Context.CollectInheritedProtocols(baseClass, knownProtocols); 1404 bool allProtocolsDeclared = true; 1405 for (auto proto : protocols) { 1406 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) { 1407 allProtocolsDeclared = false; 1408 break; 1409 } 1410 } 1411 1412 if (allProtocolsDeclared) { 1413 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type) 1414 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc) 1415 << FixItHint::CreateInsertion( 1416 PP.getLocForEndOfToken(firstClassNameLoc), " *"); 1417 } 1418 } 1419 1420 protocolLAngleLoc = lAngleLoc; 1421 protocolRAngleLoc = rAngleLoc; 1422 assert(protocols.size() == identifierLocs.size()); 1423 }; 1424 1425 // Attempt to resolve all of the identifiers as protocols. 1426 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1427 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]); 1428 protocols.push_back(proto); 1429 if (proto) 1430 ++numProtocolsResolved; 1431 } 1432 1433 // If all of the names were protocols, these were protocol qualifiers. 1434 if (numProtocolsResolved == identifiers.size()) 1435 return resolvedAsProtocols(); 1436 1437 // Attempt to resolve all of the identifiers as type names or 1438 // Objective-C class names. The latter is technically ill-formed, 1439 // but is probably something like \c NSArray<NSView *> missing the 1440 // \c*. 1441 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl; 1442 SmallVector<TypeOrClassDecl, 4> typeDecls; 1443 unsigned numTypeDeclsResolved = 0; 1444 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1445 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i], 1446 LookupOrdinaryName); 1447 if (!decl) { 1448 typeDecls.push_back(TypeOrClassDecl()); 1449 continue; 1450 } 1451 1452 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) { 1453 typeDecls.push_back(typeDecl); 1454 ++numTypeDeclsResolved; 1455 continue; 1456 } 1457 1458 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) { 1459 typeDecls.push_back(objcClass); 1460 ++numTypeDeclsResolved; 1461 continue; 1462 } 1463 1464 typeDecls.push_back(TypeOrClassDecl()); 1465 } 1466 1467 AttributeFactory attrFactory; 1468 1469 // Local function that forms a reference to the given type or 1470 // Objective-C class declaration. 1471 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc) 1472 -> TypeResult { 1473 // Form declaration specifiers. They simply refer to the type. 1474 DeclSpec DS(attrFactory); 1475 const char* prevSpec; // unused 1476 unsigned diagID; // unused 1477 QualType type; 1478 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>()) 1479 type = Context.getTypeDeclType(actualTypeDecl); 1480 else 1481 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>()); 1482 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc); 1483 ParsedType parsedType = CreateParsedType(type, parsedTSInfo); 1484 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID, 1485 parsedType, Context.getPrintingPolicy()); 1486 // Use the identifier location for the type source range. 1487 DS.SetRangeStart(loc); 1488 DS.SetRangeEnd(loc); 1489 1490 // Form the declarator. 1491 Declarator D(DS, Declarator::TypeNameContext); 1492 1493 // If we have a typedef of an Objective-C class type that is missing a '*', 1494 // add the '*'. 1495 if (type->getAs<ObjCInterfaceType>()) { 1496 SourceLocation starLoc = PP.getLocForEndOfToken(loc); 1497 ParsedAttributes parsedAttrs(attrFactory); 1498 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc, 1499 SourceLocation(), 1500 SourceLocation(), 1501 SourceLocation(), 1502 SourceLocation()), 1503 parsedAttrs, 1504 starLoc); 1505 1506 // Diagnose the missing '*'. 1507 Diag(loc, diag::err_objc_type_arg_missing_star) 1508 << type 1509 << FixItHint::CreateInsertion(starLoc, " *"); 1510 } 1511 1512 // Convert this to a type. 1513 return ActOnTypeName(S, D); 1514 }; 1515 1516 // Local function that updates the declaration specifiers with 1517 // type argument information. 1518 auto resolvedAsTypeDecls = [&] { 1519 // We did not resolve these as protocols. 1520 protocols.clear(); 1521 1522 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl"); 1523 // Map type declarations to type arguments. 1524 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1525 // Map type reference to a type. 1526 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]); 1527 if (!type.isUsable()) { 1528 typeArgs.clear(); 1529 return; 1530 } 1531 1532 typeArgs.push_back(type.get()); 1533 } 1534 1535 typeArgsLAngleLoc = lAngleLoc; 1536 typeArgsRAngleLoc = rAngleLoc; 1537 }; 1538 1539 // If all of the identifiers can be resolved as type names or 1540 // Objective-C class names, we have type arguments. 1541 if (numTypeDeclsResolved == identifiers.size()) 1542 return resolvedAsTypeDecls(); 1543 1544 // Error recovery: some names weren't found, or we have a mix of 1545 // type and protocol names. Go resolve all of the unresolved names 1546 // and complain if we can't find a consistent answer. 1547 LookupNameKind lookupKind = LookupAnyName; 1548 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1549 // If we already have a protocol or type. Check whether it is the 1550 // right thing. 1551 if (protocols[i] || typeDecls[i]) { 1552 // If we haven't figured out whether we want types or protocols 1553 // yet, try to figure it out from this name. 1554 if (lookupKind == LookupAnyName) { 1555 // If this name refers to both a protocol and a type (e.g., \c 1556 // NSObject), don't conclude anything yet. 1557 if (protocols[i] && typeDecls[i]) 1558 continue; 1559 1560 // Otherwise, let this name decide whether we'll be correcting 1561 // toward types or protocols. 1562 lookupKind = protocols[i] ? LookupObjCProtocolName 1563 : LookupOrdinaryName; 1564 continue; 1565 } 1566 1567 // If we want protocols and we have a protocol, there's nothing 1568 // more to do. 1569 if (lookupKind == LookupObjCProtocolName && protocols[i]) 1570 continue; 1571 1572 // If we want types and we have a type declaration, there's 1573 // nothing more to do. 1574 if (lookupKind == LookupOrdinaryName && typeDecls[i]) 1575 continue; 1576 1577 // We have a conflict: some names refer to protocols and others 1578 // refer to types. 1579 Diag(identifierLocs[i], diag::err_objc_type_args_and_protocols) 1580 << (protocols[i] != nullptr) 1581 << identifiers[i] 1582 << identifiers[0] 1583 << SourceRange(identifierLocs[0]); 1584 1585 protocols.clear(); 1586 typeArgs.clear(); 1587 return; 1588 } 1589 1590 // Perform typo correction on the name. 1591 TypoCorrection corrected = CorrectTypo( 1592 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S, 1593 nullptr, 1594 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context, 1595 lookupKind), 1596 CTK_ErrorRecovery); 1597 if (corrected) { 1598 // Did we find a protocol? 1599 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) { 1600 diagnoseTypo(corrected, 1601 PDiag(diag::err_undeclared_protocol_suggest) 1602 << identifiers[i]); 1603 lookupKind = LookupObjCProtocolName; 1604 protocols[i] = proto; 1605 ++numProtocolsResolved; 1606 continue; 1607 } 1608 1609 // Did we find a type? 1610 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) { 1611 diagnoseTypo(corrected, 1612 PDiag(diag::err_unknown_typename_suggest) 1613 << identifiers[i]); 1614 lookupKind = LookupOrdinaryName; 1615 typeDecls[i] = typeDecl; 1616 ++numTypeDeclsResolved; 1617 continue; 1618 } 1619 1620 // Did we find an Objective-C class? 1621 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 1622 diagnoseTypo(corrected, 1623 PDiag(diag::err_unknown_type_or_class_name_suggest) 1624 << identifiers[i] << true); 1625 lookupKind = LookupOrdinaryName; 1626 typeDecls[i] = objcClass; 1627 ++numTypeDeclsResolved; 1628 continue; 1629 } 1630 } 1631 1632 // We couldn't find anything. 1633 Diag(identifierLocs[i], 1634 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing 1635 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol 1636 : diag::err_unknown_typename)) 1637 << identifiers[i]; 1638 protocols.clear(); 1639 typeArgs.clear(); 1640 return; 1641 } 1642 1643 // If all of the names were (corrected to) protocols, these were 1644 // protocol qualifiers. 1645 if (numProtocolsResolved == identifiers.size()) 1646 return resolvedAsProtocols(); 1647 1648 // Otherwise, all of the names were (corrected to) types. 1649 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?"); 1650 return resolvedAsTypeDecls(); 1651 } 1652 1653 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of 1654 /// a class method in its extension. 1655 /// 1656 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 1657 ObjCInterfaceDecl *ID) { 1658 if (!ID) 1659 return; // Possibly due to previous error 1660 1661 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap; 1662 for (auto *MD : ID->methods()) 1663 MethodMap[MD->getSelector()] = MD; 1664 1665 if (MethodMap.empty()) 1666 return; 1667 for (const auto *Method : CAT->methods()) { 1668 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()]; 1669 if (PrevMethod && 1670 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) && 1671 !MatchTwoMethodDeclarations(Method, PrevMethod)) { 1672 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 1673 << Method->getDeclName(); 1674 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 1675 } 1676 } 1677 } 1678 1679 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo; 1680 Sema::DeclGroupPtrTy 1681 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc, 1682 const IdentifierLocPair *IdentList, 1683 unsigned NumElts, 1684 AttributeList *attrList) { 1685 SmallVector<Decl *, 8> DeclsInGroup; 1686 for (unsigned i = 0; i != NumElts; ++i) { 1687 IdentifierInfo *Ident = IdentList[i].first; 1688 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second, 1689 ForRedeclaration); 1690 ObjCProtocolDecl *PDecl 1691 = ObjCProtocolDecl::Create(Context, CurContext, Ident, 1692 IdentList[i].second, AtProtocolLoc, 1693 PrevDecl); 1694 1695 PushOnScopeChains(PDecl, TUScope); 1696 CheckObjCDeclScope(PDecl); 1697 1698 if (attrList) 1699 ProcessDeclAttributeList(TUScope, PDecl, attrList); 1700 1701 if (PrevDecl) 1702 mergeDeclAttributes(PDecl, PrevDecl); 1703 1704 DeclsInGroup.push_back(PDecl); 1705 } 1706 1707 return BuildDeclaratorGroup(DeclsInGroup, false); 1708 } 1709 1710 Decl *Sema:: 1711 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 1712 IdentifierInfo *ClassName, SourceLocation ClassLoc, 1713 ObjCTypeParamList *typeParamList, 1714 IdentifierInfo *CategoryName, 1715 SourceLocation CategoryLoc, 1716 Decl * const *ProtoRefs, 1717 unsigned NumProtoRefs, 1718 const SourceLocation *ProtoLocs, 1719 SourceLocation EndProtoLoc) { 1720 ObjCCategoryDecl *CDecl; 1721 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 1722 1723 /// Check that class of this category is already completely declared. 1724 1725 if (!IDecl 1726 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1727 diag::err_category_forward_interface, 1728 CategoryName == nullptr)) { 1729 // Create an invalid ObjCCategoryDecl to serve as context for 1730 // the enclosing method declarations. We mark the decl invalid 1731 // to make it clear that this isn't a valid AST. 1732 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 1733 ClassLoc, CategoryLoc, CategoryName, 1734 IDecl, typeParamList); 1735 CDecl->setInvalidDecl(); 1736 CurContext->addDecl(CDecl); 1737 1738 if (!IDecl) 1739 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 1740 return ActOnObjCContainerStartDefinition(CDecl); 1741 } 1742 1743 if (!CategoryName && IDecl->getImplementation()) { 1744 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName; 1745 Diag(IDecl->getImplementation()->getLocation(), 1746 diag::note_implementation_declared); 1747 } 1748 1749 if (CategoryName) { 1750 /// Check for duplicate interface declaration for this category 1751 if (ObjCCategoryDecl *Previous 1752 = IDecl->FindCategoryDeclaration(CategoryName)) { 1753 // Class extensions can be declared multiple times, categories cannot. 1754 Diag(CategoryLoc, diag::warn_dup_category_def) 1755 << ClassName << CategoryName; 1756 Diag(Previous->getLocation(), diag::note_previous_definition); 1757 } 1758 } 1759 1760 // If we have a type parameter list, check it. 1761 if (typeParamList) { 1762 if (auto prevTypeParamList = IDecl->getTypeParamList()) { 1763 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList, 1764 CategoryName 1765 ? TypeParamListContext::Category 1766 : TypeParamListContext::Extension)) 1767 typeParamList = nullptr; 1768 } else { 1769 Diag(typeParamList->getLAngleLoc(), 1770 diag::err_objc_parameterized_category_nonclass) 1771 << (CategoryName != nullptr) 1772 << ClassName 1773 << typeParamList->getSourceRange(); 1774 1775 typeParamList = nullptr; 1776 } 1777 } 1778 1779 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 1780 ClassLoc, CategoryLoc, CategoryName, IDecl, 1781 typeParamList); 1782 // FIXME: PushOnScopeChains? 1783 CurContext->addDecl(CDecl); 1784 1785 if (NumProtoRefs) { 1786 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1787 NumProtoRefs, ProtoLocs); 1788 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1789 ProtoLocs, Context); 1790 // Protocols in the class extension belong to the class. 1791 if (CDecl->IsClassExtension()) 1792 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, 1793 NumProtoRefs, Context); 1794 } 1795 1796 CheckObjCDeclScope(CDecl); 1797 return ActOnObjCContainerStartDefinition(CDecl); 1798 } 1799 1800 /// ActOnStartCategoryImplementation - Perform semantic checks on the 1801 /// category implementation declaration and build an ObjCCategoryImplDecl 1802 /// object. 1803 Decl *Sema::ActOnStartCategoryImplementation( 1804 SourceLocation AtCatImplLoc, 1805 IdentifierInfo *ClassName, SourceLocation ClassLoc, 1806 IdentifierInfo *CatName, SourceLocation CatLoc) { 1807 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 1808 ObjCCategoryDecl *CatIDecl = nullptr; 1809 if (IDecl && IDecl->hasDefinition()) { 1810 CatIDecl = IDecl->FindCategoryDeclaration(CatName); 1811 if (!CatIDecl) { 1812 // Category @implementation with no corresponding @interface. 1813 // Create and install one. 1814 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc, 1815 ClassLoc, CatLoc, 1816 CatName, IDecl, 1817 /*typeParamList=*/nullptr); 1818 CatIDecl->setImplicit(); 1819 } 1820 } 1821 1822 ObjCCategoryImplDecl *CDecl = 1823 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl, 1824 ClassLoc, AtCatImplLoc, CatLoc); 1825 /// Check that class of this category is already completely declared. 1826 if (!IDecl) { 1827 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 1828 CDecl->setInvalidDecl(); 1829 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1830 diag::err_undef_interface)) { 1831 CDecl->setInvalidDecl(); 1832 } 1833 1834 // FIXME: PushOnScopeChains? 1835 CurContext->addDecl(CDecl); 1836 1837 // If the interface is deprecated/unavailable, warn/error about it. 1838 if (IDecl) 1839 DiagnoseUseOfDecl(IDecl, ClassLoc); 1840 1841 /// Check that CatName, category name, is not used in another implementation. 1842 if (CatIDecl) { 1843 if (CatIDecl->getImplementation()) { 1844 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName 1845 << CatName; 1846 Diag(CatIDecl->getImplementation()->getLocation(), 1847 diag::note_previous_definition); 1848 CDecl->setInvalidDecl(); 1849 } else { 1850 CatIDecl->setImplementation(CDecl); 1851 // Warn on implementating category of deprecated class under 1852 // -Wdeprecated-implementations flag. 1853 DiagnoseObjCImplementedDeprecations(*this, 1854 dyn_cast<NamedDecl>(IDecl), 1855 CDecl->getLocation(), 2); 1856 } 1857 } 1858 1859 CheckObjCDeclScope(CDecl); 1860 return ActOnObjCContainerStartDefinition(CDecl); 1861 } 1862 1863 Decl *Sema::ActOnStartClassImplementation( 1864 SourceLocation AtClassImplLoc, 1865 IdentifierInfo *ClassName, SourceLocation ClassLoc, 1866 IdentifierInfo *SuperClassname, 1867 SourceLocation SuperClassLoc) { 1868 ObjCInterfaceDecl *IDecl = nullptr; 1869 // Check for another declaration kind with the same name. 1870 NamedDecl *PrevDecl 1871 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName, 1872 ForRedeclaration); 1873 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1874 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 1875 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1876 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) { 1877 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1878 diag::warn_undef_interface); 1879 } else { 1880 // We did not find anything with the name ClassName; try to correct for 1881 // typos in the class name. 1882 TypoCorrection Corrected = CorrectTypo( 1883 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope, 1884 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError); 1885 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 1886 // Suggest the (potentially) correct interface name. Don't provide a 1887 // code-modification hint or use the typo name for recovery, because 1888 // this is just a warning. The program may actually be correct. 1889 diagnoseTypo(Corrected, 1890 PDiag(diag::warn_undef_interface_suggest) << ClassName, 1891 /*ErrorRecovery*/false); 1892 } else { 1893 Diag(ClassLoc, diag::warn_undef_interface) << ClassName; 1894 } 1895 } 1896 1897 // Check that super class name is valid class name 1898 ObjCInterfaceDecl *SDecl = nullptr; 1899 if (SuperClassname) { 1900 // Check if a different kind of symbol declared in this scope. 1901 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc, 1902 LookupOrdinaryName); 1903 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1904 Diag(SuperClassLoc, diag::err_redefinition_different_kind) 1905 << SuperClassname; 1906 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1907 } else { 1908 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 1909 if (SDecl && !SDecl->hasDefinition()) 1910 SDecl = nullptr; 1911 if (!SDecl) 1912 Diag(SuperClassLoc, diag::err_undef_superclass) 1913 << SuperClassname << ClassName; 1914 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) { 1915 // This implementation and its interface do not have the same 1916 // super class. 1917 Diag(SuperClassLoc, diag::err_conflicting_super_class) 1918 << SDecl->getDeclName(); 1919 Diag(SDecl->getLocation(), diag::note_previous_definition); 1920 } 1921 } 1922 } 1923 1924 if (!IDecl) { 1925 // Legacy case of @implementation with no corresponding @interface. 1926 // Build, chain & install the interface decl into the identifier. 1927 1928 // FIXME: Do we support attributes on the @implementation? If so we should 1929 // copy them over. 1930 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc, 1931 ClassName, /*typeParamList=*/nullptr, 1932 /*PrevDecl=*/nullptr, ClassLoc, 1933 true); 1934 IDecl->startDefinition(); 1935 if (SDecl) { 1936 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo( 1937 Context.getObjCInterfaceType(SDecl), 1938 SuperClassLoc)); 1939 IDecl->setEndOfDefinitionLoc(SuperClassLoc); 1940 } else { 1941 IDecl->setEndOfDefinitionLoc(ClassLoc); 1942 } 1943 1944 PushOnScopeChains(IDecl, TUScope); 1945 } else { 1946 // Mark the interface as being completed, even if it was just as 1947 // @class ....; 1948 // declaration; the user cannot reopen it. 1949 if (!IDecl->hasDefinition()) 1950 IDecl->startDefinition(); 1951 } 1952 1953 ObjCImplementationDecl* IMPDecl = 1954 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl, 1955 ClassLoc, AtClassImplLoc, SuperClassLoc); 1956 1957 if (CheckObjCDeclScope(IMPDecl)) 1958 return ActOnObjCContainerStartDefinition(IMPDecl); 1959 1960 // Check that there is no duplicate implementation of this class. 1961 if (IDecl->getImplementation()) { 1962 // FIXME: Don't leak everything! 1963 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName; 1964 Diag(IDecl->getImplementation()->getLocation(), 1965 diag::note_previous_definition); 1966 IMPDecl->setInvalidDecl(); 1967 } else { // add it to the list. 1968 IDecl->setImplementation(IMPDecl); 1969 PushOnScopeChains(IMPDecl, TUScope); 1970 // Warn on implementating deprecated class under 1971 // -Wdeprecated-implementations flag. 1972 DiagnoseObjCImplementedDeprecations(*this, 1973 dyn_cast<NamedDecl>(IDecl), 1974 IMPDecl->getLocation(), 1); 1975 } 1976 return ActOnObjCContainerStartDefinition(IMPDecl); 1977 } 1978 1979 Sema::DeclGroupPtrTy 1980 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) { 1981 SmallVector<Decl *, 64> DeclsInGroup; 1982 DeclsInGroup.reserve(Decls.size() + 1); 1983 1984 for (unsigned i = 0, e = Decls.size(); i != e; ++i) { 1985 Decl *Dcl = Decls[i]; 1986 if (!Dcl) 1987 continue; 1988 if (Dcl->getDeclContext()->isFileContext()) 1989 Dcl->setTopLevelDeclInObjCContainer(); 1990 DeclsInGroup.push_back(Dcl); 1991 } 1992 1993 DeclsInGroup.push_back(ObjCImpDecl); 1994 1995 return BuildDeclaratorGroup(DeclsInGroup, false); 1996 } 1997 1998 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 1999 ObjCIvarDecl **ivars, unsigned numIvars, 2000 SourceLocation RBrace) { 2001 assert(ImpDecl && "missing implementation decl"); 2002 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface(); 2003 if (!IDecl) 2004 return; 2005 /// Check case of non-existing \@interface decl. 2006 /// (legacy objective-c \@implementation decl without an \@interface decl). 2007 /// Add implementations's ivar to the synthesize class's ivar list. 2008 if (IDecl->isImplicitInterfaceDecl()) { 2009 IDecl->setEndOfDefinitionLoc(RBrace); 2010 // Add ivar's to class's DeclContext. 2011 for (unsigned i = 0, e = numIvars; i != e; ++i) { 2012 ivars[i]->setLexicalDeclContext(ImpDecl); 2013 IDecl->makeDeclVisibleInContext(ivars[i]); 2014 ImpDecl->addDecl(ivars[i]); 2015 } 2016 2017 return; 2018 } 2019 // If implementation has empty ivar list, just return. 2020 if (numIvars == 0) 2021 return; 2022 2023 assert(ivars && "missing @implementation ivars"); 2024 if (LangOpts.ObjCRuntime.isNonFragile()) { 2025 if (ImpDecl->getSuperClass()) 2026 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use); 2027 for (unsigned i = 0; i < numIvars; i++) { 2028 ObjCIvarDecl* ImplIvar = ivars[i]; 2029 if (const ObjCIvarDecl *ClsIvar = 2030 IDecl->getIvarDecl(ImplIvar->getIdentifier())) { 2031 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 2032 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2033 continue; 2034 } 2035 // Check class extensions (unnamed categories) for duplicate ivars. 2036 for (const auto *CDecl : IDecl->visible_extensions()) { 2037 if (const ObjCIvarDecl *ClsExtIvar = 2038 CDecl->getIvarDecl(ImplIvar->getIdentifier())) { 2039 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 2040 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 2041 continue; 2042 } 2043 } 2044 // Instance ivar to Implementation's DeclContext. 2045 ImplIvar->setLexicalDeclContext(ImpDecl); 2046 IDecl->makeDeclVisibleInContext(ImplIvar); 2047 ImpDecl->addDecl(ImplIvar); 2048 } 2049 return; 2050 } 2051 // Check interface's Ivar list against those in the implementation. 2052 // names and types must match. 2053 // 2054 unsigned j = 0; 2055 ObjCInterfaceDecl::ivar_iterator 2056 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end(); 2057 for (; numIvars > 0 && IVI != IVE; ++IVI) { 2058 ObjCIvarDecl* ImplIvar = ivars[j++]; 2059 ObjCIvarDecl* ClsIvar = *IVI; 2060 assert (ImplIvar && "missing implementation ivar"); 2061 assert (ClsIvar && "missing class ivar"); 2062 2063 // First, make sure the types match. 2064 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) { 2065 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type) 2066 << ImplIvar->getIdentifier() 2067 << ImplIvar->getType() << ClsIvar->getType(); 2068 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2069 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() && 2070 ImplIvar->getBitWidthValue(Context) != 2071 ClsIvar->getBitWidthValue(Context)) { 2072 Diag(ImplIvar->getBitWidth()->getLocStart(), 2073 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier(); 2074 Diag(ClsIvar->getBitWidth()->getLocStart(), 2075 diag::note_previous_definition); 2076 } 2077 // Make sure the names are identical. 2078 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) { 2079 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name) 2080 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier(); 2081 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2082 } 2083 --numIvars; 2084 } 2085 2086 if (numIvars > 0) 2087 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count); 2088 else if (IVI != IVE) 2089 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count); 2090 } 2091 2092 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc, 2093 ObjCMethodDecl *method, 2094 bool &IncompleteImpl, 2095 unsigned DiagID, 2096 NamedDecl *NeededFor = nullptr) { 2097 // No point warning no definition of method which is 'unavailable'. 2098 switch (method->getAvailability()) { 2099 case AR_Available: 2100 case AR_Deprecated: 2101 break; 2102 2103 // Don't warn about unavailable or not-yet-introduced methods. 2104 case AR_NotYetIntroduced: 2105 case AR_Unavailable: 2106 return; 2107 } 2108 2109 // FIXME: For now ignore 'IncompleteImpl'. 2110 // Previously we grouped all unimplemented methods under a single 2111 // warning, but some users strongly voiced that they would prefer 2112 // separate warnings. We will give that approach a try, as that 2113 // matches what we do with protocols. 2114 { 2115 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID); 2116 B << method; 2117 if (NeededFor) 2118 B << NeededFor; 2119 } 2120 2121 // Issue a note to the original declaration. 2122 SourceLocation MethodLoc = method->getLocStart(); 2123 if (MethodLoc.isValid()) 2124 S.Diag(MethodLoc, diag::note_method_declared_at) << method; 2125 } 2126 2127 /// Determines if type B can be substituted for type A. Returns true if we can 2128 /// guarantee that anything that the user will do to an object of type A can 2129 /// also be done to an object of type B. This is trivially true if the two 2130 /// types are the same, or if B is a subclass of A. It becomes more complex 2131 /// in cases where protocols are involved. 2132 /// 2133 /// Object types in Objective-C describe the minimum requirements for an 2134 /// object, rather than providing a complete description of a type. For 2135 /// example, if A is a subclass of B, then B* may refer to an instance of A. 2136 /// The principle of substitutability means that we may use an instance of A 2137 /// anywhere that we may use an instance of B - it will implement all of the 2138 /// ivars of B and all of the methods of B. 2139 /// 2140 /// This substitutability is important when type checking methods, because 2141 /// the implementation may have stricter type definitions than the interface. 2142 /// The interface specifies minimum requirements, but the implementation may 2143 /// have more accurate ones. For example, a method may privately accept 2144 /// instances of B, but only publish that it accepts instances of A. Any 2145 /// object passed to it will be type checked against B, and so will implicitly 2146 /// by a valid A*. Similarly, a method may return a subclass of the class that 2147 /// it is declared as returning. 2148 /// 2149 /// This is most important when considering subclassing. A method in a 2150 /// subclass must accept any object as an argument that its superclass's 2151 /// implementation accepts. It may, however, accept a more general type 2152 /// without breaking substitutability (i.e. you can still use the subclass 2153 /// anywhere that you can use the superclass, but not vice versa). The 2154 /// converse requirement applies to return types: the return type for a 2155 /// subclass method must be a valid object of the kind that the superclass 2156 /// advertises, but it may be specified more accurately. This avoids the need 2157 /// for explicit down-casting by callers. 2158 /// 2159 /// Note: This is a stricter requirement than for assignment. 2160 static bool isObjCTypeSubstitutable(ASTContext &Context, 2161 const ObjCObjectPointerType *A, 2162 const ObjCObjectPointerType *B, 2163 bool rejectId) { 2164 // Reject a protocol-unqualified id. 2165 if (rejectId && B->isObjCIdType()) return false; 2166 2167 // If B is a qualified id, then A must also be a qualified id and it must 2168 // implement all of the protocols in B. It may not be a qualified class. 2169 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a 2170 // stricter definition so it is not substitutable for id<A>. 2171 if (B->isObjCQualifiedIdType()) { 2172 return A->isObjCQualifiedIdType() && 2173 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0), 2174 QualType(B,0), 2175 false); 2176 } 2177 2178 /* 2179 // id is a special type that bypasses type checking completely. We want a 2180 // warning when it is used in one place but not another. 2181 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false; 2182 2183 2184 // If B is a qualified id, then A must also be a qualified id (which it isn't 2185 // if we've got this far) 2186 if (B->isObjCQualifiedIdType()) return false; 2187 */ 2188 2189 // Now we know that A and B are (potentially-qualified) class types. The 2190 // normal rules for assignment apply. 2191 return Context.canAssignObjCInterfaces(A, B); 2192 } 2193 2194 static SourceRange getTypeRange(TypeSourceInfo *TSI) { 2195 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange()); 2196 } 2197 2198 /// Determine whether two set of Objective-C declaration qualifiers conflict. 2199 static bool objcModifiersConflict(Decl::ObjCDeclQualifier x, 2200 Decl::ObjCDeclQualifier y) { 2201 return (x & ~Decl::OBJC_TQ_CSNullability) != 2202 (y & ~Decl::OBJC_TQ_CSNullability); 2203 } 2204 2205 static bool CheckMethodOverrideReturn(Sema &S, 2206 ObjCMethodDecl *MethodImpl, 2207 ObjCMethodDecl *MethodDecl, 2208 bool IsProtocolMethodDecl, 2209 bool IsOverridingMode, 2210 bool Warn) { 2211 if (IsProtocolMethodDecl && 2212 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(), 2213 MethodImpl->getObjCDeclQualifier())) { 2214 if (Warn) { 2215 S.Diag(MethodImpl->getLocation(), 2216 (IsOverridingMode 2217 ? diag::warn_conflicting_overriding_ret_type_modifiers 2218 : diag::warn_conflicting_ret_type_modifiers)) 2219 << MethodImpl->getDeclName() 2220 << MethodImpl->getReturnTypeSourceRange(); 2221 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration) 2222 << MethodDecl->getReturnTypeSourceRange(); 2223 } 2224 else 2225 return false; 2226 } 2227 if (Warn && IsOverridingMode && 2228 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) && 2229 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(), 2230 MethodDecl->getReturnType(), 2231 false)) { 2232 auto nullabilityMethodImpl = 2233 *MethodImpl->getReturnType()->getNullability(S.Context); 2234 auto nullabilityMethodDecl = 2235 *MethodDecl->getReturnType()->getNullability(S.Context); 2236 S.Diag(MethodImpl->getLocation(), 2237 diag::warn_conflicting_nullability_attr_overriding_ret_types) 2238 << DiagNullabilityKind( 2239 nullabilityMethodImpl, 2240 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2241 != 0)) 2242 << DiagNullabilityKind( 2243 nullabilityMethodDecl, 2244 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2245 != 0)); 2246 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 2247 } 2248 2249 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(), 2250 MethodDecl->getReturnType())) 2251 return true; 2252 if (!Warn) 2253 return false; 2254 2255 unsigned DiagID = 2256 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types 2257 : diag::warn_conflicting_ret_types; 2258 2259 // Mismatches between ObjC pointers go into a different warning 2260 // category, and sometimes they're even completely whitelisted. 2261 if (const ObjCObjectPointerType *ImplPtrTy = 2262 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) { 2263 if (const ObjCObjectPointerType *IfacePtrTy = 2264 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) { 2265 // Allow non-matching return types as long as they don't violate 2266 // the principle of substitutability. Specifically, we permit 2267 // return types that are subclasses of the declared return type, 2268 // or that are more-qualified versions of the declared type. 2269 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false)) 2270 return false; 2271 2272 DiagID = 2273 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types 2274 : diag::warn_non_covariant_ret_types; 2275 } 2276 } 2277 2278 S.Diag(MethodImpl->getLocation(), DiagID) 2279 << MethodImpl->getDeclName() << MethodDecl->getReturnType() 2280 << MethodImpl->getReturnType() 2281 << MethodImpl->getReturnTypeSourceRange(); 2282 S.Diag(MethodDecl->getLocation(), IsOverridingMode 2283 ? diag::note_previous_declaration 2284 : diag::note_previous_definition) 2285 << MethodDecl->getReturnTypeSourceRange(); 2286 return false; 2287 } 2288 2289 static bool CheckMethodOverrideParam(Sema &S, 2290 ObjCMethodDecl *MethodImpl, 2291 ObjCMethodDecl *MethodDecl, 2292 ParmVarDecl *ImplVar, 2293 ParmVarDecl *IfaceVar, 2294 bool IsProtocolMethodDecl, 2295 bool IsOverridingMode, 2296 bool Warn) { 2297 if (IsProtocolMethodDecl && 2298 objcModifiersConflict(ImplVar->getObjCDeclQualifier(), 2299 IfaceVar->getObjCDeclQualifier())) { 2300 if (Warn) { 2301 if (IsOverridingMode) 2302 S.Diag(ImplVar->getLocation(), 2303 diag::warn_conflicting_overriding_param_modifiers) 2304 << getTypeRange(ImplVar->getTypeSourceInfo()) 2305 << MethodImpl->getDeclName(); 2306 else S.Diag(ImplVar->getLocation(), 2307 diag::warn_conflicting_param_modifiers) 2308 << getTypeRange(ImplVar->getTypeSourceInfo()) 2309 << MethodImpl->getDeclName(); 2310 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration) 2311 << getTypeRange(IfaceVar->getTypeSourceInfo()); 2312 } 2313 else 2314 return false; 2315 } 2316 2317 QualType ImplTy = ImplVar->getType(); 2318 QualType IfaceTy = IfaceVar->getType(); 2319 if (Warn && IsOverridingMode && 2320 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) && 2321 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) { 2322 S.Diag(ImplVar->getLocation(), 2323 diag::warn_conflicting_nullability_attr_overriding_param_types) 2324 << DiagNullabilityKind( 2325 *ImplTy->getNullability(S.Context), 2326 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2327 != 0)) 2328 << DiagNullabilityKind( 2329 *IfaceTy->getNullability(S.Context), 2330 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2331 != 0)); 2332 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration); 2333 } 2334 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy)) 2335 return true; 2336 2337 if (!Warn) 2338 return false; 2339 unsigned DiagID = 2340 IsOverridingMode ? diag::warn_conflicting_overriding_param_types 2341 : diag::warn_conflicting_param_types; 2342 2343 // Mismatches between ObjC pointers go into a different warning 2344 // category, and sometimes they're even completely whitelisted. 2345 if (const ObjCObjectPointerType *ImplPtrTy = 2346 ImplTy->getAs<ObjCObjectPointerType>()) { 2347 if (const ObjCObjectPointerType *IfacePtrTy = 2348 IfaceTy->getAs<ObjCObjectPointerType>()) { 2349 // Allow non-matching argument types as long as they don't 2350 // violate the principle of substitutability. Specifically, the 2351 // implementation must accept any objects that the superclass 2352 // accepts, however it may also accept others. 2353 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true)) 2354 return false; 2355 2356 DiagID = 2357 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types 2358 : diag::warn_non_contravariant_param_types; 2359 } 2360 } 2361 2362 S.Diag(ImplVar->getLocation(), DiagID) 2363 << getTypeRange(ImplVar->getTypeSourceInfo()) 2364 << MethodImpl->getDeclName() << IfaceTy << ImplTy; 2365 S.Diag(IfaceVar->getLocation(), 2366 (IsOverridingMode ? diag::note_previous_declaration 2367 : diag::note_previous_definition)) 2368 << getTypeRange(IfaceVar->getTypeSourceInfo()); 2369 return false; 2370 } 2371 2372 /// In ARC, check whether the conventional meanings of the two methods 2373 /// match. If they don't, it's a hard error. 2374 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl, 2375 ObjCMethodDecl *decl) { 2376 ObjCMethodFamily implFamily = impl->getMethodFamily(); 2377 ObjCMethodFamily declFamily = decl->getMethodFamily(); 2378 if (implFamily == declFamily) return false; 2379 2380 // Since conventions are sorted by selector, the only possibility is 2381 // that the types differ enough to cause one selector or the other 2382 // to fall out of the family. 2383 assert(implFamily == OMF_None || declFamily == OMF_None); 2384 2385 // No further diagnostics required on invalid declarations. 2386 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true; 2387 2388 const ObjCMethodDecl *unmatched = impl; 2389 ObjCMethodFamily family = declFamily; 2390 unsigned errorID = diag::err_arc_lost_method_convention; 2391 unsigned noteID = diag::note_arc_lost_method_convention; 2392 if (declFamily == OMF_None) { 2393 unmatched = decl; 2394 family = implFamily; 2395 errorID = diag::err_arc_gained_method_convention; 2396 noteID = diag::note_arc_gained_method_convention; 2397 } 2398 2399 // Indexes into a %select clause in the diagnostic. 2400 enum FamilySelector { 2401 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new 2402 }; 2403 FamilySelector familySelector = FamilySelector(); 2404 2405 switch (family) { 2406 case OMF_None: llvm_unreachable("logic error, no method convention"); 2407 case OMF_retain: 2408 case OMF_release: 2409 case OMF_autorelease: 2410 case OMF_dealloc: 2411 case OMF_finalize: 2412 case OMF_retainCount: 2413 case OMF_self: 2414 case OMF_initialize: 2415 case OMF_performSelector: 2416 // Mismatches for these methods don't change ownership 2417 // conventions, so we don't care. 2418 return false; 2419 2420 case OMF_init: familySelector = F_init; break; 2421 case OMF_alloc: familySelector = F_alloc; break; 2422 case OMF_copy: familySelector = F_copy; break; 2423 case OMF_mutableCopy: familySelector = F_mutableCopy; break; 2424 case OMF_new: familySelector = F_new; break; 2425 } 2426 2427 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn }; 2428 ReasonSelector reasonSelector; 2429 2430 // The only reason these methods don't fall within their families is 2431 // due to unusual result types. 2432 if (unmatched->getReturnType()->isObjCObjectPointerType()) { 2433 reasonSelector = R_UnrelatedReturn; 2434 } else { 2435 reasonSelector = R_NonObjectReturn; 2436 } 2437 2438 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector); 2439 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector); 2440 2441 return true; 2442 } 2443 2444 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, 2445 ObjCMethodDecl *MethodDecl, 2446 bool IsProtocolMethodDecl) { 2447 if (getLangOpts().ObjCAutoRefCount && 2448 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)) 2449 return; 2450 2451 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 2452 IsProtocolMethodDecl, false, 2453 true); 2454 2455 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 2456 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 2457 EF = MethodDecl->param_end(); 2458 IM != EM && IF != EF; ++IM, ++IF) { 2459 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF, 2460 IsProtocolMethodDecl, false, true); 2461 } 2462 2463 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) { 2464 Diag(ImpMethodDecl->getLocation(), 2465 diag::warn_conflicting_variadic); 2466 Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 2467 } 2468 } 2469 2470 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 2471 ObjCMethodDecl *Overridden, 2472 bool IsProtocolMethodDecl) { 2473 2474 CheckMethodOverrideReturn(*this, Method, Overridden, 2475 IsProtocolMethodDecl, true, 2476 true); 2477 2478 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(), 2479 IF = Overridden->param_begin(), EM = Method->param_end(), 2480 EF = Overridden->param_end(); 2481 IM != EM && IF != EF; ++IM, ++IF) { 2482 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF, 2483 IsProtocolMethodDecl, true, true); 2484 } 2485 2486 if (Method->isVariadic() != Overridden->isVariadic()) { 2487 Diag(Method->getLocation(), 2488 diag::warn_conflicting_overriding_variadic); 2489 Diag(Overridden->getLocation(), diag::note_previous_declaration); 2490 } 2491 } 2492 2493 /// WarnExactTypedMethods - This routine issues a warning if method 2494 /// implementation declaration matches exactly that of its declaration. 2495 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, 2496 ObjCMethodDecl *MethodDecl, 2497 bool IsProtocolMethodDecl) { 2498 // don't issue warning when protocol method is optional because primary 2499 // class is not required to implement it and it is safe for protocol 2500 // to implement it. 2501 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional) 2502 return; 2503 // don't issue warning when primary class's method is 2504 // depecated/unavailable. 2505 if (MethodDecl->hasAttr<UnavailableAttr>() || 2506 MethodDecl->hasAttr<DeprecatedAttr>()) 2507 return; 2508 2509 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 2510 IsProtocolMethodDecl, false, false); 2511 if (match) 2512 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 2513 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 2514 EF = MethodDecl->param_end(); 2515 IM != EM && IF != EF; ++IM, ++IF) { 2516 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, 2517 *IM, *IF, 2518 IsProtocolMethodDecl, false, false); 2519 if (!match) 2520 break; 2521 } 2522 if (match) 2523 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic()); 2524 if (match) 2525 match = !(MethodDecl->isClassMethod() && 2526 MethodDecl->getSelector() == GetNullarySelector("load", Context)); 2527 2528 if (match) { 2529 Diag(ImpMethodDecl->getLocation(), 2530 diag::warn_category_method_impl_match); 2531 Diag(MethodDecl->getLocation(), diag::note_method_declared_at) 2532 << MethodDecl->getDeclName(); 2533 } 2534 } 2535 2536 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely 2537 /// improve the efficiency of selector lookups and type checking by associating 2538 /// with each protocol / interface / category the flattened instance tables. If 2539 /// we used an immutable set to keep the table then it wouldn't add significant 2540 /// memory cost and it would be handy for lookups. 2541 2542 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet; 2543 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet; 2544 2545 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl, 2546 ProtocolNameSet &PNS) { 2547 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) 2548 PNS.insert(PDecl->getIdentifier()); 2549 for (const auto *PI : PDecl->protocols()) 2550 findProtocolsWithExplicitImpls(PI, PNS); 2551 } 2552 2553 /// Recursively populates a set with all conformed protocols in a class 2554 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation' 2555 /// attribute. 2556 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super, 2557 ProtocolNameSet &PNS) { 2558 if (!Super) 2559 return; 2560 2561 for (const auto *I : Super->all_referenced_protocols()) 2562 findProtocolsWithExplicitImpls(I, PNS); 2563 2564 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS); 2565 } 2566 2567 /// CheckProtocolMethodDefs - This routine checks unimplemented methods 2568 /// Declared in protocol, and those referenced by it. 2569 static void CheckProtocolMethodDefs(Sema &S, 2570 SourceLocation ImpLoc, 2571 ObjCProtocolDecl *PDecl, 2572 bool& IncompleteImpl, 2573 const Sema::SelectorSet &InsMap, 2574 const Sema::SelectorSet &ClsMap, 2575 ObjCContainerDecl *CDecl, 2576 LazyProtocolNameSet &ProtocolsExplictImpl) { 2577 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); 2578 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() 2579 : dyn_cast<ObjCInterfaceDecl>(CDecl); 2580 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null"); 2581 2582 ObjCInterfaceDecl *Super = IDecl->getSuperClass(); 2583 ObjCInterfaceDecl *NSIDecl = nullptr; 2584 2585 // If this protocol is marked 'objc_protocol_requires_explicit_implementation' 2586 // then we should check if any class in the super class hierarchy also 2587 // conforms to this protocol, either directly or via protocol inheritance. 2588 // If so, we can skip checking this protocol completely because we 2589 // know that a parent class already satisfies this protocol. 2590 // 2591 // Note: we could generalize this logic for all protocols, and merely 2592 // add the limit on looking at the super class chain for just 2593 // specially marked protocols. This may be a good optimization. This 2594 // change is restricted to 'objc_protocol_requires_explicit_implementation' 2595 // protocols for now for controlled evaluation. 2596 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) { 2597 if (!ProtocolsExplictImpl) { 2598 ProtocolsExplictImpl.reset(new ProtocolNameSet); 2599 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl); 2600 } 2601 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) != 2602 ProtocolsExplictImpl->end()) 2603 return; 2604 2605 // If no super class conforms to the protocol, we should not search 2606 // for methods in the super class to implicitly satisfy the protocol. 2607 Super = nullptr; 2608 } 2609 2610 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) { 2611 // check to see if class implements forwardInvocation method and objects 2612 // of this class are derived from 'NSProxy' so that to forward requests 2613 // from one object to another. 2614 // Under such conditions, which means that every method possible is 2615 // implemented in the class, we should not issue "Method definition not 2616 // found" warnings. 2617 // FIXME: Use a general GetUnarySelector method for this. 2618 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation"); 2619 Selector fISelector = S.Context.Selectors.getSelector(1, &II); 2620 if (InsMap.count(fISelector)) 2621 // Is IDecl derived from 'NSProxy'? If so, no instance methods 2622 // need be implemented in the implementation. 2623 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy")); 2624 } 2625 2626 // If this is a forward protocol declaration, get its definition. 2627 if (!PDecl->isThisDeclarationADefinition() && 2628 PDecl->getDefinition()) 2629 PDecl = PDecl->getDefinition(); 2630 2631 // If a method lookup fails locally we still need to look and see if 2632 // the method was implemented by a base class or an inherited 2633 // protocol. This lookup is slow, but occurs rarely in correct code 2634 // and otherwise would terminate in a warning. 2635 2636 // check unimplemented instance methods. 2637 if (!NSIDecl) 2638 for (auto *method : PDecl->instance_methods()) { 2639 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 2640 !method->isPropertyAccessor() && 2641 !InsMap.count(method->getSelector()) && 2642 (!Super || !Super->lookupMethod(method->getSelector(), 2643 true /* instance */, 2644 false /* shallowCategory */, 2645 true /* followsSuper */, 2646 nullptr /* category */))) { 2647 // If a method is not implemented in the category implementation but 2648 // has been declared in its primary class, superclass, 2649 // or in one of their protocols, no need to issue the warning. 2650 // This is because method will be implemented in the primary class 2651 // or one of its super class implementation. 2652 2653 // Ugly, but necessary. Method declared in protcol might have 2654 // have been synthesized due to a property declared in the class which 2655 // uses the protocol. 2656 if (ObjCMethodDecl *MethodInClass = 2657 IDecl->lookupMethod(method->getSelector(), 2658 true /* instance */, 2659 true /* shallowCategoryLookup */, 2660 false /* followSuper */)) 2661 if (C || MethodInClass->isPropertyAccessor()) 2662 continue; 2663 unsigned DIAG = diag::warn_unimplemented_protocol_method; 2664 if (!S.Diags.isIgnored(DIAG, ImpLoc)) { 2665 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, 2666 PDecl); 2667 } 2668 } 2669 } 2670 // check unimplemented class methods 2671 for (auto *method : PDecl->class_methods()) { 2672 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 2673 !ClsMap.count(method->getSelector()) && 2674 (!Super || !Super->lookupMethod(method->getSelector(), 2675 false /* class method */, 2676 false /* shallowCategoryLookup */, 2677 true /* followSuper */, 2678 nullptr /* category */))) { 2679 // See above comment for instance method lookups. 2680 if (C && IDecl->lookupMethod(method->getSelector(), 2681 false /* class */, 2682 true /* shallowCategoryLookup */, 2683 false /* followSuper */)) 2684 continue; 2685 2686 unsigned DIAG = diag::warn_unimplemented_protocol_method; 2687 if (!S.Diags.isIgnored(DIAG, ImpLoc)) { 2688 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl); 2689 } 2690 } 2691 } 2692 // Check on this protocols's referenced protocols, recursively. 2693 for (auto *PI : PDecl->protocols()) 2694 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap, 2695 CDecl, ProtocolsExplictImpl); 2696 } 2697 2698 /// MatchAllMethodDeclarations - Check methods declared in interface 2699 /// or protocol against those declared in their implementations. 2700 /// 2701 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, 2702 const SelectorSet &ClsMap, 2703 SelectorSet &InsMapSeen, 2704 SelectorSet &ClsMapSeen, 2705 ObjCImplDecl* IMPDecl, 2706 ObjCContainerDecl* CDecl, 2707 bool &IncompleteImpl, 2708 bool ImmediateClass, 2709 bool WarnCategoryMethodImpl) { 2710 // Check and see if instance methods in class interface have been 2711 // implemented in the implementation class. If so, their types match. 2712 for (auto *I : CDecl->instance_methods()) { 2713 if (!InsMapSeen.insert(I->getSelector()).second) 2714 continue; 2715 if (!I->isPropertyAccessor() && 2716 !InsMap.count(I->getSelector())) { 2717 if (ImmediateClass) 2718 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl, 2719 diag::warn_undef_method_impl); 2720 continue; 2721 } else { 2722 ObjCMethodDecl *ImpMethodDecl = 2723 IMPDecl->getInstanceMethod(I->getSelector()); 2724 assert(CDecl->getInstanceMethod(I->getSelector()) && 2725 "Expected to find the method through lookup as well"); 2726 // ImpMethodDecl may be null as in a @dynamic property. 2727 if (ImpMethodDecl) { 2728 if (!WarnCategoryMethodImpl) 2729 WarnConflictingTypedMethods(ImpMethodDecl, I, 2730 isa<ObjCProtocolDecl>(CDecl)); 2731 else if (!I->isPropertyAccessor()) 2732 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl)); 2733 } 2734 } 2735 } 2736 2737 // Check and see if class methods in class interface have been 2738 // implemented in the implementation class. If so, their types match. 2739 for (auto *I : CDecl->class_methods()) { 2740 if (!ClsMapSeen.insert(I->getSelector()).second) 2741 continue; 2742 if (!ClsMap.count(I->getSelector())) { 2743 if (ImmediateClass) 2744 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl, 2745 diag::warn_undef_method_impl); 2746 } else { 2747 ObjCMethodDecl *ImpMethodDecl = 2748 IMPDecl->getClassMethod(I->getSelector()); 2749 assert(CDecl->getClassMethod(I->getSelector()) && 2750 "Expected to find the method through lookup as well"); 2751 if (!WarnCategoryMethodImpl) 2752 WarnConflictingTypedMethods(ImpMethodDecl, I, 2753 isa<ObjCProtocolDecl>(CDecl)); 2754 else 2755 WarnExactTypedMethods(ImpMethodDecl, I, 2756 isa<ObjCProtocolDecl>(CDecl)); 2757 } 2758 } 2759 2760 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) { 2761 // Also, check for methods declared in protocols inherited by 2762 // this protocol. 2763 for (auto *PI : PD->protocols()) 2764 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2765 IMPDecl, PI, IncompleteImpl, false, 2766 WarnCategoryMethodImpl); 2767 } 2768 2769 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 2770 // when checking that methods in implementation match their declaration, 2771 // i.e. when WarnCategoryMethodImpl is false, check declarations in class 2772 // extension; as well as those in categories. 2773 if (!WarnCategoryMethodImpl) { 2774 for (auto *Cat : I->visible_categories()) 2775 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2776 IMPDecl, Cat, IncompleteImpl, false, 2777 WarnCategoryMethodImpl); 2778 } else { 2779 // Also methods in class extensions need be looked at next. 2780 for (auto *Ext : I->visible_extensions()) 2781 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2782 IMPDecl, Ext, IncompleteImpl, false, 2783 WarnCategoryMethodImpl); 2784 } 2785 2786 // Check for any implementation of a methods declared in protocol. 2787 for (auto *PI : I->all_referenced_protocols()) 2788 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2789 IMPDecl, PI, IncompleteImpl, false, 2790 WarnCategoryMethodImpl); 2791 2792 // FIXME. For now, we are not checking for extact match of methods 2793 // in category implementation and its primary class's super class. 2794 if (!WarnCategoryMethodImpl && I->getSuperClass()) 2795 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2796 IMPDecl, 2797 I->getSuperClass(), IncompleteImpl, false); 2798 } 2799 } 2800 2801 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 2802 /// category matches with those implemented in its primary class and 2803 /// warns each time an exact match is found. 2804 void Sema::CheckCategoryVsClassMethodMatches( 2805 ObjCCategoryImplDecl *CatIMPDecl) { 2806 // Get category's primary class. 2807 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl(); 2808 if (!CatDecl) 2809 return; 2810 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface(); 2811 if (!IDecl) 2812 return; 2813 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass(); 2814 SelectorSet InsMap, ClsMap; 2815 2816 for (const auto *I : CatIMPDecl->instance_methods()) { 2817 Selector Sel = I->getSelector(); 2818 // When checking for methods implemented in the category, skip over 2819 // those declared in category class's super class. This is because 2820 // the super class must implement the method. 2821 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true)) 2822 continue; 2823 InsMap.insert(Sel); 2824 } 2825 2826 for (const auto *I : CatIMPDecl->class_methods()) { 2827 Selector Sel = I->getSelector(); 2828 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false)) 2829 continue; 2830 ClsMap.insert(Sel); 2831 } 2832 if (InsMap.empty() && ClsMap.empty()) 2833 return; 2834 2835 SelectorSet InsMapSeen, ClsMapSeen; 2836 bool IncompleteImpl = false; 2837 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2838 CatIMPDecl, IDecl, 2839 IncompleteImpl, false, 2840 true /*WarnCategoryMethodImpl*/); 2841 } 2842 2843 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 2844 ObjCContainerDecl* CDecl, 2845 bool IncompleteImpl) { 2846 SelectorSet InsMap; 2847 // Check and see if instance methods in class interface have been 2848 // implemented in the implementation class. 2849 for (const auto *I : IMPDecl->instance_methods()) 2850 InsMap.insert(I->getSelector()); 2851 2852 // Check and see if properties declared in the interface have either 1) 2853 // an implementation or 2) there is a @synthesize/@dynamic implementation 2854 // of the property in the @implementation. 2855 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2856 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties && 2857 LangOpts.ObjCRuntime.isNonFragile() && 2858 !IDecl->isObjCRequiresPropertyDefs(); 2859 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties); 2860 } 2861 2862 // Diagnose null-resettable synthesized setters. 2863 diagnoseNullResettableSynthesizedSetters(IMPDecl); 2864 2865 SelectorSet ClsMap; 2866 for (const auto *I : IMPDecl->class_methods()) 2867 ClsMap.insert(I->getSelector()); 2868 2869 // Check for type conflict of methods declared in a class/protocol and 2870 // its implementation; if any. 2871 SelectorSet InsMapSeen, ClsMapSeen; 2872 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2873 IMPDecl, CDecl, 2874 IncompleteImpl, true); 2875 2876 // check all methods implemented in category against those declared 2877 // in its primary class. 2878 if (ObjCCategoryImplDecl *CatDecl = 2879 dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) 2880 CheckCategoryVsClassMethodMatches(CatDecl); 2881 2882 // Check the protocol list for unimplemented methods in the @implementation 2883 // class. 2884 // Check and see if class methods in class interface have been 2885 // implemented in the implementation class. 2886 2887 LazyProtocolNameSet ExplicitImplProtocols; 2888 2889 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 2890 for (auto *PI : I->all_referenced_protocols()) 2891 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl, 2892 InsMap, ClsMap, I, ExplicitImplProtocols); 2893 // Check class extensions (unnamed categories) 2894 for (auto *Ext : I->visible_extensions()) 2895 ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl); 2896 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2897 // For extended class, unimplemented methods in its protocols will 2898 // be reported in the primary class. 2899 if (!C->IsClassExtension()) { 2900 for (auto *P : C->protocols()) 2901 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P, 2902 IncompleteImpl, InsMap, ClsMap, CDecl, 2903 ExplicitImplProtocols); 2904 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, 2905 /*SynthesizeProperties=*/false); 2906 } 2907 } else 2908 llvm_unreachable("invalid ObjCContainerDecl type."); 2909 } 2910 2911 Sema::DeclGroupPtrTy 2912 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, 2913 IdentifierInfo **IdentList, 2914 SourceLocation *IdentLocs, 2915 ArrayRef<ObjCTypeParamList *> TypeParamLists, 2916 unsigned NumElts) { 2917 SmallVector<Decl *, 8> DeclsInGroup; 2918 for (unsigned i = 0; i != NumElts; ++i) { 2919 // Check for another declaration kind with the same name. 2920 NamedDecl *PrevDecl 2921 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 2922 LookupOrdinaryName, ForRedeclaration); 2923 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 2924 // GCC apparently allows the following idiom: 2925 // 2926 // typedef NSObject < XCElementTogglerP > XCElementToggler; 2927 // @class XCElementToggler; 2928 // 2929 // Here we have chosen to ignore the forward class declaration 2930 // with a warning. Since this is the implied behavior. 2931 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl); 2932 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) { 2933 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; 2934 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2935 } else { 2936 // a forward class declaration matching a typedef name of a class refers 2937 // to the underlying class. Just ignore the forward class with a warning 2938 // as this will force the intended behavior which is to lookup the 2939 // typedef name. 2940 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) { 2941 Diag(AtClassLoc, diag::warn_forward_class_redefinition) 2942 << IdentList[i]; 2943 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2944 continue; 2945 } 2946 } 2947 } 2948 2949 // Create a declaration to describe this forward declaration. 2950 ObjCInterfaceDecl *PrevIDecl 2951 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 2952 2953 IdentifierInfo *ClassName = IdentList[i]; 2954 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 2955 // A previous decl with a different name is because of 2956 // @compatibility_alias, for example: 2957 // \code 2958 // @class NewImage; 2959 // @compatibility_alias OldImage NewImage; 2960 // \endcode 2961 // A lookup for 'OldImage' will return the 'NewImage' decl. 2962 // 2963 // In such a case use the real declaration name, instead of the alias one, 2964 // otherwise we will break IdentifierResolver and redecls-chain invariants. 2965 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 2966 // has been aliased. 2967 ClassName = PrevIDecl->getIdentifier(); 2968 } 2969 2970 // If this forward declaration has type parameters, compare them with the 2971 // type parameters of the previous declaration. 2972 ObjCTypeParamList *TypeParams = TypeParamLists[i]; 2973 if (PrevIDecl && TypeParams) { 2974 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) { 2975 // Check for consistency with the previous declaration. 2976 if (checkTypeParamListConsistency( 2977 *this, PrevTypeParams, TypeParams, 2978 TypeParamListContext::ForwardDeclaration)) { 2979 TypeParams = nullptr; 2980 } 2981 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 2982 // The @interface does not have type parameters. Complain. 2983 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class) 2984 << ClassName 2985 << TypeParams->getSourceRange(); 2986 Diag(Def->getLocation(), diag::note_defined_here) 2987 << ClassName; 2988 2989 TypeParams = nullptr; 2990 } 2991 } 2992 2993 ObjCInterfaceDecl *IDecl 2994 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, 2995 ClassName, TypeParams, PrevIDecl, 2996 IdentLocs[i]); 2997 IDecl->setAtEndRange(IdentLocs[i]); 2998 2999 PushOnScopeChains(IDecl, TUScope); 3000 CheckObjCDeclScope(IDecl); 3001 DeclsInGroup.push_back(IDecl); 3002 } 3003 3004 return BuildDeclaratorGroup(DeclsInGroup, false); 3005 } 3006 3007 static bool tryMatchRecordTypes(ASTContext &Context, 3008 Sema::MethodMatchStrategy strategy, 3009 const Type *left, const Type *right); 3010 3011 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, 3012 QualType leftQT, QualType rightQT) { 3013 const Type *left = 3014 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr(); 3015 const Type *right = 3016 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr(); 3017 3018 if (left == right) return true; 3019 3020 // If we're doing a strict match, the types have to match exactly. 3021 if (strategy == Sema::MMS_strict) return false; 3022 3023 if (left->isIncompleteType() || right->isIncompleteType()) return false; 3024 3025 // Otherwise, use this absurdly complicated algorithm to try to 3026 // validate the basic, low-level compatibility of the two types. 3027 3028 // As a minimum, require the sizes and alignments to match. 3029 TypeInfo LeftTI = Context.getTypeInfo(left); 3030 TypeInfo RightTI = Context.getTypeInfo(right); 3031 if (LeftTI.Width != RightTI.Width) 3032 return false; 3033 3034 if (LeftTI.Align != RightTI.Align) 3035 return false; 3036 3037 // Consider all the kinds of non-dependent canonical types: 3038 // - functions and arrays aren't possible as return and parameter types 3039 3040 // - vector types of equal size can be arbitrarily mixed 3041 if (isa<VectorType>(left)) return isa<VectorType>(right); 3042 if (isa<VectorType>(right)) return false; 3043 3044 // - references should only match references of identical type 3045 // - structs, unions, and Objective-C objects must match more-or-less 3046 // exactly 3047 // - everything else should be a scalar 3048 if (!left->isScalarType() || !right->isScalarType()) 3049 return tryMatchRecordTypes(Context, strategy, left, right); 3050 3051 // Make scalars agree in kind, except count bools as chars, and group 3052 // all non-member pointers together. 3053 Type::ScalarTypeKind leftSK = left->getScalarTypeKind(); 3054 Type::ScalarTypeKind rightSK = right->getScalarTypeKind(); 3055 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral; 3056 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral; 3057 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer) 3058 leftSK = Type::STK_ObjCObjectPointer; 3059 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer) 3060 rightSK = Type::STK_ObjCObjectPointer; 3061 3062 // Note that data member pointers and function member pointers don't 3063 // intermix because of the size differences. 3064 3065 return (leftSK == rightSK); 3066 } 3067 3068 static bool tryMatchRecordTypes(ASTContext &Context, 3069 Sema::MethodMatchStrategy strategy, 3070 const Type *lt, const Type *rt) { 3071 assert(lt && rt && lt != rt); 3072 3073 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false; 3074 RecordDecl *left = cast<RecordType>(lt)->getDecl(); 3075 RecordDecl *right = cast<RecordType>(rt)->getDecl(); 3076 3077 // Require union-hood to match. 3078 if (left->isUnion() != right->isUnion()) return false; 3079 3080 // Require an exact match if either is non-POD. 3081 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) || 3082 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD())) 3083 return false; 3084 3085 // Require size and alignment to match. 3086 TypeInfo LeftTI = Context.getTypeInfo(lt); 3087 TypeInfo RightTI = Context.getTypeInfo(rt); 3088 if (LeftTI.Width != RightTI.Width) 3089 return false; 3090 3091 if (LeftTI.Align != RightTI.Align) 3092 return false; 3093 3094 // Require fields to match. 3095 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end(); 3096 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end(); 3097 for (; li != le && ri != re; ++li, ++ri) { 3098 if (!matchTypes(Context, strategy, li->getType(), ri->getType())) 3099 return false; 3100 } 3101 return (li == le && ri == re); 3102 } 3103 3104 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and 3105 /// returns true, or false, accordingly. 3106 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons 3107 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left, 3108 const ObjCMethodDecl *right, 3109 MethodMatchStrategy strategy) { 3110 if (!matchTypes(Context, strategy, left->getReturnType(), 3111 right->getReturnType())) 3112 return false; 3113 3114 // If either is hidden, it is not considered to match. 3115 if (left->isHidden() || right->isHidden()) 3116 return false; 3117 3118 if (getLangOpts().ObjCAutoRefCount && 3119 (left->hasAttr<NSReturnsRetainedAttr>() 3120 != right->hasAttr<NSReturnsRetainedAttr>() || 3121 left->hasAttr<NSConsumesSelfAttr>() 3122 != right->hasAttr<NSConsumesSelfAttr>())) 3123 return false; 3124 3125 ObjCMethodDecl::param_const_iterator 3126 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(), 3127 re = right->param_end(); 3128 3129 for (; li != le && ri != re; ++li, ++ri) { 3130 assert(ri != right->param_end() && "Param mismatch"); 3131 const ParmVarDecl *lparm = *li, *rparm = *ri; 3132 3133 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType())) 3134 return false; 3135 3136 if (getLangOpts().ObjCAutoRefCount && 3137 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()) 3138 return false; 3139 } 3140 return true; 3141 } 3142 3143 void Sema::addMethodToGlobalList(ObjCMethodList *List, 3144 ObjCMethodDecl *Method) { 3145 // Record at the head of the list whether there were 0, 1, or >= 2 methods 3146 // inside categories. 3147 if (ObjCCategoryDecl *CD = 3148 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) 3149 if (!CD->IsClassExtension() && List->getBits() < 2) 3150 List->setBits(List->getBits() + 1); 3151 3152 // If the list is empty, make it a singleton list. 3153 if (List->getMethod() == nullptr) { 3154 List->setMethod(Method); 3155 List->setNext(nullptr); 3156 return; 3157 } 3158 3159 // We've seen a method with this name, see if we have already seen this type 3160 // signature. 3161 ObjCMethodList *Previous = List; 3162 for (; List; Previous = List, List = List->getNext()) { 3163 // If we are building a module, keep all of the methods. 3164 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) 3165 continue; 3166 3167 if (!MatchTwoMethodDeclarations(Method, List->getMethod())) { 3168 // Even if two method types do not match, we would like to say 3169 // there is more than one declaration so unavailability/deprecated 3170 // warning is not too noisy. 3171 if (!Method->isDefined()) 3172 List->setHasMoreThanOneDecl(true); 3173 continue; 3174 } 3175 3176 ObjCMethodDecl *PrevObjCMethod = List->getMethod(); 3177 3178 // Propagate the 'defined' bit. 3179 if (Method->isDefined()) 3180 PrevObjCMethod->setDefined(true); 3181 else { 3182 // Objective-C doesn't allow an @interface for a class after its 3183 // @implementation. So if Method is not defined and there already is 3184 // an entry for this type signature, Method has to be for a different 3185 // class than PrevObjCMethod. 3186 List->setHasMoreThanOneDecl(true); 3187 } 3188 3189 // If a method is deprecated, push it in the global pool. 3190 // This is used for better diagnostics. 3191 if (Method->isDeprecated()) { 3192 if (!PrevObjCMethod->isDeprecated()) 3193 List->setMethod(Method); 3194 } 3195 // If the new method is unavailable, push it into global pool 3196 // unless previous one is deprecated. 3197 if (Method->isUnavailable()) { 3198 if (PrevObjCMethod->getAvailability() < AR_Deprecated) 3199 List->setMethod(Method); 3200 } 3201 3202 return; 3203 } 3204 3205 // We have a new signature for an existing method - add it. 3206 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". 3207 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>(); 3208 Previous->setNext(new (Mem) ObjCMethodList(Method)); 3209 } 3210 3211 /// \brief Read the contents of the method pool for a given selector from 3212 /// external storage. 3213 void Sema::ReadMethodPool(Selector Sel) { 3214 assert(ExternalSource && "We need an external AST source"); 3215 ExternalSource->ReadMethodPool(Sel); 3216 } 3217 3218 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, 3219 bool instance) { 3220 // Ignore methods of invalid containers. 3221 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl()) 3222 return; 3223 3224 if (ExternalSource) 3225 ReadMethodPool(Method->getSelector()); 3226 3227 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); 3228 if (Pos == MethodPool.end()) 3229 Pos = MethodPool.insert(std::make_pair(Method->getSelector(), 3230 GlobalMethods())).first; 3231 3232 Method->setDefined(impl); 3233 3234 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; 3235 addMethodToGlobalList(&Entry, Method); 3236 } 3237 3238 /// Determines if this is an "acceptable" loose mismatch in the global 3239 /// method pool. This exists mostly as a hack to get around certain 3240 /// global mismatches which we can't afford to make warnings / errors. 3241 /// Really, what we want is a way to take a method out of the global 3242 /// method pool. 3243 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen, 3244 ObjCMethodDecl *other) { 3245 if (!chosen->isInstanceMethod()) 3246 return false; 3247 3248 Selector sel = chosen->getSelector(); 3249 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length") 3250 return false; 3251 3252 // Don't complain about mismatches for -length if the method we 3253 // chose has an integral result type. 3254 return (chosen->getReturnType()->isIntegerType()); 3255 } 3256 3257 bool Sema::CollectMultipleMethodsInGlobalPool( 3258 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) { 3259 if (ExternalSource) 3260 ReadMethodPool(Sel); 3261 3262 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3263 if (Pos == MethodPool.end()) 3264 return false; 3265 // Gather the non-hidden methods. 3266 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 3267 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) 3268 if (M->getMethod() && !M->getMethod()->isHidden()) 3269 Methods.push_back(M->getMethod()); 3270 return Methods.size() > 1; 3271 } 3272 3273 bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, 3274 SourceRange R, 3275 bool receiverIdOrClass) { 3276 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3277 // Test for no method in the pool which should not trigger any warning by 3278 // caller. 3279 if (Pos == MethodPool.end()) 3280 return true; 3281 ObjCMethodList &MethList = 3282 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second; 3283 3284 // Diagnose finding more than one method in global pool 3285 SmallVector<ObjCMethodDecl *, 4> Methods; 3286 Methods.push_back(BestMethod); 3287 for (ObjCMethodList *ML = &MethList; ML; ML = ML->getNext()) 3288 if (ObjCMethodDecl *M = ML->getMethod()) 3289 if (!M->isHidden() && M != BestMethod && !M->hasAttr<UnavailableAttr>()) 3290 Methods.push_back(M); 3291 if (Methods.size() > 1) 3292 DiagnoseMultipleMethodInGlobalPool(Methods, Sel, R, receiverIdOrClass); 3293 3294 return MethList.hasMoreThanOneDecl(); 3295 } 3296 3297 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, 3298 bool receiverIdOrClass, 3299 bool instance) { 3300 if (ExternalSource) 3301 ReadMethodPool(Sel); 3302 3303 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3304 if (Pos == MethodPool.end()) 3305 return nullptr; 3306 3307 // Gather the non-hidden methods. 3308 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 3309 SmallVector<ObjCMethodDecl *, 4> Methods; 3310 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) { 3311 if (M->getMethod() && !M->getMethod()->isHidden()) 3312 return M->getMethod(); 3313 } 3314 return nullptr; 3315 } 3316 3317 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 3318 Selector Sel, SourceRange R, 3319 bool receiverIdOrClass) { 3320 // We found multiple methods, so we may have to complain. 3321 bool issueDiagnostic = false, issueError = false; 3322 3323 // We support a warning which complains about *any* difference in 3324 // method signature. 3325 bool strictSelectorMatch = 3326 receiverIdOrClass && 3327 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin()); 3328 if (strictSelectorMatch) { 3329 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3330 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) { 3331 issueDiagnostic = true; 3332 break; 3333 } 3334 } 3335 } 3336 3337 // If we didn't see any strict differences, we won't see any loose 3338 // differences. In ARC, however, we also need to check for loose 3339 // mismatches, because most of them are errors. 3340 if (!strictSelectorMatch || 3341 (issueDiagnostic && getLangOpts().ObjCAutoRefCount)) 3342 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3343 // This checks if the methods differ in type mismatch. 3344 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) && 3345 !isAcceptableMethodMismatch(Methods[0], Methods[I])) { 3346 issueDiagnostic = true; 3347 if (getLangOpts().ObjCAutoRefCount) 3348 issueError = true; 3349 break; 3350 } 3351 } 3352 3353 if (issueDiagnostic) { 3354 if (issueError) 3355 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; 3356 else if (strictSelectorMatch) 3357 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; 3358 else 3359 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; 3360 3361 Diag(Methods[0]->getLocStart(), 3362 issueError ? diag::note_possibility : diag::note_using) 3363 << Methods[0]->getSourceRange(); 3364 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3365 Diag(Methods[I]->getLocStart(), diag::note_also_found) 3366 << Methods[I]->getSourceRange(); 3367 } 3368 } 3369 } 3370 3371 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { 3372 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3373 if (Pos == MethodPool.end()) 3374 return nullptr; 3375 3376 GlobalMethods &Methods = Pos->second; 3377 for (const ObjCMethodList *Method = &Methods.first; Method; 3378 Method = Method->getNext()) 3379 if (Method->getMethod() && 3380 (Method->getMethod()->isDefined() || 3381 Method->getMethod()->isPropertyAccessor())) 3382 return Method->getMethod(); 3383 3384 for (const ObjCMethodList *Method = &Methods.second; Method; 3385 Method = Method->getNext()) 3386 if (Method->getMethod() && 3387 (Method->getMethod()->isDefined() || 3388 Method->getMethod()->isPropertyAccessor())) 3389 return Method->getMethod(); 3390 return nullptr; 3391 } 3392 3393 static void 3394 HelperSelectorsForTypoCorrection( 3395 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod, 3396 StringRef Typo, const ObjCMethodDecl * Method) { 3397 const unsigned MaxEditDistance = 1; 3398 unsigned BestEditDistance = MaxEditDistance + 1; 3399 std::string MethodName = Method->getSelector().getAsString(); 3400 3401 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size()); 3402 if (MinPossibleEditDistance > 0 && 3403 Typo.size() / MinPossibleEditDistance < 1) 3404 return; 3405 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance); 3406 if (EditDistance > MaxEditDistance) 3407 return; 3408 if (EditDistance == BestEditDistance) 3409 BestMethod.push_back(Method); 3410 else if (EditDistance < BestEditDistance) { 3411 BestMethod.clear(); 3412 BestMethod.push_back(Method); 3413 } 3414 } 3415 3416 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel, 3417 QualType ObjectType) { 3418 if (ObjectType.isNull()) 3419 return true; 3420 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/)) 3421 return true; 3422 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) != 3423 nullptr; 3424 } 3425 3426 const ObjCMethodDecl * 3427 Sema::SelectorsForTypoCorrection(Selector Sel, 3428 QualType ObjectType) { 3429 unsigned NumArgs = Sel.getNumArgs(); 3430 SmallVector<const ObjCMethodDecl *, 8> Methods; 3431 bool ObjectIsId = true, ObjectIsClass = true; 3432 if (ObjectType.isNull()) 3433 ObjectIsId = ObjectIsClass = false; 3434 else if (!ObjectType->isObjCObjectPointerType()) 3435 return nullptr; 3436 else if (const ObjCObjectPointerType *ObjCPtr = 3437 ObjectType->getAsObjCInterfacePointerType()) { 3438 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0); 3439 ObjectIsId = ObjectIsClass = false; 3440 } 3441 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType()) 3442 ObjectIsClass = false; 3443 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType()) 3444 ObjectIsId = false; 3445 else 3446 return nullptr; 3447 3448 for (GlobalMethodPool::iterator b = MethodPool.begin(), 3449 e = MethodPool.end(); b != e; b++) { 3450 // instance methods 3451 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext()) 3452 if (M->getMethod() && 3453 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3454 (M->getMethod()->getSelector() != Sel)) { 3455 if (ObjectIsId) 3456 Methods.push_back(M->getMethod()); 3457 else if (!ObjectIsClass && 3458 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3459 ObjectType)) 3460 Methods.push_back(M->getMethod()); 3461 } 3462 // class methods 3463 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext()) 3464 if (M->getMethod() && 3465 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3466 (M->getMethod()->getSelector() != Sel)) { 3467 if (ObjectIsClass) 3468 Methods.push_back(M->getMethod()); 3469 else if (!ObjectIsId && 3470 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3471 ObjectType)) 3472 Methods.push_back(M->getMethod()); 3473 } 3474 } 3475 3476 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods; 3477 for (unsigned i = 0, e = Methods.size(); i < e; i++) { 3478 HelperSelectorsForTypoCorrection(SelectedMethods, 3479 Sel.getAsString(), Methods[i]); 3480 } 3481 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr; 3482 } 3483 3484 /// DiagnoseDuplicateIvars - 3485 /// Check for duplicate ivars in the entire class at the start of 3486 /// \@implementation. This becomes necesssary because class extension can 3487 /// add ivars to a class in random order which will not be known until 3488 /// class's \@implementation is seen. 3489 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 3490 ObjCInterfaceDecl *SID) { 3491 for (auto *Ivar : ID->ivars()) { 3492 if (Ivar->isInvalidDecl()) 3493 continue; 3494 if (IdentifierInfo *II = Ivar->getIdentifier()) { 3495 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II); 3496 if (prevIvar) { 3497 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 3498 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 3499 Ivar->setInvalidDecl(); 3500 } 3501 } 3502 } 3503 } 3504 3505 Sema::ObjCContainerKind Sema::getObjCContainerKind() const { 3506 switch (CurContext->getDeclKind()) { 3507 case Decl::ObjCInterface: 3508 return Sema::OCK_Interface; 3509 case Decl::ObjCProtocol: 3510 return Sema::OCK_Protocol; 3511 case Decl::ObjCCategory: 3512 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension()) 3513 return Sema::OCK_ClassExtension; 3514 return Sema::OCK_Category; 3515 case Decl::ObjCImplementation: 3516 return Sema::OCK_Implementation; 3517 case Decl::ObjCCategoryImpl: 3518 return Sema::OCK_CategoryImplementation; 3519 3520 default: 3521 return Sema::OCK_None; 3522 } 3523 } 3524 3525 // Note: For class/category implementations, allMethods is always null. 3526 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods, 3527 ArrayRef<DeclGroupPtrTy> allTUVars) { 3528 if (getObjCContainerKind() == Sema::OCK_None) 3529 return nullptr; 3530 3531 assert(AtEnd.isValid() && "Invalid location for '@end'"); 3532 3533 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 3534 Decl *ClassDecl = cast<Decl>(OCD); 3535 3536 bool isInterfaceDeclKind = 3537 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) 3538 || isa<ObjCProtocolDecl>(ClassDecl); 3539 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); 3540 3541 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. 3542 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; 3543 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; 3544 3545 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) { 3546 ObjCMethodDecl *Method = 3547 cast_or_null<ObjCMethodDecl>(allMethods[i]); 3548 3549 if (!Method) continue; // Already issued a diagnostic. 3550 if (Method->isInstanceMethod()) { 3551 /// Check for instance method of the same name with incompatible types 3552 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; 3553 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 3554 : false; 3555 if ((isInterfaceDeclKind && PrevMethod && !match) 3556 || (checkIdenticalMethods && match)) { 3557 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 3558 << Method->getDeclName(); 3559 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3560 Method->setInvalidDecl(); 3561 } else { 3562 if (PrevMethod) { 3563 Method->setAsRedeclaration(PrevMethod); 3564 if (!Context.getSourceManager().isInSystemHeader( 3565 Method->getLocation())) 3566 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 3567 << Method->getDeclName(); 3568 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3569 } 3570 InsMap[Method->getSelector()] = Method; 3571 /// The following allows us to typecheck messages to "id". 3572 AddInstanceMethodToGlobalPool(Method); 3573 } 3574 } else { 3575 /// Check for class method of the same name with incompatible types 3576 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; 3577 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 3578 : false; 3579 if ((isInterfaceDeclKind && PrevMethod && !match) 3580 || (checkIdenticalMethods && match)) { 3581 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 3582 << Method->getDeclName(); 3583 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3584 Method->setInvalidDecl(); 3585 } else { 3586 if (PrevMethod) { 3587 Method->setAsRedeclaration(PrevMethod); 3588 if (!Context.getSourceManager().isInSystemHeader( 3589 Method->getLocation())) 3590 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 3591 << Method->getDeclName(); 3592 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3593 } 3594 ClsMap[Method->getSelector()] = Method; 3595 AddFactoryMethodToGlobalPool(Method); 3596 } 3597 } 3598 } 3599 if (isa<ObjCInterfaceDecl>(ClassDecl)) { 3600 // Nothing to do here. 3601 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 3602 // Categories are used to extend the class by declaring new methods. 3603 // By the same token, they are also used to add new properties. No 3604 // need to compare the added property to those in the class. 3605 3606 if (C->IsClassExtension()) { 3607 ObjCInterfaceDecl *CCPrimary = C->getClassInterface(); 3608 DiagnoseClassExtensionDupMethods(C, CCPrimary); 3609 } 3610 } 3611 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { 3612 if (CDecl->getIdentifier()) 3613 // ProcessPropertyDecl is responsible for diagnosing conflicts with any 3614 // user-defined setter/getter. It also synthesizes setter/getter methods 3615 // and adds them to the DeclContext and global method pools. 3616 for (auto *I : CDecl->properties()) 3617 ProcessPropertyDecl(I, CDecl); 3618 CDecl->setAtEndRange(AtEnd); 3619 } 3620 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { 3621 IC->setAtEndRange(AtEnd); 3622 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) { 3623 // Any property declared in a class extension might have user 3624 // declared setter or getter in current class extension or one 3625 // of the other class extensions. Mark them as synthesized as 3626 // property will be synthesized when property with same name is 3627 // seen in the @implementation. 3628 for (const auto *Ext : IDecl->visible_extensions()) { 3629 for (const auto *Property : Ext->properties()) { 3630 // Skip over properties declared @dynamic 3631 if (const ObjCPropertyImplDecl *PIDecl 3632 = IC->FindPropertyImplDecl(Property->getIdentifier())) 3633 if (PIDecl->getPropertyImplementation() 3634 == ObjCPropertyImplDecl::Dynamic) 3635 continue; 3636 3637 for (const auto *Ext : IDecl->visible_extensions()) { 3638 if (ObjCMethodDecl *GetterMethod 3639 = Ext->getInstanceMethod(Property->getGetterName())) 3640 GetterMethod->setPropertyAccessor(true); 3641 if (!Property->isReadOnly()) 3642 if (ObjCMethodDecl *SetterMethod 3643 = Ext->getInstanceMethod(Property->getSetterName())) 3644 SetterMethod->setPropertyAccessor(true); 3645 } 3646 } 3647 } 3648 ImplMethodsVsClassMethods(S, IC, IDecl); 3649 AtomicPropertySetterGetterRules(IC, IDecl); 3650 DiagnoseOwningPropertyGetterSynthesis(IC); 3651 DiagnoseUnusedBackingIvarInAccessor(S, IC); 3652 if (IDecl->hasDesignatedInitializers()) 3653 DiagnoseMissingDesignatedInitOverrides(IC, IDecl); 3654 3655 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>(); 3656 if (IDecl->getSuperClass() == nullptr) { 3657 // This class has no superclass, so check that it has been marked with 3658 // __attribute((objc_root_class)). 3659 if (!HasRootClassAttr) { 3660 SourceLocation DeclLoc(IDecl->getLocation()); 3661 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc)); 3662 Diag(DeclLoc, diag::warn_objc_root_class_missing) 3663 << IDecl->getIdentifier(); 3664 // See if NSObject is in the current scope, and if it is, suggest 3665 // adding " : NSObject " to the class declaration. 3666 NamedDecl *IF = LookupSingleName(TUScope, 3667 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject), 3668 DeclLoc, LookupOrdinaryName); 3669 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 3670 if (NSObjectDecl && NSObjectDecl->getDefinition()) { 3671 Diag(SuperClassLoc, diag::note_objc_needs_superclass) 3672 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject "); 3673 } else { 3674 Diag(SuperClassLoc, diag::note_objc_needs_superclass); 3675 } 3676 } 3677 } else if (HasRootClassAttr) { 3678 // Complain that only root classes may have this attribute. 3679 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass); 3680 } 3681 3682 if (LangOpts.ObjCRuntime.isNonFragile()) { 3683 while (IDecl->getSuperClass()) { 3684 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass()); 3685 IDecl = IDecl->getSuperClass(); 3686 } 3687 } 3688 } 3689 SetIvarInitializers(IC); 3690 } else if (ObjCCategoryImplDecl* CatImplClass = 3691 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { 3692 CatImplClass->setAtEndRange(AtEnd); 3693 3694 // Find category interface decl and then check that all methods declared 3695 // in this interface are implemented in the category @implementation. 3696 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { 3697 if (ObjCCategoryDecl *Cat 3698 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) { 3699 ImplMethodsVsClassMethods(S, CatImplClass, Cat); 3700 } 3701 } 3702 } 3703 if (isInterfaceDeclKind) { 3704 // Reject invalid vardecls. 3705 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 3706 DeclGroupRef DG = allTUVars[i].get(); 3707 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 3708 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { 3709 if (!VDecl->hasExternalStorage()) 3710 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); 3711 } 3712 } 3713 } 3714 ActOnObjCContainerFinishDefinition(); 3715 3716 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 3717 DeclGroupRef DG = allTUVars[i].get(); 3718 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 3719 (*I)->setTopLevelDeclInObjCContainer(); 3720 Consumer.HandleTopLevelDeclInObjCContainer(DG); 3721 } 3722 3723 ActOnDocumentableDecl(ClassDecl); 3724 return ClassDecl; 3725 } 3726 3727 3728 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for 3729 /// objective-c's type qualifier from the parser version of the same info. 3730 static Decl::ObjCDeclQualifier 3731 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { 3732 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal; 3733 } 3734 3735 /// \brief Check whether the declared result type of the given Objective-C 3736 /// method declaration is compatible with the method's class. 3737 /// 3738 static Sema::ResultTypeCompatibilityKind 3739 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, 3740 ObjCInterfaceDecl *CurrentClass) { 3741 QualType ResultType = Method->getReturnType(); 3742 3743 // If an Objective-C method inherits its related result type, then its 3744 // declared result type must be compatible with its own class type. The 3745 // declared result type is compatible if: 3746 if (const ObjCObjectPointerType *ResultObjectType 3747 = ResultType->getAs<ObjCObjectPointerType>()) { 3748 // - it is id or qualified id, or 3749 if (ResultObjectType->isObjCIdType() || 3750 ResultObjectType->isObjCQualifiedIdType()) 3751 return Sema::RTC_Compatible; 3752 3753 if (CurrentClass) { 3754 if (ObjCInterfaceDecl *ResultClass 3755 = ResultObjectType->getInterfaceDecl()) { 3756 // - it is the same as the method's class type, or 3757 if (declaresSameEntity(CurrentClass, ResultClass)) 3758 return Sema::RTC_Compatible; 3759 3760 // - it is a superclass of the method's class type 3761 if (ResultClass->isSuperClassOf(CurrentClass)) 3762 return Sema::RTC_Compatible; 3763 } 3764 } else { 3765 // Any Objective-C pointer type might be acceptable for a protocol 3766 // method; we just don't know. 3767 return Sema::RTC_Unknown; 3768 } 3769 } 3770 3771 return Sema::RTC_Incompatible; 3772 } 3773 3774 namespace { 3775 /// A helper class for searching for methods which a particular method 3776 /// overrides. 3777 class OverrideSearch { 3778 public: 3779 Sema &S; 3780 ObjCMethodDecl *Method; 3781 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden; 3782 bool Recursive; 3783 3784 public: 3785 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) { 3786 Selector selector = method->getSelector(); 3787 3788 // Bypass this search if we've never seen an instance/class method 3789 // with this selector before. 3790 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector); 3791 if (it == S.MethodPool.end()) { 3792 if (!S.getExternalSource()) return; 3793 S.ReadMethodPool(selector); 3794 3795 it = S.MethodPool.find(selector); 3796 if (it == S.MethodPool.end()) 3797 return; 3798 } 3799 ObjCMethodList &list = 3800 method->isInstanceMethod() ? it->second.first : it->second.second; 3801 if (!list.getMethod()) return; 3802 3803 ObjCContainerDecl *container 3804 = cast<ObjCContainerDecl>(method->getDeclContext()); 3805 3806 // Prevent the search from reaching this container again. This is 3807 // important with categories, which override methods from the 3808 // interface and each other. 3809 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) { 3810 searchFromContainer(container); 3811 if (ObjCInterfaceDecl *Interface = Category->getClassInterface()) 3812 searchFromContainer(Interface); 3813 } else { 3814 searchFromContainer(container); 3815 } 3816 } 3817 3818 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator; 3819 iterator begin() const { return Overridden.begin(); } 3820 iterator end() const { return Overridden.end(); } 3821 3822 private: 3823 void searchFromContainer(ObjCContainerDecl *container) { 3824 if (container->isInvalidDecl()) return; 3825 3826 switch (container->getDeclKind()) { 3827 #define OBJCCONTAINER(type, base) \ 3828 case Decl::type: \ 3829 searchFrom(cast<type##Decl>(container)); \ 3830 break; 3831 #define ABSTRACT_DECL(expansion) 3832 #define DECL(type, base) \ 3833 case Decl::type: 3834 #include "clang/AST/DeclNodes.inc" 3835 llvm_unreachable("not an ObjC container!"); 3836 } 3837 } 3838 3839 void searchFrom(ObjCProtocolDecl *protocol) { 3840 if (!protocol->hasDefinition()) 3841 return; 3842 3843 // A method in a protocol declaration overrides declarations from 3844 // referenced ("parent") protocols. 3845 search(protocol->getReferencedProtocols()); 3846 } 3847 3848 void searchFrom(ObjCCategoryDecl *category) { 3849 // A method in a category declaration overrides declarations from 3850 // the main class and from protocols the category references. 3851 // The main class is handled in the constructor. 3852 search(category->getReferencedProtocols()); 3853 } 3854 3855 void searchFrom(ObjCCategoryImplDecl *impl) { 3856 // A method in a category definition that has a category 3857 // declaration overrides declarations from the category 3858 // declaration. 3859 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) { 3860 search(category); 3861 if (ObjCInterfaceDecl *Interface = category->getClassInterface()) 3862 search(Interface); 3863 3864 // Otherwise it overrides declarations from the class. 3865 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) { 3866 search(Interface); 3867 } 3868 } 3869 3870 void searchFrom(ObjCInterfaceDecl *iface) { 3871 // A method in a class declaration overrides declarations from 3872 if (!iface->hasDefinition()) 3873 return; 3874 3875 // - categories, 3876 for (auto *Cat : iface->known_categories()) 3877 search(Cat); 3878 3879 // - the super class, and 3880 if (ObjCInterfaceDecl *super = iface->getSuperClass()) 3881 search(super); 3882 3883 // - any referenced protocols. 3884 search(iface->getReferencedProtocols()); 3885 } 3886 3887 void searchFrom(ObjCImplementationDecl *impl) { 3888 // A method in a class implementation overrides declarations from 3889 // the class interface. 3890 if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) 3891 search(Interface); 3892 } 3893 3894 3895 void search(const ObjCProtocolList &protocols) { 3896 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end(); 3897 i != e; ++i) 3898 search(*i); 3899 } 3900 3901 void search(ObjCContainerDecl *container) { 3902 // Check for a method in this container which matches this selector. 3903 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(), 3904 Method->isInstanceMethod(), 3905 /*AllowHidden=*/true); 3906 3907 // If we find one, record it and bail out. 3908 if (meth) { 3909 Overridden.insert(meth); 3910 return; 3911 } 3912 3913 // Otherwise, search for methods that a hypothetical method here 3914 // would have overridden. 3915 3916 // Note that we're now in a recursive case. 3917 Recursive = true; 3918 3919 searchFromContainer(container); 3920 } 3921 }; 3922 } 3923 3924 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 3925 ObjCInterfaceDecl *CurrentClass, 3926 ResultTypeCompatibilityKind RTC) { 3927 // Search for overridden methods and merge information down from them. 3928 OverrideSearch overrides(*this, ObjCMethod); 3929 // Keep track if the method overrides any method in the class's base classes, 3930 // its protocols, or its categories' protocols; we will keep that info 3931 // in the ObjCMethodDecl. 3932 // For this info, a method in an implementation is not considered as 3933 // overriding the same method in the interface or its categories. 3934 bool hasOverriddenMethodsInBaseOrProtocol = false; 3935 for (OverrideSearch::iterator 3936 i = overrides.begin(), e = overrides.end(); i != e; ++i) { 3937 ObjCMethodDecl *overridden = *i; 3938 3939 if (!hasOverriddenMethodsInBaseOrProtocol) { 3940 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) || 3941 CurrentClass != overridden->getClassInterface() || 3942 overridden->isOverriding()) { 3943 hasOverriddenMethodsInBaseOrProtocol = true; 3944 3945 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) { 3946 // OverrideSearch will return as "overridden" the same method in the 3947 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to 3948 // check whether a category of a base class introduced a method with the 3949 // same selector, after the interface method declaration. 3950 // To avoid unnecessary lookups in the majority of cases, we use the 3951 // extra info bits in GlobalMethodPool to check whether there were any 3952 // category methods with this selector. 3953 GlobalMethodPool::iterator It = 3954 MethodPool.find(ObjCMethod->getSelector()); 3955 if (It != MethodPool.end()) { 3956 ObjCMethodList &List = 3957 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second; 3958 unsigned CategCount = List.getBits(); 3959 if (CategCount > 0) { 3960 // If the method is in a category we'll do lookup if there were at 3961 // least 2 category methods recorded, otherwise only one will do. 3962 if (CategCount > 1 || 3963 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) { 3964 OverrideSearch overrides(*this, overridden); 3965 for (OverrideSearch::iterator 3966 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) { 3967 ObjCMethodDecl *SuperOverridden = *OI; 3968 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) || 3969 CurrentClass != SuperOverridden->getClassInterface()) { 3970 hasOverriddenMethodsInBaseOrProtocol = true; 3971 overridden->setOverriding(true); 3972 break; 3973 } 3974 } 3975 } 3976 } 3977 } 3978 } 3979 } 3980 3981 // Propagate down the 'related result type' bit from overridden methods. 3982 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType()) 3983 ObjCMethod->SetRelatedResultType(); 3984 3985 // Then merge the declarations. 3986 mergeObjCMethodDecls(ObjCMethod, overridden); 3987 3988 if (ObjCMethod->isImplicit() && overridden->isImplicit()) 3989 continue; // Conflicting properties are detected elsewhere. 3990 3991 // Check for overriding methods 3992 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 3993 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) 3994 CheckConflictingOverridingMethod(ObjCMethod, overridden, 3995 isa<ObjCProtocolDecl>(overridden->getDeclContext())); 3996 3997 if (CurrentClass && overridden->getDeclContext() != CurrentClass && 3998 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && 3999 !overridden->isImplicit() /* not meant for properties */) { 4000 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(), 4001 E = ObjCMethod->param_end(); 4002 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(), 4003 PrevE = overridden->param_end(); 4004 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) { 4005 assert(PrevI != overridden->param_end() && "Param mismatch"); 4006 QualType T1 = Context.getCanonicalType((*ParamI)->getType()); 4007 QualType T2 = Context.getCanonicalType((*PrevI)->getType()); 4008 // If type of argument of method in this class does not match its 4009 // respective argument type in the super class method, issue warning; 4010 if (!Context.typesAreCompatible(T1, T2)) { 4011 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super) 4012 << T1 << T2; 4013 Diag(overridden->getLocation(), diag::note_previous_declaration); 4014 break; 4015 } 4016 } 4017 } 4018 } 4019 4020 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol); 4021 } 4022 4023 /// Merge type nullability from for a redeclaration of the same entity, 4024 /// producing the updated type of the redeclared entity. 4025 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc, 4026 QualType type, 4027 bool usesCSKeyword, 4028 SourceLocation prevLoc, 4029 QualType prevType, 4030 bool prevUsesCSKeyword) { 4031 // Determine the nullability of both types. 4032 auto nullability = type->getNullability(S.Context); 4033 auto prevNullability = prevType->getNullability(S.Context); 4034 4035 // Easy case: both have nullability. 4036 if (nullability.hasValue() == prevNullability.hasValue()) { 4037 // Neither has nullability; continue. 4038 if (!nullability) 4039 return type; 4040 4041 // The nullabilities are equivalent; do nothing. 4042 if (*nullability == *prevNullability) 4043 return type; 4044 4045 // Complain about mismatched nullability. 4046 S.Diag(loc, diag::err_nullability_conflicting) 4047 << DiagNullabilityKind(*nullability, usesCSKeyword) 4048 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword); 4049 return type; 4050 } 4051 4052 // If it's the redeclaration that has nullability, don't change anything. 4053 if (nullability) 4054 return type; 4055 4056 // Otherwise, provide the result with the same nullability. 4057 return S.Context.getAttributedType( 4058 AttributedType::getNullabilityAttrKind(*prevNullability), 4059 type, type); 4060 } 4061 4062 /// Merge information from the declaration of a method in the \@interface 4063 /// (or a category/extension) into the corresponding method in the 4064 /// @implementation (for a class or category). 4065 static void mergeInterfaceMethodToImpl(Sema &S, 4066 ObjCMethodDecl *method, 4067 ObjCMethodDecl *prevMethod) { 4068 // Merge the objc_requires_super attribute. 4069 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() && 4070 !method->hasAttr<ObjCRequiresSuperAttr>()) { 4071 // merge the attribute into implementation. 4072 method->addAttr( 4073 ObjCRequiresSuperAttr::CreateImplicit(S.Context, 4074 method->getLocation())); 4075 } 4076 4077 // Merge nullability of the result type. 4078 QualType newReturnType 4079 = mergeTypeNullabilityForRedecl( 4080 S, method->getReturnTypeSourceRange().getBegin(), 4081 method->getReturnType(), 4082 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4083 prevMethod->getReturnTypeSourceRange().getBegin(), 4084 prevMethod->getReturnType(), 4085 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4086 method->setReturnType(newReturnType); 4087 4088 // Handle each of the parameters. 4089 unsigned numParams = method->param_size(); 4090 unsigned numPrevParams = prevMethod->param_size(); 4091 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) { 4092 ParmVarDecl *param = method->param_begin()[i]; 4093 ParmVarDecl *prevParam = prevMethod->param_begin()[i]; 4094 4095 // Merge nullability. 4096 QualType newParamType 4097 = mergeTypeNullabilityForRedecl( 4098 S, param->getLocation(), param->getType(), 4099 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4100 prevParam->getLocation(), prevParam->getType(), 4101 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4102 param->setType(newParamType); 4103 } 4104 } 4105 4106 Decl *Sema::ActOnMethodDeclaration( 4107 Scope *S, 4108 SourceLocation MethodLoc, SourceLocation EndLoc, 4109 tok::TokenKind MethodType, 4110 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 4111 ArrayRef<SourceLocation> SelectorLocs, 4112 Selector Sel, 4113 // optional arguments. The number of types/arguments is obtained 4114 // from the Sel.getNumArgs(). 4115 ObjCArgInfo *ArgInfo, 4116 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 4117 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind, 4118 bool isVariadic, bool MethodDefinition) { 4119 // Make sure we can establish a context for the method. 4120 if (!CurContext->isObjCContainer()) { 4121 Diag(MethodLoc, diag::error_missing_method_context); 4122 return nullptr; 4123 } 4124 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 4125 Decl *ClassDecl = cast<Decl>(OCD); 4126 QualType resultDeclType; 4127 4128 bool HasRelatedResultType = false; 4129 TypeSourceInfo *ReturnTInfo = nullptr; 4130 if (ReturnType) { 4131 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo); 4132 4133 if (CheckFunctionReturnType(resultDeclType, MethodLoc)) 4134 return nullptr; 4135 4136 QualType bareResultType = resultDeclType; 4137 (void)AttributedType::stripOuterNullability(bareResultType); 4138 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType()); 4139 } else { // get the type for "id". 4140 resultDeclType = Context.getObjCIdType(); 4141 Diag(MethodLoc, diag::warn_missing_method_return_type) 4142 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)"); 4143 } 4144 4145 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create( 4146 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext, 4147 MethodType == tok::minus, isVariadic, 4148 /*isPropertyAccessor=*/false, 4149 /*isImplicitlyDeclared=*/false, /*isDefined=*/false, 4150 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional 4151 : ObjCMethodDecl::Required, 4152 HasRelatedResultType); 4153 4154 SmallVector<ParmVarDecl*, 16> Params; 4155 4156 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { 4157 QualType ArgType; 4158 TypeSourceInfo *DI; 4159 4160 if (!ArgInfo[i].Type) { 4161 ArgType = Context.getObjCIdType(); 4162 DI = nullptr; 4163 } else { 4164 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); 4165 } 4166 4167 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 4168 LookupOrdinaryName, ForRedeclaration); 4169 LookupName(R, S); 4170 if (R.isSingleResult()) { 4171 NamedDecl *PrevDecl = R.getFoundDecl(); 4172 if (S->isDeclScope(PrevDecl)) { 4173 Diag(ArgInfo[i].NameLoc, 4174 (MethodDefinition ? diag::warn_method_param_redefinition 4175 : diag::warn_method_param_declaration)) 4176 << ArgInfo[i].Name; 4177 Diag(PrevDecl->getLocation(), 4178 diag::note_previous_declaration); 4179 } 4180 } 4181 4182 SourceLocation StartLoc = DI 4183 ? DI->getTypeLoc().getBeginLoc() 4184 : ArgInfo[i].NameLoc; 4185 4186 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc, 4187 ArgInfo[i].NameLoc, ArgInfo[i].Name, 4188 ArgType, DI, SC_None); 4189 4190 Param->setObjCMethodScopeInfo(i); 4191 4192 Param->setObjCDeclQualifier( 4193 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); 4194 4195 // Apply the attributes to the parameter. 4196 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs); 4197 4198 if (Param->hasAttr<BlocksAttr>()) { 4199 Diag(Param->getLocation(), diag::err_block_on_nonlocal); 4200 Param->setInvalidDecl(); 4201 } 4202 S->AddDecl(Param); 4203 IdResolver.AddDecl(Param); 4204 4205 Params.push_back(Param); 4206 } 4207 4208 for (unsigned i = 0, e = CNumArgs; i != e; ++i) { 4209 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); 4210 QualType ArgType = Param->getType(); 4211 if (ArgType.isNull()) 4212 ArgType = Context.getObjCIdType(); 4213 else 4214 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 4215 ArgType = Context.getAdjustedParameterType(ArgType); 4216 4217 Param->setDeclContext(ObjCMethod); 4218 Params.push_back(Param); 4219 } 4220 4221 ObjCMethod->setMethodParams(Context, Params, SelectorLocs); 4222 ObjCMethod->setObjCDeclQualifier( 4223 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); 4224 4225 if (AttrList) 4226 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList); 4227 4228 // Add the method now. 4229 const ObjCMethodDecl *PrevMethod = nullptr; 4230 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) { 4231 if (MethodType == tok::minus) { 4232 PrevMethod = ImpDecl->getInstanceMethod(Sel); 4233 ImpDecl->addInstanceMethod(ObjCMethod); 4234 } else { 4235 PrevMethod = ImpDecl->getClassMethod(Sel); 4236 ImpDecl->addClassMethod(ObjCMethod); 4237 } 4238 4239 // Merge information from the @interface declaration into the 4240 // @implementation. 4241 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) { 4242 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 4243 ObjCMethod->isInstanceMethod())) { 4244 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD); 4245 4246 // Warn about defining -dealloc in a category. 4247 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() && 4248 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) { 4249 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category) 4250 << ObjCMethod->getDeclName(); 4251 } 4252 } 4253 } 4254 } else { 4255 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); 4256 } 4257 4258 if (PrevMethod) { 4259 // You can never have two method definitions with the same name. 4260 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) 4261 << ObjCMethod->getDeclName(); 4262 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 4263 ObjCMethod->setInvalidDecl(); 4264 return ObjCMethod; 4265 } 4266 4267 // If this Objective-C method does not have a related result type, but we 4268 // are allowed to infer related result types, try to do so based on the 4269 // method family. 4270 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 4271 if (!CurrentClass) { 4272 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) 4273 CurrentClass = Cat->getClassInterface(); 4274 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl)) 4275 CurrentClass = Impl->getClassInterface(); 4276 else if (ObjCCategoryImplDecl *CatImpl 4277 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) 4278 CurrentClass = CatImpl->getClassInterface(); 4279 } 4280 4281 ResultTypeCompatibilityKind RTC 4282 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass); 4283 4284 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC); 4285 4286 bool ARCError = false; 4287 if (getLangOpts().ObjCAutoRefCount) 4288 ARCError = CheckARCMethodDecl(ObjCMethod); 4289 4290 // Infer the related result type when possible. 4291 if (!ARCError && RTC == Sema::RTC_Compatible && 4292 !ObjCMethod->hasRelatedResultType() && 4293 LangOpts.ObjCInferRelatedResultType) { 4294 bool InferRelatedResultType = false; 4295 switch (ObjCMethod->getMethodFamily()) { 4296 case OMF_None: 4297 case OMF_copy: 4298 case OMF_dealloc: 4299 case OMF_finalize: 4300 case OMF_mutableCopy: 4301 case OMF_release: 4302 case OMF_retainCount: 4303 case OMF_initialize: 4304 case OMF_performSelector: 4305 break; 4306 4307 case OMF_alloc: 4308 case OMF_new: 4309 InferRelatedResultType = ObjCMethod->isClassMethod(); 4310 break; 4311 4312 case OMF_init: 4313 case OMF_autorelease: 4314 case OMF_retain: 4315 case OMF_self: 4316 InferRelatedResultType = ObjCMethod->isInstanceMethod(); 4317 break; 4318 } 4319 4320 if (InferRelatedResultType && 4321 !ObjCMethod->getReturnType()->isObjCIndependentClassType()) 4322 ObjCMethod->SetRelatedResultType(); 4323 } 4324 4325 ActOnDocumentableDecl(ObjCMethod); 4326 4327 return ObjCMethod; 4328 } 4329 4330 bool Sema::CheckObjCDeclScope(Decl *D) { 4331 // Following is also an error. But it is caused by a missing @end 4332 // and diagnostic is issued elsewhere. 4333 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) 4334 return false; 4335 4336 // If we switched context to translation unit while we are still lexically in 4337 // an objc container, it means the parser missed emitting an error. 4338 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) 4339 return false; 4340 4341 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); 4342 D->setInvalidDecl(); 4343 4344 return true; 4345 } 4346 4347 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the 4348 /// instance variables of ClassName into Decls. 4349 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 4350 IdentifierInfo *ClassName, 4351 SmallVectorImpl<Decl*> &Decls) { 4352 // Check that ClassName is a valid class 4353 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart); 4354 if (!Class) { 4355 Diag(DeclStart, diag::err_undef_interface) << ClassName; 4356 return; 4357 } 4358 if (LangOpts.ObjCRuntime.isNonFragile()) { 4359 Diag(DeclStart, diag::err_atdef_nonfragile_interface); 4360 return; 4361 } 4362 4363 // Collect the instance variables 4364 SmallVector<const ObjCIvarDecl*, 32> Ivars; 4365 Context.DeepCollectObjCIvars(Class, true, Ivars); 4366 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 4367 for (unsigned i = 0; i < Ivars.size(); i++) { 4368 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]); 4369 RecordDecl *Record = dyn_cast<RecordDecl>(TagD); 4370 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, 4371 /*FIXME: StartL=*/ID->getLocation(), 4372 ID->getLocation(), 4373 ID->getIdentifier(), ID->getType(), 4374 ID->getBitWidth()); 4375 Decls.push_back(FD); 4376 } 4377 4378 // Introduce all of these fields into the appropriate scope. 4379 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin(); 4380 D != Decls.end(); ++D) { 4381 FieldDecl *FD = cast<FieldDecl>(*D); 4382 if (getLangOpts().CPlusPlus) 4383 PushOnScopeChains(cast<FieldDecl>(FD), S); 4384 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD)) 4385 Record->addDecl(FD); 4386 } 4387 } 4388 4389 /// \brief Build a type-check a new Objective-C exception variable declaration. 4390 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, 4391 SourceLocation StartLoc, 4392 SourceLocation IdLoc, 4393 IdentifierInfo *Id, 4394 bool Invalid) { 4395 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 4396 // duration shall not be qualified by an address-space qualifier." 4397 // Since all parameters have automatic store duration, they can not have 4398 // an address space. 4399 if (T.getAddressSpace() != 0) { 4400 Diag(IdLoc, diag::err_arg_with_address_space); 4401 Invalid = true; 4402 } 4403 4404 // An @catch parameter must be an unqualified object pointer type; 4405 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? 4406 if (Invalid) { 4407 // Don't do any further checking. 4408 } else if (T->isDependentType()) { 4409 // Okay: we don't know what this type will instantiate to. 4410 } else if (!T->isObjCObjectPointerType()) { 4411 Invalid = true; 4412 Diag(IdLoc ,diag::err_catch_param_not_objc_type); 4413 } else if (T->isObjCQualifiedIdType()) { 4414 Invalid = true; 4415 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm); 4416 } 4417 4418 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, 4419 T, TInfo, SC_None); 4420 New->setExceptionVariable(true); 4421 4422 // In ARC, infer 'retaining' for variables of retainable type. 4423 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) 4424 Invalid = true; 4425 4426 if (Invalid) 4427 New->setInvalidDecl(); 4428 return New; 4429 } 4430 4431 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { 4432 const DeclSpec &DS = D.getDeclSpec(); 4433 4434 // We allow the "register" storage class on exception variables because 4435 // GCC did, but we drop it completely. Any other storage class is an error. 4436 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 4437 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm) 4438 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc())); 4439 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4440 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm) 4441 << DeclSpec::getSpecifierName(SCS); 4442 } 4443 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 4444 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 4445 diag::err_invalid_thread) 4446 << DeclSpec::getSpecifierName(TSCS); 4447 D.getMutableDeclSpec().ClearStorageClassSpecs(); 4448 4449 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4450 4451 // Check that there are no default arguments inside the type of this 4452 // exception object (C++ only). 4453 if (getLangOpts().CPlusPlus) 4454 CheckExtraCXXDefaultArguments(D); 4455 4456 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4457 QualType ExceptionType = TInfo->getType(); 4458 4459 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, 4460 D.getSourceRange().getBegin(), 4461 D.getIdentifierLoc(), 4462 D.getIdentifier(), 4463 D.isInvalidType()); 4464 4465 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 4466 if (D.getCXXScopeSpec().isSet()) { 4467 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) 4468 << D.getCXXScopeSpec().getRange(); 4469 New->setInvalidDecl(); 4470 } 4471 4472 // Add the parameter declaration into this scope. 4473 S->AddDecl(New); 4474 if (D.getIdentifier()) 4475 IdResolver.AddDecl(New); 4476 4477 ProcessDeclAttributes(S, New, D); 4478 4479 if (New->hasAttr<BlocksAttr>()) 4480 Diag(New->getLocation(), diag::err_block_on_nonlocal); 4481 return New; 4482 } 4483 4484 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 4485 /// initialization. 4486 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 4487 SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 4488 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 4489 Iv= Iv->getNextIvar()) { 4490 QualType QT = Context.getBaseElementType(Iv->getType()); 4491 if (QT->isRecordType()) 4492 Ivars.push_back(Iv); 4493 } 4494 } 4495 4496 void Sema::DiagnoseUseOfUnimplementedSelectors() { 4497 // Load referenced selectors from the external source. 4498 if (ExternalSource) { 4499 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels; 4500 ExternalSource->ReadReferencedSelectors(Sels); 4501 for (unsigned I = 0, N = Sels.size(); I != N; ++I) 4502 ReferencedSelectors[Sels[I].first] = Sels[I].second; 4503 } 4504 4505 // Warning will be issued only when selector table is 4506 // generated (which means there is at lease one implementation 4507 // in the TU). This is to match gcc's behavior. 4508 if (ReferencedSelectors.empty() || 4509 !Context.AnyObjCImplementation()) 4510 return; 4511 for (auto &SelectorAndLocation : ReferencedSelectors) { 4512 Selector Sel = SelectorAndLocation.first; 4513 SourceLocation Loc = SelectorAndLocation.second; 4514 if (!LookupImplementedMethodInGlobalPool(Sel)) 4515 Diag(Loc, diag::warn_unimplemented_selector) << Sel; 4516 } 4517 return; 4518 } 4519 4520 ObjCIvarDecl * 4521 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 4522 const ObjCPropertyDecl *&PDecl) const { 4523 if (Method->isClassMethod()) 4524 return nullptr; 4525 const ObjCInterfaceDecl *IDecl = Method->getClassInterface(); 4526 if (!IDecl) 4527 return nullptr; 4528 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true, 4529 /*shallowCategoryLookup=*/false, 4530 /*followSuper=*/false); 4531 if (!Method || !Method->isPropertyAccessor()) 4532 return nullptr; 4533 if ((PDecl = Method->findPropertyDecl())) 4534 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) { 4535 // property backing ivar must belong to property's class 4536 // or be a private ivar in class's implementation. 4537 // FIXME. fix the const-ness issue. 4538 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable( 4539 IV->getIdentifier()); 4540 return IV; 4541 } 4542 return nullptr; 4543 } 4544 4545 namespace { 4546 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property 4547 /// accessor references the backing ivar. 4548 class UnusedBackingIvarChecker : 4549 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> { 4550 public: 4551 Sema &S; 4552 const ObjCMethodDecl *Method; 4553 const ObjCIvarDecl *IvarD; 4554 bool AccessedIvar; 4555 bool InvokedSelfMethod; 4556 4557 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method, 4558 const ObjCIvarDecl *IvarD) 4559 : S(S), Method(Method), IvarD(IvarD), 4560 AccessedIvar(false), InvokedSelfMethod(false) { 4561 assert(IvarD); 4562 } 4563 4564 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 4565 if (E->getDecl() == IvarD) { 4566 AccessedIvar = true; 4567 return false; 4568 } 4569 return true; 4570 } 4571 4572 bool VisitObjCMessageExpr(ObjCMessageExpr *E) { 4573 if (E->getReceiverKind() == ObjCMessageExpr::Instance && 4574 S.isSelfExpr(E->getInstanceReceiver(), Method)) { 4575 InvokedSelfMethod = true; 4576 } 4577 return true; 4578 } 4579 }; 4580 } 4581 4582 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S, 4583 const ObjCImplementationDecl *ImplD) { 4584 if (S->hasUnrecoverableErrorOccurred()) 4585 return; 4586 4587 for (const auto *CurMethod : ImplD->instance_methods()) { 4588 unsigned DIAG = diag::warn_unused_property_backing_ivar; 4589 SourceLocation Loc = CurMethod->getLocation(); 4590 if (Diags.isIgnored(DIAG, Loc)) 4591 continue; 4592 4593 const ObjCPropertyDecl *PDecl; 4594 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl); 4595 if (!IV) 4596 continue; 4597 4598 UnusedBackingIvarChecker Checker(*this, CurMethod, IV); 4599 Checker.TraverseStmt(CurMethod->getBody()); 4600 if (Checker.AccessedIvar) 4601 continue; 4602 4603 // Do not issue this warning if backing ivar is used somewhere and accessor 4604 // implementation makes a self call. This is to prevent false positive in 4605 // cases where the ivar is accessed by another method that the accessor 4606 // delegates to. 4607 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) { 4608 Diag(Loc, DIAG) << IV; 4609 Diag(PDecl->getLocation(), diag::note_property_declare); 4610 } 4611 } 4612 } 4613