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 } // end anonymous namespace 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 nullptr, 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) { 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 = nullptr; 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 } // end anonymous namespace 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, 2777 ImmediateClass && Cat->IsClassExtension(), 2778 WarnCategoryMethodImpl); 2779 } else { 2780 // Also methods in class extensions need be looked at next. 2781 for (auto *Ext : I->visible_extensions()) 2782 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2783 IMPDecl, Ext, IncompleteImpl, false, 2784 WarnCategoryMethodImpl); 2785 } 2786 2787 // Check for any implementation of a methods declared in protocol. 2788 for (auto *PI : I->all_referenced_protocols()) 2789 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2790 IMPDecl, PI, IncompleteImpl, false, 2791 WarnCategoryMethodImpl); 2792 2793 // FIXME. For now, we are not checking for extact match of methods 2794 // in category implementation and its primary class's super class. 2795 if (!WarnCategoryMethodImpl && I->getSuperClass()) 2796 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2797 IMPDecl, 2798 I->getSuperClass(), IncompleteImpl, false); 2799 } 2800 } 2801 2802 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 2803 /// category matches with those implemented in its primary class and 2804 /// warns each time an exact match is found. 2805 void Sema::CheckCategoryVsClassMethodMatches( 2806 ObjCCategoryImplDecl *CatIMPDecl) { 2807 // Get category's primary class. 2808 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl(); 2809 if (!CatDecl) 2810 return; 2811 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface(); 2812 if (!IDecl) 2813 return; 2814 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass(); 2815 SelectorSet InsMap, ClsMap; 2816 2817 for (const auto *I : CatIMPDecl->instance_methods()) { 2818 Selector Sel = I->getSelector(); 2819 // When checking for methods implemented in the category, skip over 2820 // those declared in category class's super class. This is because 2821 // the super class must implement the method. 2822 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true)) 2823 continue; 2824 InsMap.insert(Sel); 2825 } 2826 2827 for (const auto *I : CatIMPDecl->class_methods()) { 2828 Selector Sel = I->getSelector(); 2829 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false)) 2830 continue; 2831 ClsMap.insert(Sel); 2832 } 2833 if (InsMap.empty() && ClsMap.empty()) 2834 return; 2835 2836 SelectorSet InsMapSeen, ClsMapSeen; 2837 bool IncompleteImpl = false; 2838 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2839 CatIMPDecl, IDecl, 2840 IncompleteImpl, false, 2841 true /*WarnCategoryMethodImpl*/); 2842 } 2843 2844 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 2845 ObjCContainerDecl* CDecl, 2846 bool IncompleteImpl) { 2847 SelectorSet InsMap; 2848 // Check and see if instance methods in class interface have been 2849 // implemented in the implementation class. 2850 for (const auto *I : IMPDecl->instance_methods()) 2851 InsMap.insert(I->getSelector()); 2852 2853 // Check and see if properties declared in the interface have either 1) 2854 // an implementation or 2) there is a @synthesize/@dynamic implementation 2855 // of the property in the @implementation. 2856 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2857 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties && 2858 LangOpts.ObjCRuntime.isNonFragile() && 2859 !IDecl->isObjCRequiresPropertyDefs(); 2860 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties); 2861 } 2862 2863 // Diagnose null-resettable synthesized setters. 2864 diagnoseNullResettableSynthesizedSetters(IMPDecl); 2865 2866 SelectorSet ClsMap; 2867 for (const auto *I : IMPDecl->class_methods()) 2868 ClsMap.insert(I->getSelector()); 2869 2870 // Check for type conflict of methods declared in a class/protocol and 2871 // its implementation; if any. 2872 SelectorSet InsMapSeen, ClsMapSeen; 2873 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2874 IMPDecl, CDecl, 2875 IncompleteImpl, true); 2876 2877 // check all methods implemented in category against those declared 2878 // in its primary class. 2879 if (ObjCCategoryImplDecl *CatDecl = 2880 dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) 2881 CheckCategoryVsClassMethodMatches(CatDecl); 2882 2883 // Check the protocol list for unimplemented methods in the @implementation 2884 // class. 2885 // Check and see if class methods in class interface have been 2886 // implemented in the implementation class. 2887 2888 LazyProtocolNameSet ExplicitImplProtocols; 2889 2890 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 2891 for (auto *PI : I->all_referenced_protocols()) 2892 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl, 2893 InsMap, ClsMap, I, ExplicitImplProtocols); 2894 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2895 // For extended class, unimplemented methods in its protocols will 2896 // be reported in the primary class. 2897 if (!C->IsClassExtension()) { 2898 for (auto *P : C->protocols()) 2899 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P, 2900 IncompleteImpl, InsMap, ClsMap, CDecl, 2901 ExplicitImplProtocols); 2902 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, 2903 /*SynthesizeProperties=*/false); 2904 } 2905 } else 2906 llvm_unreachable("invalid ObjCContainerDecl type."); 2907 } 2908 2909 Sema::DeclGroupPtrTy 2910 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, 2911 IdentifierInfo **IdentList, 2912 SourceLocation *IdentLocs, 2913 ArrayRef<ObjCTypeParamList *> TypeParamLists, 2914 unsigned NumElts) { 2915 SmallVector<Decl *, 8> DeclsInGroup; 2916 for (unsigned i = 0; i != NumElts; ++i) { 2917 // Check for another declaration kind with the same name. 2918 NamedDecl *PrevDecl 2919 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 2920 LookupOrdinaryName, ForRedeclaration); 2921 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 2922 // GCC apparently allows the following idiom: 2923 // 2924 // typedef NSObject < XCElementTogglerP > XCElementToggler; 2925 // @class XCElementToggler; 2926 // 2927 // Here we have chosen to ignore the forward class declaration 2928 // with a warning. Since this is the implied behavior. 2929 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl); 2930 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) { 2931 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; 2932 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2933 } else { 2934 // a forward class declaration matching a typedef name of a class refers 2935 // to the underlying class. Just ignore the forward class with a warning 2936 // as this will force the intended behavior which is to lookup the 2937 // typedef name. 2938 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) { 2939 Diag(AtClassLoc, diag::warn_forward_class_redefinition) 2940 << IdentList[i]; 2941 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2942 continue; 2943 } 2944 } 2945 } 2946 2947 // Create a declaration to describe this forward declaration. 2948 ObjCInterfaceDecl *PrevIDecl 2949 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 2950 2951 IdentifierInfo *ClassName = IdentList[i]; 2952 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 2953 // A previous decl with a different name is because of 2954 // @compatibility_alias, for example: 2955 // \code 2956 // @class NewImage; 2957 // @compatibility_alias OldImage NewImage; 2958 // \endcode 2959 // A lookup for 'OldImage' will return the 'NewImage' decl. 2960 // 2961 // In such a case use the real declaration name, instead of the alias one, 2962 // otherwise we will break IdentifierResolver and redecls-chain invariants. 2963 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 2964 // has been aliased. 2965 ClassName = PrevIDecl->getIdentifier(); 2966 } 2967 2968 // If this forward declaration has type parameters, compare them with the 2969 // type parameters of the previous declaration. 2970 ObjCTypeParamList *TypeParams = TypeParamLists[i]; 2971 if (PrevIDecl && TypeParams) { 2972 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) { 2973 // Check for consistency with the previous declaration. 2974 if (checkTypeParamListConsistency( 2975 *this, PrevTypeParams, TypeParams, 2976 TypeParamListContext::ForwardDeclaration)) { 2977 TypeParams = nullptr; 2978 } 2979 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 2980 // The @interface does not have type parameters. Complain. 2981 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class) 2982 << ClassName 2983 << TypeParams->getSourceRange(); 2984 Diag(Def->getLocation(), diag::note_defined_here) 2985 << ClassName; 2986 2987 TypeParams = nullptr; 2988 } 2989 } 2990 2991 ObjCInterfaceDecl *IDecl 2992 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, 2993 ClassName, TypeParams, PrevIDecl, 2994 IdentLocs[i]); 2995 IDecl->setAtEndRange(IdentLocs[i]); 2996 2997 PushOnScopeChains(IDecl, TUScope); 2998 CheckObjCDeclScope(IDecl); 2999 DeclsInGroup.push_back(IDecl); 3000 } 3001 3002 return BuildDeclaratorGroup(DeclsInGroup, false); 3003 } 3004 3005 static bool tryMatchRecordTypes(ASTContext &Context, 3006 Sema::MethodMatchStrategy strategy, 3007 const Type *left, const Type *right); 3008 3009 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, 3010 QualType leftQT, QualType rightQT) { 3011 const Type *left = 3012 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr(); 3013 const Type *right = 3014 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr(); 3015 3016 if (left == right) return true; 3017 3018 // If we're doing a strict match, the types have to match exactly. 3019 if (strategy == Sema::MMS_strict) return false; 3020 3021 if (left->isIncompleteType() || right->isIncompleteType()) return false; 3022 3023 // Otherwise, use this absurdly complicated algorithm to try to 3024 // validate the basic, low-level compatibility of the two types. 3025 3026 // As a minimum, require the sizes and alignments to match. 3027 TypeInfo LeftTI = Context.getTypeInfo(left); 3028 TypeInfo RightTI = Context.getTypeInfo(right); 3029 if (LeftTI.Width != RightTI.Width) 3030 return false; 3031 3032 if (LeftTI.Align != RightTI.Align) 3033 return false; 3034 3035 // Consider all the kinds of non-dependent canonical types: 3036 // - functions and arrays aren't possible as return and parameter types 3037 3038 // - vector types of equal size can be arbitrarily mixed 3039 if (isa<VectorType>(left)) return isa<VectorType>(right); 3040 if (isa<VectorType>(right)) return false; 3041 3042 // - references should only match references of identical type 3043 // - structs, unions, and Objective-C objects must match more-or-less 3044 // exactly 3045 // - everything else should be a scalar 3046 if (!left->isScalarType() || !right->isScalarType()) 3047 return tryMatchRecordTypes(Context, strategy, left, right); 3048 3049 // Make scalars agree in kind, except count bools as chars, and group 3050 // all non-member pointers together. 3051 Type::ScalarTypeKind leftSK = left->getScalarTypeKind(); 3052 Type::ScalarTypeKind rightSK = right->getScalarTypeKind(); 3053 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral; 3054 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral; 3055 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer) 3056 leftSK = Type::STK_ObjCObjectPointer; 3057 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer) 3058 rightSK = Type::STK_ObjCObjectPointer; 3059 3060 // Note that data member pointers and function member pointers don't 3061 // intermix because of the size differences. 3062 3063 return (leftSK == rightSK); 3064 } 3065 3066 static bool tryMatchRecordTypes(ASTContext &Context, 3067 Sema::MethodMatchStrategy strategy, 3068 const Type *lt, const Type *rt) { 3069 assert(lt && rt && lt != rt); 3070 3071 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false; 3072 RecordDecl *left = cast<RecordType>(lt)->getDecl(); 3073 RecordDecl *right = cast<RecordType>(rt)->getDecl(); 3074 3075 // Require union-hood to match. 3076 if (left->isUnion() != right->isUnion()) return false; 3077 3078 // Require an exact match if either is non-POD. 3079 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) || 3080 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD())) 3081 return false; 3082 3083 // Require size and alignment to match. 3084 TypeInfo LeftTI = Context.getTypeInfo(lt); 3085 TypeInfo RightTI = Context.getTypeInfo(rt); 3086 if (LeftTI.Width != RightTI.Width) 3087 return false; 3088 3089 if (LeftTI.Align != RightTI.Align) 3090 return false; 3091 3092 // Require fields to match. 3093 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end(); 3094 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end(); 3095 for (; li != le && ri != re; ++li, ++ri) { 3096 if (!matchTypes(Context, strategy, li->getType(), ri->getType())) 3097 return false; 3098 } 3099 return (li == le && ri == re); 3100 } 3101 3102 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and 3103 /// returns true, or false, accordingly. 3104 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons 3105 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left, 3106 const ObjCMethodDecl *right, 3107 MethodMatchStrategy strategy) { 3108 if (!matchTypes(Context, strategy, left->getReturnType(), 3109 right->getReturnType())) 3110 return false; 3111 3112 // If either is hidden, it is not considered to match. 3113 if (left->isHidden() || right->isHidden()) 3114 return false; 3115 3116 if (getLangOpts().ObjCAutoRefCount && 3117 (left->hasAttr<NSReturnsRetainedAttr>() 3118 != right->hasAttr<NSReturnsRetainedAttr>() || 3119 left->hasAttr<NSConsumesSelfAttr>() 3120 != right->hasAttr<NSConsumesSelfAttr>())) 3121 return false; 3122 3123 ObjCMethodDecl::param_const_iterator 3124 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(), 3125 re = right->param_end(); 3126 3127 for (; li != le && ri != re; ++li, ++ri) { 3128 assert(ri != right->param_end() && "Param mismatch"); 3129 const ParmVarDecl *lparm = *li, *rparm = *ri; 3130 3131 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType())) 3132 return false; 3133 3134 if (getLangOpts().ObjCAutoRefCount && 3135 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()) 3136 return false; 3137 } 3138 return true; 3139 } 3140 3141 void Sema::addMethodToGlobalList(ObjCMethodList *List, 3142 ObjCMethodDecl *Method) { 3143 // Record at the head of the list whether there were 0, 1, or >= 2 methods 3144 // inside categories. 3145 if (ObjCCategoryDecl *CD = 3146 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) 3147 if (!CD->IsClassExtension() && List->getBits() < 2) 3148 List->setBits(List->getBits() + 1); 3149 3150 // If the list is empty, make it a singleton list. 3151 if (List->getMethod() == nullptr) { 3152 List->setMethod(Method); 3153 List->setNext(nullptr); 3154 return; 3155 } 3156 3157 // We've seen a method with this name, see if we have already seen this type 3158 // signature. 3159 ObjCMethodList *Previous = List; 3160 for (; List; Previous = List, List = List->getNext()) { 3161 // If we are building a module, keep all of the methods. 3162 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) 3163 continue; 3164 3165 if (!MatchTwoMethodDeclarations(Method, List->getMethod())) { 3166 // Even if two method types do not match, we would like to say 3167 // there is more than one declaration so unavailability/deprecated 3168 // warning is not too noisy. 3169 if (!Method->isDefined()) 3170 List->setHasMoreThanOneDecl(true); 3171 continue; 3172 } 3173 3174 ObjCMethodDecl *PrevObjCMethod = List->getMethod(); 3175 3176 // Propagate the 'defined' bit. 3177 if (Method->isDefined()) 3178 PrevObjCMethod->setDefined(true); 3179 else { 3180 // Objective-C doesn't allow an @interface for a class after its 3181 // @implementation. So if Method is not defined and there already is 3182 // an entry for this type signature, Method has to be for a different 3183 // class than PrevObjCMethod. 3184 List->setHasMoreThanOneDecl(true); 3185 } 3186 3187 // If a method is deprecated, push it in the global pool. 3188 // This is used for better diagnostics. 3189 if (Method->isDeprecated()) { 3190 if (!PrevObjCMethod->isDeprecated()) 3191 List->setMethod(Method); 3192 } 3193 // If the new method is unavailable, push it into global pool 3194 // unless previous one is deprecated. 3195 if (Method->isUnavailable()) { 3196 if (PrevObjCMethod->getAvailability() < AR_Deprecated) 3197 List->setMethod(Method); 3198 } 3199 3200 return; 3201 } 3202 3203 // We have a new signature for an existing method - add it. 3204 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". 3205 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>(); 3206 Previous->setNext(new (Mem) ObjCMethodList(Method)); 3207 } 3208 3209 /// \brief Read the contents of the method pool for a given selector from 3210 /// external storage. 3211 void Sema::ReadMethodPool(Selector Sel) { 3212 assert(ExternalSource && "We need an external AST source"); 3213 ExternalSource->ReadMethodPool(Sel); 3214 } 3215 3216 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, 3217 bool instance) { 3218 // Ignore methods of invalid containers. 3219 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl()) 3220 return; 3221 3222 if (ExternalSource) 3223 ReadMethodPool(Method->getSelector()); 3224 3225 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); 3226 if (Pos == MethodPool.end()) 3227 Pos = MethodPool.insert(std::make_pair(Method->getSelector(), 3228 GlobalMethods())).first; 3229 3230 Method->setDefined(impl); 3231 3232 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; 3233 addMethodToGlobalList(&Entry, Method); 3234 } 3235 3236 /// Determines if this is an "acceptable" loose mismatch in the global 3237 /// method pool. This exists mostly as a hack to get around certain 3238 /// global mismatches which we can't afford to make warnings / errors. 3239 /// Really, what we want is a way to take a method out of the global 3240 /// method pool. 3241 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen, 3242 ObjCMethodDecl *other) { 3243 if (!chosen->isInstanceMethod()) 3244 return false; 3245 3246 Selector sel = chosen->getSelector(); 3247 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length") 3248 return false; 3249 3250 // Don't complain about mismatches for -length if the method we 3251 // chose has an integral result type. 3252 return (chosen->getReturnType()->isIntegerType()); 3253 } 3254 3255 bool Sema::CollectMultipleMethodsInGlobalPool( 3256 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) { 3257 if (ExternalSource) 3258 ReadMethodPool(Sel); 3259 3260 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3261 if (Pos == MethodPool.end()) 3262 return false; 3263 // Gather the non-hidden methods. 3264 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 3265 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) 3266 if (M->getMethod() && !M->getMethod()->isHidden()) 3267 Methods.push_back(M->getMethod()); 3268 return Methods.size() > 1; 3269 } 3270 3271 bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, 3272 SourceRange R, 3273 bool receiverIdOrClass) { 3274 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3275 // Test for no method in the pool which should not trigger any warning by 3276 // caller. 3277 if (Pos == MethodPool.end()) 3278 return true; 3279 ObjCMethodList &MethList = 3280 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second; 3281 3282 // Diagnose finding more than one method in global pool 3283 SmallVector<ObjCMethodDecl *, 4> Methods; 3284 Methods.push_back(BestMethod); 3285 for (ObjCMethodList *ML = &MethList; ML; ML = ML->getNext()) 3286 if (ObjCMethodDecl *M = ML->getMethod()) 3287 if (!M->isHidden() && M != BestMethod && !M->hasAttr<UnavailableAttr>()) 3288 Methods.push_back(M); 3289 if (Methods.size() > 1) 3290 DiagnoseMultipleMethodInGlobalPool(Methods, Sel, R, receiverIdOrClass); 3291 3292 return MethList.hasMoreThanOneDecl(); 3293 } 3294 3295 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, 3296 bool receiverIdOrClass, 3297 bool instance) { 3298 if (ExternalSource) 3299 ReadMethodPool(Sel); 3300 3301 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3302 if (Pos == MethodPool.end()) 3303 return nullptr; 3304 3305 // Gather the non-hidden methods. 3306 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 3307 SmallVector<ObjCMethodDecl *, 4> Methods; 3308 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) { 3309 if (M->getMethod() && !M->getMethod()->isHidden()) 3310 return M->getMethod(); 3311 } 3312 return nullptr; 3313 } 3314 3315 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 3316 Selector Sel, SourceRange R, 3317 bool receiverIdOrClass) { 3318 // We found multiple methods, so we may have to complain. 3319 bool issueDiagnostic = false, issueError = false; 3320 3321 // We support a warning which complains about *any* difference in 3322 // method signature. 3323 bool strictSelectorMatch = 3324 receiverIdOrClass && 3325 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin()); 3326 if (strictSelectorMatch) { 3327 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3328 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) { 3329 issueDiagnostic = true; 3330 break; 3331 } 3332 } 3333 } 3334 3335 // If we didn't see any strict differences, we won't see any loose 3336 // differences. In ARC, however, we also need to check for loose 3337 // mismatches, because most of them are errors. 3338 if (!strictSelectorMatch || 3339 (issueDiagnostic && getLangOpts().ObjCAutoRefCount)) 3340 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3341 // This checks if the methods differ in type mismatch. 3342 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) && 3343 !isAcceptableMethodMismatch(Methods[0], Methods[I])) { 3344 issueDiagnostic = true; 3345 if (getLangOpts().ObjCAutoRefCount) 3346 issueError = true; 3347 break; 3348 } 3349 } 3350 3351 if (issueDiagnostic) { 3352 if (issueError) 3353 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; 3354 else if (strictSelectorMatch) 3355 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; 3356 else 3357 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; 3358 3359 Diag(Methods[0]->getLocStart(), 3360 issueError ? diag::note_possibility : diag::note_using) 3361 << Methods[0]->getSourceRange(); 3362 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3363 Diag(Methods[I]->getLocStart(), diag::note_also_found) 3364 << Methods[I]->getSourceRange(); 3365 } 3366 } 3367 } 3368 3369 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { 3370 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3371 if (Pos == MethodPool.end()) 3372 return nullptr; 3373 3374 GlobalMethods &Methods = Pos->second; 3375 for (const ObjCMethodList *Method = &Methods.first; Method; 3376 Method = Method->getNext()) 3377 if (Method->getMethod() && 3378 (Method->getMethod()->isDefined() || 3379 Method->getMethod()->isPropertyAccessor())) 3380 return Method->getMethod(); 3381 3382 for (const ObjCMethodList *Method = &Methods.second; Method; 3383 Method = Method->getNext()) 3384 if (Method->getMethod() && 3385 (Method->getMethod()->isDefined() || 3386 Method->getMethod()->isPropertyAccessor())) 3387 return Method->getMethod(); 3388 return nullptr; 3389 } 3390 3391 static void 3392 HelperSelectorsForTypoCorrection( 3393 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod, 3394 StringRef Typo, const ObjCMethodDecl * Method) { 3395 const unsigned MaxEditDistance = 1; 3396 unsigned BestEditDistance = MaxEditDistance + 1; 3397 std::string MethodName = Method->getSelector().getAsString(); 3398 3399 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size()); 3400 if (MinPossibleEditDistance > 0 && 3401 Typo.size() / MinPossibleEditDistance < 1) 3402 return; 3403 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance); 3404 if (EditDistance > MaxEditDistance) 3405 return; 3406 if (EditDistance == BestEditDistance) 3407 BestMethod.push_back(Method); 3408 else if (EditDistance < BestEditDistance) { 3409 BestMethod.clear(); 3410 BestMethod.push_back(Method); 3411 } 3412 } 3413 3414 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel, 3415 QualType ObjectType) { 3416 if (ObjectType.isNull()) 3417 return true; 3418 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/)) 3419 return true; 3420 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) != 3421 nullptr; 3422 } 3423 3424 const ObjCMethodDecl * 3425 Sema::SelectorsForTypoCorrection(Selector Sel, 3426 QualType ObjectType) { 3427 unsigned NumArgs = Sel.getNumArgs(); 3428 SmallVector<const ObjCMethodDecl *, 8> Methods; 3429 bool ObjectIsId = true, ObjectIsClass = true; 3430 if (ObjectType.isNull()) 3431 ObjectIsId = ObjectIsClass = false; 3432 else if (!ObjectType->isObjCObjectPointerType()) 3433 return nullptr; 3434 else if (const ObjCObjectPointerType *ObjCPtr = 3435 ObjectType->getAsObjCInterfacePointerType()) { 3436 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0); 3437 ObjectIsId = ObjectIsClass = false; 3438 } 3439 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType()) 3440 ObjectIsClass = false; 3441 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType()) 3442 ObjectIsId = false; 3443 else 3444 return nullptr; 3445 3446 for (GlobalMethodPool::iterator b = MethodPool.begin(), 3447 e = MethodPool.end(); b != e; b++) { 3448 // instance methods 3449 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext()) 3450 if (M->getMethod() && 3451 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3452 (M->getMethod()->getSelector() != Sel)) { 3453 if (ObjectIsId) 3454 Methods.push_back(M->getMethod()); 3455 else if (!ObjectIsClass && 3456 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3457 ObjectType)) 3458 Methods.push_back(M->getMethod()); 3459 } 3460 // class methods 3461 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext()) 3462 if (M->getMethod() && 3463 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3464 (M->getMethod()->getSelector() != Sel)) { 3465 if (ObjectIsClass) 3466 Methods.push_back(M->getMethod()); 3467 else if (!ObjectIsId && 3468 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3469 ObjectType)) 3470 Methods.push_back(M->getMethod()); 3471 } 3472 } 3473 3474 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods; 3475 for (unsigned i = 0, e = Methods.size(); i < e; i++) { 3476 HelperSelectorsForTypoCorrection(SelectedMethods, 3477 Sel.getAsString(), Methods[i]); 3478 } 3479 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr; 3480 } 3481 3482 /// DiagnoseDuplicateIvars - 3483 /// Check for duplicate ivars in the entire class at the start of 3484 /// \@implementation. This becomes necesssary because class extension can 3485 /// add ivars to a class in random order which will not be known until 3486 /// class's \@implementation is seen. 3487 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 3488 ObjCInterfaceDecl *SID) { 3489 for (auto *Ivar : ID->ivars()) { 3490 if (Ivar->isInvalidDecl()) 3491 continue; 3492 if (IdentifierInfo *II = Ivar->getIdentifier()) { 3493 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II); 3494 if (prevIvar) { 3495 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 3496 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 3497 Ivar->setInvalidDecl(); 3498 } 3499 } 3500 } 3501 } 3502 3503 Sema::ObjCContainerKind Sema::getObjCContainerKind() const { 3504 switch (CurContext->getDeclKind()) { 3505 case Decl::ObjCInterface: 3506 return Sema::OCK_Interface; 3507 case Decl::ObjCProtocol: 3508 return Sema::OCK_Protocol; 3509 case Decl::ObjCCategory: 3510 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension()) 3511 return Sema::OCK_ClassExtension; 3512 return Sema::OCK_Category; 3513 case Decl::ObjCImplementation: 3514 return Sema::OCK_Implementation; 3515 case Decl::ObjCCategoryImpl: 3516 return Sema::OCK_CategoryImplementation; 3517 3518 default: 3519 return Sema::OCK_None; 3520 } 3521 } 3522 3523 // Note: For class/category implementations, allMethods is always null. 3524 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods, 3525 ArrayRef<DeclGroupPtrTy> allTUVars) { 3526 if (getObjCContainerKind() == Sema::OCK_None) 3527 return nullptr; 3528 3529 assert(AtEnd.isValid() && "Invalid location for '@end'"); 3530 3531 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 3532 Decl *ClassDecl = cast<Decl>(OCD); 3533 3534 bool isInterfaceDeclKind = 3535 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) 3536 || isa<ObjCProtocolDecl>(ClassDecl); 3537 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); 3538 3539 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. 3540 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; 3541 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; 3542 3543 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) { 3544 ObjCMethodDecl *Method = 3545 cast_or_null<ObjCMethodDecl>(allMethods[i]); 3546 3547 if (!Method) continue; // Already issued a diagnostic. 3548 if (Method->isInstanceMethod()) { 3549 /// Check for instance method of the same name with incompatible types 3550 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; 3551 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 3552 : false; 3553 if ((isInterfaceDeclKind && PrevMethod && !match) 3554 || (checkIdenticalMethods && match)) { 3555 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 3556 << Method->getDeclName(); 3557 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3558 Method->setInvalidDecl(); 3559 } else { 3560 if (PrevMethod) { 3561 Method->setAsRedeclaration(PrevMethod); 3562 if (!Context.getSourceManager().isInSystemHeader( 3563 Method->getLocation())) 3564 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 3565 << Method->getDeclName(); 3566 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3567 } 3568 InsMap[Method->getSelector()] = Method; 3569 /// The following allows us to typecheck messages to "id". 3570 AddInstanceMethodToGlobalPool(Method); 3571 } 3572 } else { 3573 /// Check for class method of the same name with incompatible types 3574 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; 3575 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 3576 : false; 3577 if ((isInterfaceDeclKind && PrevMethod && !match) 3578 || (checkIdenticalMethods && match)) { 3579 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 3580 << Method->getDeclName(); 3581 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3582 Method->setInvalidDecl(); 3583 } else { 3584 if (PrevMethod) { 3585 Method->setAsRedeclaration(PrevMethod); 3586 if (!Context.getSourceManager().isInSystemHeader( 3587 Method->getLocation())) 3588 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 3589 << Method->getDeclName(); 3590 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3591 } 3592 ClsMap[Method->getSelector()] = Method; 3593 AddFactoryMethodToGlobalPool(Method); 3594 } 3595 } 3596 } 3597 if (isa<ObjCInterfaceDecl>(ClassDecl)) { 3598 // Nothing to do here. 3599 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 3600 // Categories are used to extend the class by declaring new methods. 3601 // By the same token, they are also used to add new properties. No 3602 // need to compare the added property to those in the class. 3603 3604 if (C->IsClassExtension()) { 3605 ObjCInterfaceDecl *CCPrimary = C->getClassInterface(); 3606 DiagnoseClassExtensionDupMethods(C, CCPrimary); 3607 } 3608 } 3609 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { 3610 if (CDecl->getIdentifier()) 3611 // ProcessPropertyDecl is responsible for diagnosing conflicts with any 3612 // user-defined setter/getter. It also synthesizes setter/getter methods 3613 // and adds them to the DeclContext and global method pools. 3614 for (auto *I : CDecl->properties()) 3615 ProcessPropertyDecl(I, CDecl); 3616 CDecl->setAtEndRange(AtEnd); 3617 } 3618 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { 3619 IC->setAtEndRange(AtEnd); 3620 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) { 3621 // Any property declared in a class extension might have user 3622 // declared setter or getter in current class extension or one 3623 // of the other class extensions. Mark them as synthesized as 3624 // property will be synthesized when property with same name is 3625 // seen in the @implementation. 3626 for (const auto *Ext : IDecl->visible_extensions()) { 3627 for (const auto *Property : Ext->properties()) { 3628 // Skip over properties declared @dynamic 3629 if (const ObjCPropertyImplDecl *PIDecl 3630 = IC->FindPropertyImplDecl(Property->getIdentifier())) 3631 if (PIDecl->getPropertyImplementation() 3632 == ObjCPropertyImplDecl::Dynamic) 3633 continue; 3634 3635 for (const auto *Ext : IDecl->visible_extensions()) { 3636 if (ObjCMethodDecl *GetterMethod 3637 = Ext->getInstanceMethod(Property->getGetterName())) 3638 GetterMethod->setPropertyAccessor(true); 3639 if (!Property->isReadOnly()) 3640 if (ObjCMethodDecl *SetterMethod 3641 = Ext->getInstanceMethod(Property->getSetterName())) 3642 SetterMethod->setPropertyAccessor(true); 3643 } 3644 } 3645 } 3646 ImplMethodsVsClassMethods(S, IC, IDecl); 3647 AtomicPropertySetterGetterRules(IC, IDecl); 3648 DiagnoseOwningPropertyGetterSynthesis(IC); 3649 DiagnoseUnusedBackingIvarInAccessor(S, IC); 3650 if (IDecl->hasDesignatedInitializers()) 3651 DiagnoseMissingDesignatedInitOverrides(IC, IDecl); 3652 3653 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>(); 3654 if (IDecl->getSuperClass() == nullptr) { 3655 // This class has no superclass, so check that it has been marked with 3656 // __attribute((objc_root_class)). 3657 if (!HasRootClassAttr) { 3658 SourceLocation DeclLoc(IDecl->getLocation()); 3659 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc)); 3660 Diag(DeclLoc, diag::warn_objc_root_class_missing) 3661 << IDecl->getIdentifier(); 3662 // See if NSObject is in the current scope, and if it is, suggest 3663 // adding " : NSObject " to the class declaration. 3664 NamedDecl *IF = LookupSingleName(TUScope, 3665 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject), 3666 DeclLoc, LookupOrdinaryName); 3667 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 3668 if (NSObjectDecl && NSObjectDecl->getDefinition()) { 3669 Diag(SuperClassLoc, diag::note_objc_needs_superclass) 3670 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject "); 3671 } else { 3672 Diag(SuperClassLoc, diag::note_objc_needs_superclass); 3673 } 3674 } 3675 } else if (HasRootClassAttr) { 3676 // Complain that only root classes may have this attribute. 3677 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass); 3678 } 3679 3680 if (LangOpts.ObjCRuntime.isNonFragile()) { 3681 while (IDecl->getSuperClass()) { 3682 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass()); 3683 IDecl = IDecl->getSuperClass(); 3684 } 3685 } 3686 } 3687 SetIvarInitializers(IC); 3688 } else if (ObjCCategoryImplDecl* CatImplClass = 3689 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { 3690 CatImplClass->setAtEndRange(AtEnd); 3691 3692 // Find category interface decl and then check that all methods declared 3693 // in this interface are implemented in the category @implementation. 3694 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { 3695 if (ObjCCategoryDecl *Cat 3696 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) { 3697 ImplMethodsVsClassMethods(S, CatImplClass, Cat); 3698 } 3699 } 3700 } 3701 if (isInterfaceDeclKind) { 3702 // Reject invalid vardecls. 3703 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 3704 DeclGroupRef DG = allTUVars[i].get(); 3705 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 3706 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { 3707 if (!VDecl->hasExternalStorage()) 3708 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); 3709 } 3710 } 3711 } 3712 ActOnObjCContainerFinishDefinition(); 3713 3714 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 3715 DeclGroupRef DG = allTUVars[i].get(); 3716 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 3717 (*I)->setTopLevelDeclInObjCContainer(); 3718 Consumer.HandleTopLevelDeclInObjCContainer(DG); 3719 } 3720 3721 ActOnDocumentableDecl(ClassDecl); 3722 return ClassDecl; 3723 } 3724 3725 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for 3726 /// objective-c's type qualifier from the parser version of the same info. 3727 static Decl::ObjCDeclQualifier 3728 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { 3729 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal; 3730 } 3731 3732 /// \brief Check whether the declared result type of the given Objective-C 3733 /// method declaration is compatible with the method's class. 3734 /// 3735 static Sema::ResultTypeCompatibilityKind 3736 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, 3737 ObjCInterfaceDecl *CurrentClass) { 3738 QualType ResultType = Method->getReturnType(); 3739 3740 // If an Objective-C method inherits its related result type, then its 3741 // declared result type must be compatible with its own class type. The 3742 // declared result type is compatible if: 3743 if (const ObjCObjectPointerType *ResultObjectType 3744 = ResultType->getAs<ObjCObjectPointerType>()) { 3745 // - it is id or qualified id, or 3746 if (ResultObjectType->isObjCIdType() || 3747 ResultObjectType->isObjCQualifiedIdType()) 3748 return Sema::RTC_Compatible; 3749 3750 if (CurrentClass) { 3751 if (ObjCInterfaceDecl *ResultClass 3752 = ResultObjectType->getInterfaceDecl()) { 3753 // - it is the same as the method's class type, or 3754 if (declaresSameEntity(CurrentClass, ResultClass)) 3755 return Sema::RTC_Compatible; 3756 3757 // - it is a superclass of the method's class type 3758 if (ResultClass->isSuperClassOf(CurrentClass)) 3759 return Sema::RTC_Compatible; 3760 } 3761 } else { 3762 // Any Objective-C pointer type might be acceptable for a protocol 3763 // method; we just don't know. 3764 return Sema::RTC_Unknown; 3765 } 3766 } 3767 3768 return Sema::RTC_Incompatible; 3769 } 3770 3771 namespace { 3772 /// A helper class for searching for methods which a particular method 3773 /// overrides. 3774 class OverrideSearch { 3775 public: 3776 Sema &S; 3777 ObjCMethodDecl *Method; 3778 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden; 3779 bool Recursive; 3780 3781 public: 3782 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) { 3783 Selector selector = method->getSelector(); 3784 3785 // Bypass this search if we've never seen an instance/class method 3786 // with this selector before. 3787 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector); 3788 if (it == S.MethodPool.end()) { 3789 if (!S.getExternalSource()) return; 3790 S.ReadMethodPool(selector); 3791 3792 it = S.MethodPool.find(selector); 3793 if (it == S.MethodPool.end()) 3794 return; 3795 } 3796 ObjCMethodList &list = 3797 method->isInstanceMethod() ? it->second.first : it->second.second; 3798 if (!list.getMethod()) return; 3799 3800 ObjCContainerDecl *container 3801 = cast<ObjCContainerDecl>(method->getDeclContext()); 3802 3803 // Prevent the search from reaching this container again. This is 3804 // important with categories, which override methods from the 3805 // interface and each other. 3806 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) { 3807 searchFromContainer(container); 3808 if (ObjCInterfaceDecl *Interface = Category->getClassInterface()) 3809 searchFromContainer(Interface); 3810 } else { 3811 searchFromContainer(container); 3812 } 3813 } 3814 3815 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator; 3816 iterator begin() const { return Overridden.begin(); } 3817 iterator end() const { return Overridden.end(); } 3818 3819 private: 3820 void searchFromContainer(ObjCContainerDecl *container) { 3821 if (container->isInvalidDecl()) return; 3822 3823 switch (container->getDeclKind()) { 3824 #define OBJCCONTAINER(type, base) \ 3825 case Decl::type: \ 3826 searchFrom(cast<type##Decl>(container)); \ 3827 break; 3828 #define ABSTRACT_DECL(expansion) 3829 #define DECL(type, base) \ 3830 case Decl::type: 3831 #include "clang/AST/DeclNodes.inc" 3832 llvm_unreachable("not an ObjC container!"); 3833 } 3834 } 3835 3836 void searchFrom(ObjCProtocolDecl *protocol) { 3837 if (!protocol->hasDefinition()) 3838 return; 3839 3840 // A method in a protocol declaration overrides declarations from 3841 // referenced ("parent") protocols. 3842 search(protocol->getReferencedProtocols()); 3843 } 3844 3845 void searchFrom(ObjCCategoryDecl *category) { 3846 // A method in a category declaration overrides declarations from 3847 // the main class and from protocols the category references. 3848 // The main class is handled in the constructor. 3849 search(category->getReferencedProtocols()); 3850 } 3851 3852 void searchFrom(ObjCCategoryImplDecl *impl) { 3853 // A method in a category definition that has a category 3854 // declaration overrides declarations from the category 3855 // declaration. 3856 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) { 3857 search(category); 3858 if (ObjCInterfaceDecl *Interface = category->getClassInterface()) 3859 search(Interface); 3860 3861 // Otherwise it overrides declarations from the class. 3862 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) { 3863 search(Interface); 3864 } 3865 } 3866 3867 void searchFrom(ObjCInterfaceDecl *iface) { 3868 // A method in a class declaration overrides declarations from 3869 if (!iface->hasDefinition()) 3870 return; 3871 3872 // - categories, 3873 for (auto *Cat : iface->known_categories()) 3874 search(Cat); 3875 3876 // - the super class, and 3877 if (ObjCInterfaceDecl *super = iface->getSuperClass()) 3878 search(super); 3879 3880 // - any referenced protocols. 3881 search(iface->getReferencedProtocols()); 3882 } 3883 3884 void searchFrom(ObjCImplementationDecl *impl) { 3885 // A method in a class implementation overrides declarations from 3886 // the class interface. 3887 if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) 3888 search(Interface); 3889 } 3890 3891 void search(const ObjCProtocolList &protocols) { 3892 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end(); 3893 i != e; ++i) 3894 search(*i); 3895 } 3896 3897 void search(ObjCContainerDecl *container) { 3898 // Check for a method in this container which matches this selector. 3899 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(), 3900 Method->isInstanceMethod(), 3901 /*AllowHidden=*/true); 3902 3903 // If we find one, record it and bail out. 3904 if (meth) { 3905 Overridden.insert(meth); 3906 return; 3907 } 3908 3909 // Otherwise, search for methods that a hypothetical method here 3910 // would have overridden. 3911 3912 // Note that we're now in a recursive case. 3913 Recursive = true; 3914 3915 searchFromContainer(container); 3916 } 3917 }; 3918 } // end anonymous namespace 3919 3920 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 3921 ObjCInterfaceDecl *CurrentClass, 3922 ResultTypeCompatibilityKind RTC) { 3923 // Search for overridden methods and merge information down from them. 3924 OverrideSearch overrides(*this, ObjCMethod); 3925 // Keep track if the method overrides any method in the class's base classes, 3926 // its protocols, or its categories' protocols; we will keep that info 3927 // in the ObjCMethodDecl. 3928 // For this info, a method in an implementation is not considered as 3929 // overriding the same method in the interface or its categories. 3930 bool hasOverriddenMethodsInBaseOrProtocol = false; 3931 for (OverrideSearch::iterator 3932 i = overrides.begin(), e = overrides.end(); i != e; ++i) { 3933 ObjCMethodDecl *overridden = *i; 3934 3935 if (!hasOverriddenMethodsInBaseOrProtocol) { 3936 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) || 3937 CurrentClass != overridden->getClassInterface() || 3938 overridden->isOverriding()) { 3939 hasOverriddenMethodsInBaseOrProtocol = true; 3940 3941 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) { 3942 // OverrideSearch will return as "overridden" the same method in the 3943 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to 3944 // check whether a category of a base class introduced a method with the 3945 // same selector, after the interface method declaration. 3946 // To avoid unnecessary lookups in the majority of cases, we use the 3947 // extra info bits in GlobalMethodPool to check whether there were any 3948 // category methods with this selector. 3949 GlobalMethodPool::iterator It = 3950 MethodPool.find(ObjCMethod->getSelector()); 3951 if (It != MethodPool.end()) { 3952 ObjCMethodList &List = 3953 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second; 3954 unsigned CategCount = List.getBits(); 3955 if (CategCount > 0) { 3956 // If the method is in a category we'll do lookup if there were at 3957 // least 2 category methods recorded, otherwise only one will do. 3958 if (CategCount > 1 || 3959 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) { 3960 OverrideSearch overrides(*this, overridden); 3961 for (OverrideSearch::iterator 3962 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) { 3963 ObjCMethodDecl *SuperOverridden = *OI; 3964 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) || 3965 CurrentClass != SuperOverridden->getClassInterface()) { 3966 hasOverriddenMethodsInBaseOrProtocol = true; 3967 overridden->setOverriding(true); 3968 break; 3969 } 3970 } 3971 } 3972 } 3973 } 3974 } 3975 } 3976 3977 // Propagate down the 'related result type' bit from overridden methods. 3978 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType()) 3979 ObjCMethod->SetRelatedResultType(); 3980 3981 // Then merge the declarations. 3982 mergeObjCMethodDecls(ObjCMethod, overridden); 3983 3984 if (ObjCMethod->isImplicit() && overridden->isImplicit()) 3985 continue; // Conflicting properties are detected elsewhere. 3986 3987 // Check for overriding methods 3988 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 3989 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) 3990 CheckConflictingOverridingMethod(ObjCMethod, overridden, 3991 isa<ObjCProtocolDecl>(overridden->getDeclContext())); 3992 3993 if (CurrentClass && overridden->getDeclContext() != CurrentClass && 3994 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && 3995 !overridden->isImplicit() /* not meant for properties */) { 3996 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(), 3997 E = ObjCMethod->param_end(); 3998 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(), 3999 PrevE = overridden->param_end(); 4000 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) { 4001 assert(PrevI != overridden->param_end() && "Param mismatch"); 4002 QualType T1 = Context.getCanonicalType((*ParamI)->getType()); 4003 QualType T2 = Context.getCanonicalType((*PrevI)->getType()); 4004 // If type of argument of method in this class does not match its 4005 // respective argument type in the super class method, issue warning; 4006 if (!Context.typesAreCompatible(T1, T2)) { 4007 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super) 4008 << T1 << T2; 4009 Diag(overridden->getLocation(), diag::note_previous_declaration); 4010 break; 4011 } 4012 } 4013 } 4014 } 4015 4016 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol); 4017 } 4018 4019 /// Merge type nullability from for a redeclaration of the same entity, 4020 /// producing the updated type of the redeclared entity. 4021 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc, 4022 QualType type, 4023 bool usesCSKeyword, 4024 SourceLocation prevLoc, 4025 QualType prevType, 4026 bool prevUsesCSKeyword) { 4027 // Determine the nullability of both types. 4028 auto nullability = type->getNullability(S.Context); 4029 auto prevNullability = prevType->getNullability(S.Context); 4030 4031 // Easy case: both have nullability. 4032 if (nullability.hasValue() == prevNullability.hasValue()) { 4033 // Neither has nullability; continue. 4034 if (!nullability) 4035 return type; 4036 4037 // The nullabilities are equivalent; do nothing. 4038 if (*nullability == *prevNullability) 4039 return type; 4040 4041 // Complain about mismatched nullability. 4042 S.Diag(loc, diag::err_nullability_conflicting) 4043 << DiagNullabilityKind(*nullability, usesCSKeyword) 4044 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword); 4045 return type; 4046 } 4047 4048 // If it's the redeclaration that has nullability, don't change anything. 4049 if (nullability) 4050 return type; 4051 4052 // Otherwise, provide the result with the same nullability. 4053 return S.Context.getAttributedType( 4054 AttributedType::getNullabilityAttrKind(*prevNullability), 4055 type, type); 4056 } 4057 4058 /// Merge information from the declaration of a method in the \@interface 4059 /// (or a category/extension) into the corresponding method in the 4060 /// @implementation (for a class or category). 4061 static void mergeInterfaceMethodToImpl(Sema &S, 4062 ObjCMethodDecl *method, 4063 ObjCMethodDecl *prevMethod) { 4064 // Merge the objc_requires_super attribute. 4065 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() && 4066 !method->hasAttr<ObjCRequiresSuperAttr>()) { 4067 // merge the attribute into implementation. 4068 method->addAttr( 4069 ObjCRequiresSuperAttr::CreateImplicit(S.Context, 4070 method->getLocation())); 4071 } 4072 4073 // Merge nullability of the result type. 4074 QualType newReturnType 4075 = mergeTypeNullabilityForRedecl( 4076 S, method->getReturnTypeSourceRange().getBegin(), 4077 method->getReturnType(), 4078 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4079 prevMethod->getReturnTypeSourceRange().getBegin(), 4080 prevMethod->getReturnType(), 4081 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4082 method->setReturnType(newReturnType); 4083 4084 // Handle each of the parameters. 4085 unsigned numParams = method->param_size(); 4086 unsigned numPrevParams = prevMethod->param_size(); 4087 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) { 4088 ParmVarDecl *param = method->param_begin()[i]; 4089 ParmVarDecl *prevParam = prevMethod->param_begin()[i]; 4090 4091 // Merge nullability. 4092 QualType newParamType 4093 = mergeTypeNullabilityForRedecl( 4094 S, param->getLocation(), param->getType(), 4095 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4096 prevParam->getLocation(), prevParam->getType(), 4097 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4098 param->setType(newParamType); 4099 } 4100 } 4101 4102 Decl *Sema::ActOnMethodDeclaration( 4103 Scope *S, 4104 SourceLocation MethodLoc, SourceLocation EndLoc, 4105 tok::TokenKind MethodType, 4106 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 4107 ArrayRef<SourceLocation> SelectorLocs, 4108 Selector Sel, 4109 // optional arguments. The number of types/arguments is obtained 4110 // from the Sel.getNumArgs(). 4111 ObjCArgInfo *ArgInfo, 4112 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 4113 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind, 4114 bool isVariadic, bool MethodDefinition) { 4115 // Make sure we can establish a context for the method. 4116 if (!CurContext->isObjCContainer()) { 4117 Diag(MethodLoc, diag::error_missing_method_context); 4118 return nullptr; 4119 } 4120 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 4121 Decl *ClassDecl = cast<Decl>(OCD); 4122 QualType resultDeclType; 4123 4124 bool HasRelatedResultType = false; 4125 TypeSourceInfo *ReturnTInfo = nullptr; 4126 if (ReturnType) { 4127 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo); 4128 4129 if (CheckFunctionReturnType(resultDeclType, MethodLoc)) 4130 return nullptr; 4131 4132 QualType bareResultType = resultDeclType; 4133 (void)AttributedType::stripOuterNullability(bareResultType); 4134 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType()); 4135 } else { // get the type for "id". 4136 resultDeclType = Context.getObjCIdType(); 4137 Diag(MethodLoc, diag::warn_missing_method_return_type) 4138 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)"); 4139 } 4140 4141 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create( 4142 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext, 4143 MethodType == tok::minus, isVariadic, 4144 /*isPropertyAccessor=*/false, 4145 /*isImplicitlyDeclared=*/false, /*isDefined=*/false, 4146 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional 4147 : ObjCMethodDecl::Required, 4148 HasRelatedResultType); 4149 4150 SmallVector<ParmVarDecl*, 16> Params; 4151 4152 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { 4153 QualType ArgType; 4154 TypeSourceInfo *DI; 4155 4156 if (!ArgInfo[i].Type) { 4157 ArgType = Context.getObjCIdType(); 4158 DI = nullptr; 4159 } else { 4160 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); 4161 } 4162 4163 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 4164 LookupOrdinaryName, ForRedeclaration); 4165 LookupName(R, S); 4166 if (R.isSingleResult()) { 4167 NamedDecl *PrevDecl = R.getFoundDecl(); 4168 if (S->isDeclScope(PrevDecl)) { 4169 Diag(ArgInfo[i].NameLoc, 4170 (MethodDefinition ? diag::warn_method_param_redefinition 4171 : diag::warn_method_param_declaration)) 4172 << ArgInfo[i].Name; 4173 Diag(PrevDecl->getLocation(), 4174 diag::note_previous_declaration); 4175 } 4176 } 4177 4178 SourceLocation StartLoc = DI 4179 ? DI->getTypeLoc().getBeginLoc() 4180 : ArgInfo[i].NameLoc; 4181 4182 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc, 4183 ArgInfo[i].NameLoc, ArgInfo[i].Name, 4184 ArgType, DI, SC_None); 4185 4186 Param->setObjCMethodScopeInfo(i); 4187 4188 Param->setObjCDeclQualifier( 4189 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); 4190 4191 // Apply the attributes to the parameter. 4192 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs); 4193 4194 if (Param->hasAttr<BlocksAttr>()) { 4195 Diag(Param->getLocation(), diag::err_block_on_nonlocal); 4196 Param->setInvalidDecl(); 4197 } 4198 S->AddDecl(Param); 4199 IdResolver.AddDecl(Param); 4200 4201 Params.push_back(Param); 4202 } 4203 4204 for (unsigned i = 0, e = CNumArgs; i != e; ++i) { 4205 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); 4206 QualType ArgType = Param->getType(); 4207 if (ArgType.isNull()) 4208 ArgType = Context.getObjCIdType(); 4209 else 4210 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 4211 ArgType = Context.getAdjustedParameterType(ArgType); 4212 4213 Param->setDeclContext(ObjCMethod); 4214 Params.push_back(Param); 4215 } 4216 4217 ObjCMethod->setMethodParams(Context, Params, SelectorLocs); 4218 ObjCMethod->setObjCDeclQualifier( 4219 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); 4220 4221 if (AttrList) 4222 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList); 4223 4224 // Add the method now. 4225 const ObjCMethodDecl *PrevMethod = nullptr; 4226 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) { 4227 if (MethodType == tok::minus) { 4228 PrevMethod = ImpDecl->getInstanceMethod(Sel); 4229 ImpDecl->addInstanceMethod(ObjCMethod); 4230 } else { 4231 PrevMethod = ImpDecl->getClassMethod(Sel); 4232 ImpDecl->addClassMethod(ObjCMethod); 4233 } 4234 4235 // Merge information from the @interface declaration into the 4236 // @implementation. 4237 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) { 4238 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 4239 ObjCMethod->isInstanceMethod())) { 4240 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD); 4241 4242 // Warn about defining -dealloc in a category. 4243 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() && 4244 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) { 4245 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category) 4246 << ObjCMethod->getDeclName(); 4247 } 4248 } 4249 } 4250 } else { 4251 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); 4252 } 4253 4254 if (PrevMethod) { 4255 // You can never have two method definitions with the same name. 4256 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) 4257 << ObjCMethod->getDeclName(); 4258 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 4259 ObjCMethod->setInvalidDecl(); 4260 return ObjCMethod; 4261 } 4262 4263 // If this Objective-C method does not have a related result type, but we 4264 // are allowed to infer related result types, try to do so based on the 4265 // method family. 4266 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 4267 if (!CurrentClass) { 4268 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) 4269 CurrentClass = Cat->getClassInterface(); 4270 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl)) 4271 CurrentClass = Impl->getClassInterface(); 4272 else if (ObjCCategoryImplDecl *CatImpl 4273 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) 4274 CurrentClass = CatImpl->getClassInterface(); 4275 } 4276 4277 ResultTypeCompatibilityKind RTC 4278 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass); 4279 4280 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC); 4281 4282 bool ARCError = false; 4283 if (getLangOpts().ObjCAutoRefCount) 4284 ARCError = CheckARCMethodDecl(ObjCMethod); 4285 4286 // Infer the related result type when possible. 4287 if (!ARCError && RTC == Sema::RTC_Compatible && 4288 !ObjCMethod->hasRelatedResultType() && 4289 LangOpts.ObjCInferRelatedResultType) { 4290 bool InferRelatedResultType = false; 4291 switch (ObjCMethod->getMethodFamily()) { 4292 case OMF_None: 4293 case OMF_copy: 4294 case OMF_dealloc: 4295 case OMF_finalize: 4296 case OMF_mutableCopy: 4297 case OMF_release: 4298 case OMF_retainCount: 4299 case OMF_initialize: 4300 case OMF_performSelector: 4301 break; 4302 4303 case OMF_alloc: 4304 case OMF_new: 4305 InferRelatedResultType = ObjCMethod->isClassMethod(); 4306 break; 4307 4308 case OMF_init: 4309 case OMF_autorelease: 4310 case OMF_retain: 4311 case OMF_self: 4312 InferRelatedResultType = ObjCMethod->isInstanceMethod(); 4313 break; 4314 } 4315 4316 if (InferRelatedResultType && 4317 !ObjCMethod->getReturnType()->isObjCIndependentClassType()) 4318 ObjCMethod->SetRelatedResultType(); 4319 } 4320 4321 ActOnDocumentableDecl(ObjCMethod); 4322 4323 return ObjCMethod; 4324 } 4325 4326 bool Sema::CheckObjCDeclScope(Decl *D) { 4327 // Following is also an error. But it is caused by a missing @end 4328 // and diagnostic is issued elsewhere. 4329 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) 4330 return false; 4331 4332 // If we switched context to translation unit while we are still lexically in 4333 // an objc container, it means the parser missed emitting an error. 4334 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) 4335 return false; 4336 4337 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); 4338 D->setInvalidDecl(); 4339 4340 return true; 4341 } 4342 4343 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the 4344 /// instance variables of ClassName into Decls. 4345 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 4346 IdentifierInfo *ClassName, 4347 SmallVectorImpl<Decl*> &Decls) { 4348 // Check that ClassName is a valid class 4349 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart); 4350 if (!Class) { 4351 Diag(DeclStart, diag::err_undef_interface) << ClassName; 4352 return; 4353 } 4354 if (LangOpts.ObjCRuntime.isNonFragile()) { 4355 Diag(DeclStart, diag::err_atdef_nonfragile_interface); 4356 return; 4357 } 4358 4359 // Collect the instance variables 4360 SmallVector<const ObjCIvarDecl*, 32> Ivars; 4361 Context.DeepCollectObjCIvars(Class, true, Ivars); 4362 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 4363 for (unsigned i = 0; i < Ivars.size(); i++) { 4364 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]); 4365 RecordDecl *Record = dyn_cast<RecordDecl>(TagD); 4366 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, 4367 /*FIXME: StartL=*/ID->getLocation(), 4368 ID->getLocation(), 4369 ID->getIdentifier(), ID->getType(), 4370 ID->getBitWidth()); 4371 Decls.push_back(FD); 4372 } 4373 4374 // Introduce all of these fields into the appropriate scope. 4375 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin(); 4376 D != Decls.end(); ++D) { 4377 FieldDecl *FD = cast<FieldDecl>(*D); 4378 if (getLangOpts().CPlusPlus) 4379 PushOnScopeChains(cast<FieldDecl>(FD), S); 4380 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD)) 4381 Record->addDecl(FD); 4382 } 4383 } 4384 4385 /// \brief Build a type-check a new Objective-C exception variable declaration. 4386 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, 4387 SourceLocation StartLoc, 4388 SourceLocation IdLoc, 4389 IdentifierInfo *Id, 4390 bool Invalid) { 4391 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 4392 // duration shall not be qualified by an address-space qualifier." 4393 // Since all parameters have automatic store duration, they can not have 4394 // an address space. 4395 if (T.getAddressSpace() != 0) { 4396 Diag(IdLoc, diag::err_arg_with_address_space); 4397 Invalid = true; 4398 } 4399 4400 // An @catch parameter must be an unqualified object pointer type; 4401 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? 4402 if (Invalid) { 4403 // Don't do any further checking. 4404 } else if (T->isDependentType()) { 4405 // Okay: we don't know what this type will instantiate to. 4406 } else if (!T->isObjCObjectPointerType()) { 4407 Invalid = true; 4408 Diag(IdLoc ,diag::err_catch_param_not_objc_type); 4409 } else if (T->isObjCQualifiedIdType()) { 4410 Invalid = true; 4411 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm); 4412 } 4413 4414 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, 4415 T, TInfo, SC_None); 4416 New->setExceptionVariable(true); 4417 4418 // In ARC, infer 'retaining' for variables of retainable type. 4419 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) 4420 Invalid = true; 4421 4422 if (Invalid) 4423 New->setInvalidDecl(); 4424 return New; 4425 } 4426 4427 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { 4428 const DeclSpec &DS = D.getDeclSpec(); 4429 4430 // We allow the "register" storage class on exception variables because 4431 // GCC did, but we drop it completely. Any other storage class is an error. 4432 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 4433 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm) 4434 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc())); 4435 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4436 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm) 4437 << DeclSpec::getSpecifierName(SCS); 4438 } 4439 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 4440 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 4441 diag::err_invalid_thread) 4442 << DeclSpec::getSpecifierName(TSCS); 4443 D.getMutableDeclSpec().ClearStorageClassSpecs(); 4444 4445 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4446 4447 // Check that there are no default arguments inside the type of this 4448 // exception object (C++ only). 4449 if (getLangOpts().CPlusPlus) 4450 CheckExtraCXXDefaultArguments(D); 4451 4452 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4453 QualType ExceptionType = TInfo->getType(); 4454 4455 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, 4456 D.getSourceRange().getBegin(), 4457 D.getIdentifierLoc(), 4458 D.getIdentifier(), 4459 D.isInvalidType()); 4460 4461 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 4462 if (D.getCXXScopeSpec().isSet()) { 4463 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) 4464 << D.getCXXScopeSpec().getRange(); 4465 New->setInvalidDecl(); 4466 } 4467 4468 // Add the parameter declaration into this scope. 4469 S->AddDecl(New); 4470 if (D.getIdentifier()) 4471 IdResolver.AddDecl(New); 4472 4473 ProcessDeclAttributes(S, New, D); 4474 4475 if (New->hasAttr<BlocksAttr>()) 4476 Diag(New->getLocation(), diag::err_block_on_nonlocal); 4477 return New; 4478 } 4479 4480 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 4481 /// initialization. 4482 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 4483 SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 4484 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 4485 Iv= Iv->getNextIvar()) { 4486 QualType QT = Context.getBaseElementType(Iv->getType()); 4487 if (QT->isRecordType()) 4488 Ivars.push_back(Iv); 4489 } 4490 } 4491 4492 void Sema::DiagnoseUseOfUnimplementedSelectors() { 4493 // Load referenced selectors from the external source. 4494 if (ExternalSource) { 4495 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels; 4496 ExternalSource->ReadReferencedSelectors(Sels); 4497 for (unsigned I = 0, N = Sels.size(); I != N; ++I) 4498 ReferencedSelectors[Sels[I].first] = Sels[I].second; 4499 } 4500 4501 // Warning will be issued only when selector table is 4502 // generated (which means there is at lease one implementation 4503 // in the TU). This is to match gcc's behavior. 4504 if (ReferencedSelectors.empty() || 4505 !Context.AnyObjCImplementation()) 4506 return; 4507 for (auto &SelectorAndLocation : ReferencedSelectors) { 4508 Selector Sel = SelectorAndLocation.first; 4509 SourceLocation Loc = SelectorAndLocation.second; 4510 if (!LookupImplementedMethodInGlobalPool(Sel)) 4511 Diag(Loc, diag::warn_unimplemented_selector) << Sel; 4512 } 4513 } 4514 4515 ObjCIvarDecl * 4516 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 4517 const ObjCPropertyDecl *&PDecl) const { 4518 if (Method->isClassMethod()) 4519 return nullptr; 4520 const ObjCInterfaceDecl *IDecl = Method->getClassInterface(); 4521 if (!IDecl) 4522 return nullptr; 4523 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true, 4524 /*shallowCategoryLookup=*/false, 4525 /*followSuper=*/false); 4526 if (!Method || !Method->isPropertyAccessor()) 4527 return nullptr; 4528 if ((PDecl = Method->findPropertyDecl())) 4529 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) { 4530 // property backing ivar must belong to property's class 4531 // or be a private ivar in class's implementation. 4532 // FIXME. fix the const-ness issue. 4533 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable( 4534 IV->getIdentifier()); 4535 return IV; 4536 } 4537 return nullptr; 4538 } 4539 4540 namespace { 4541 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property 4542 /// accessor references the backing ivar. 4543 class UnusedBackingIvarChecker : 4544 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> { 4545 public: 4546 Sema &S; 4547 const ObjCMethodDecl *Method; 4548 const ObjCIvarDecl *IvarD; 4549 bool AccessedIvar; 4550 bool InvokedSelfMethod; 4551 4552 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method, 4553 const ObjCIvarDecl *IvarD) 4554 : S(S), Method(Method), IvarD(IvarD), 4555 AccessedIvar(false), InvokedSelfMethod(false) { 4556 assert(IvarD); 4557 } 4558 4559 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 4560 if (E->getDecl() == IvarD) { 4561 AccessedIvar = true; 4562 return false; 4563 } 4564 return true; 4565 } 4566 4567 bool VisitObjCMessageExpr(ObjCMessageExpr *E) { 4568 if (E->getReceiverKind() == ObjCMessageExpr::Instance && 4569 S.isSelfExpr(E->getInstanceReceiver(), Method)) { 4570 InvokedSelfMethod = true; 4571 } 4572 return true; 4573 } 4574 }; 4575 } // end anonymous namespace 4576 4577 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S, 4578 const ObjCImplementationDecl *ImplD) { 4579 if (S->hasUnrecoverableErrorOccurred()) 4580 return; 4581 4582 for (const auto *CurMethod : ImplD->instance_methods()) { 4583 unsigned DIAG = diag::warn_unused_property_backing_ivar; 4584 SourceLocation Loc = CurMethod->getLocation(); 4585 if (Diags.isIgnored(DIAG, Loc)) 4586 continue; 4587 4588 const ObjCPropertyDecl *PDecl; 4589 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl); 4590 if (!IV) 4591 continue; 4592 4593 UnusedBackingIvarChecker Checker(*this, CurMethod, IV); 4594 Checker.TraverseStmt(CurMethod->getBody()); 4595 if (Checker.AccessedIvar) 4596 continue; 4597 4598 // Do not issue this warning if backing ivar is used somewhere and accessor 4599 // implementation makes a self call. This is to prevent false positive in 4600 // cases where the ivar is accessed by another method that the accessor 4601 // delegates to. 4602 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) { 4603 Diag(Loc, DIAG) << IV; 4604 Diag(PDecl->getLocation(), diag::note_property_declare); 4605 } 4606 } 4607 } 4608