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