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/DeclObjC.h" 19 #include "clang/AST/Expr.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/Basic/SourceManager.h" 22 #include "clang/Lex/Preprocessor.h" 23 #include "clang/Sema/DeclSpec.h" 24 #include "clang/Sema/ExternalSemaSource.h" 25 #include "clang/Sema/Lookup.h" 26 #include "clang/Sema/Scope.h" 27 #include "clang/Sema/ScopeInfo.h" 28 #include "llvm/ADT/DenseSet.h" 29 30 using namespace clang; 31 32 /// Check whether the given method, which must be in the 'init' 33 /// family, is a valid member of that family. 34 /// 35 /// \param receiverTypeIfCall - if null, check this as if declaring it; 36 /// if non-null, check this as if making a call to it with the given 37 /// receiver type 38 /// 39 /// \return true to indicate that there was an error and appropriate 40 /// actions were taken 41 bool Sema::checkInitMethod(ObjCMethodDecl *method, 42 QualType receiverTypeIfCall) { 43 if (method->isInvalidDecl()) return true; 44 45 // This castAs is safe: methods that don't return an object 46 // pointer won't be inferred as inits and will reject an explicit 47 // objc_method_family(init). 48 49 // We ignore protocols here. Should we? What about Class? 50 51 const ObjCObjectType *result = method->getResultType() 52 ->castAs<ObjCObjectPointerType>()->getObjectType(); 53 54 if (result->isObjCId()) { 55 return false; 56 } else if (result->isObjCClass()) { 57 // fall through: always an error 58 } else { 59 ObjCInterfaceDecl *resultClass = result->getInterface(); 60 assert(resultClass && "unexpected object type!"); 61 62 // It's okay for the result type to still be a forward declaration 63 // if we're checking an interface declaration. 64 if (!resultClass->hasDefinition()) { 65 if (receiverTypeIfCall.isNull() && 66 !isa<ObjCImplementationDecl>(method->getDeclContext())) 67 return false; 68 69 // Otherwise, we try to compare class types. 70 } else { 71 // If this method was declared in a protocol, we can't check 72 // anything unless we have a receiver type that's an interface. 73 const ObjCInterfaceDecl *receiverClass = 0; 74 if (isa<ObjCProtocolDecl>(method->getDeclContext())) { 75 if (receiverTypeIfCall.isNull()) 76 return false; 77 78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>() 79 ->getInterfaceDecl(); 80 81 // This can be null for calls to e.g. id<Foo>. 82 if (!receiverClass) return false; 83 } else { 84 receiverClass = method->getClassInterface(); 85 assert(receiverClass && "method not associated with a class!"); 86 } 87 88 // If either class is a subclass of the other, it's fine. 89 if (receiverClass->isSuperClassOf(resultClass) || 90 resultClass->isSuperClassOf(receiverClass)) 91 return false; 92 } 93 } 94 95 SourceLocation loc = method->getLocation(); 96 97 // If we're in a system header, and this is not a call, just make 98 // the method unusable. 99 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) { 100 method->addAttr(new (Context) UnavailableAttr(loc, Context, 101 "init method returns a type unrelated to its receiver type")); 102 return true; 103 } 104 105 // Otherwise, it's an error. 106 Diag(loc, diag::err_arc_init_method_unrelated_result_type); 107 method->setInvalidDecl(); 108 return true; 109 } 110 111 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 112 const ObjCMethodDecl *Overridden) { 113 if (Overridden->hasRelatedResultType() && 114 !NewMethod->hasRelatedResultType()) { 115 // This can only happen when the method follows a naming convention that 116 // implies a related result type, and the original (overridden) method has 117 // a suitable return type, but the new (overriding) method does not have 118 // a suitable return type. 119 QualType ResultType = NewMethod->getResultType(); 120 SourceRange ResultTypeRange; 121 if (const TypeSourceInfo *ResultTypeInfo 122 = NewMethod->getResultTypeSourceInfo()) 123 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange(); 124 125 // Figure out which class this method is part of, if any. 126 ObjCInterfaceDecl *CurrentClass 127 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext()); 128 if (!CurrentClass) { 129 DeclContext *DC = NewMethod->getDeclContext(); 130 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC)) 131 CurrentClass = Cat->getClassInterface(); 132 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC)) 133 CurrentClass = Impl->getClassInterface(); 134 else if (ObjCCategoryImplDecl *CatImpl 135 = dyn_cast<ObjCCategoryImplDecl>(DC)) 136 CurrentClass = CatImpl->getClassInterface(); 137 } 138 139 if (CurrentClass) { 140 Diag(NewMethod->getLocation(), 141 diag::warn_related_result_type_compatibility_class) 142 << Context.getObjCInterfaceType(CurrentClass) 143 << ResultType 144 << ResultTypeRange; 145 } else { 146 Diag(NewMethod->getLocation(), 147 diag::warn_related_result_type_compatibility_protocol) 148 << ResultType 149 << ResultTypeRange; 150 } 151 152 if (ObjCMethodFamily Family = Overridden->getMethodFamily()) 153 Diag(Overridden->getLocation(), 154 diag::note_related_result_type_family) 155 << /*overridden method*/ 0 156 << Family; 157 else 158 Diag(Overridden->getLocation(), 159 diag::note_related_result_type_overridden); 160 } 161 if (getLangOpts().ObjCAutoRefCount) { 162 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() != 163 Overridden->hasAttr<NSReturnsRetainedAttr>())) { 164 Diag(NewMethod->getLocation(), 165 diag::err_nsreturns_retained_attribute_mismatch) << 1; 166 Diag(Overridden->getLocation(), diag::note_previous_decl) 167 << "method"; 168 } 169 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() != 170 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) { 171 Diag(NewMethod->getLocation(), 172 diag::err_nsreturns_retained_attribute_mismatch) << 0; 173 Diag(Overridden->getLocation(), diag::note_previous_decl) 174 << "method"; 175 } 176 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(), 177 oe = Overridden->param_end(); 178 for (ObjCMethodDecl::param_iterator 179 ni = NewMethod->param_begin(), ne = NewMethod->param_end(); 180 ni != ne && oi != oe; ++ni, ++oi) { 181 const ParmVarDecl *oldDecl = (*oi); 182 ParmVarDecl *newDecl = (*ni); 183 if (newDecl->hasAttr<NSConsumedAttr>() != 184 oldDecl->hasAttr<NSConsumedAttr>()) { 185 Diag(newDecl->getLocation(), 186 diag::err_nsconsumed_attribute_mismatch); 187 Diag(oldDecl->getLocation(), diag::note_previous_decl) 188 << "parameter"; 189 } 190 } 191 } 192 } 193 194 /// \brief Check a method declaration for compatibility with the Objective-C 195 /// ARC conventions. 196 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) { 197 ObjCMethodFamily family = method->getMethodFamily(); 198 switch (family) { 199 case OMF_None: 200 case OMF_finalize: 201 case OMF_retain: 202 case OMF_release: 203 case OMF_autorelease: 204 case OMF_retainCount: 205 case OMF_self: 206 case OMF_performSelector: 207 return false; 208 209 case OMF_dealloc: 210 if (!Context.hasSameType(method->getResultType(), Context.VoidTy)) { 211 SourceRange ResultTypeRange; 212 if (const TypeSourceInfo *ResultTypeInfo 213 = method->getResultTypeSourceInfo()) 214 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange(); 215 if (ResultTypeRange.isInvalid()) 216 Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 217 << method->getResultType() 218 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)"); 219 else 220 Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 221 << method->getResultType() 222 << FixItHint::CreateReplacement(ResultTypeRange, "void"); 223 return true; 224 } 225 return false; 226 227 case OMF_init: 228 // If the method doesn't obey the init rules, don't bother annotating it. 229 if (checkInitMethod(method, QualType())) 230 return true; 231 232 method->addAttr(new (Context) NSConsumesSelfAttr(SourceLocation(), 233 Context)); 234 235 // Don't add a second copy of this attribute, but otherwise don't 236 // let it be suppressed. 237 if (method->hasAttr<NSReturnsRetainedAttr>()) 238 return false; 239 break; 240 241 case OMF_alloc: 242 case OMF_copy: 243 case OMF_mutableCopy: 244 case OMF_new: 245 if (method->hasAttr<NSReturnsRetainedAttr>() || 246 method->hasAttr<NSReturnsNotRetainedAttr>() || 247 method->hasAttr<NSReturnsAutoreleasedAttr>()) 248 return false; 249 break; 250 } 251 252 method->addAttr(new (Context) NSReturnsRetainedAttr(SourceLocation(), 253 Context)); 254 return false; 255 } 256 257 static void DiagnoseObjCImplementedDeprecations(Sema &S, 258 NamedDecl *ND, 259 SourceLocation ImplLoc, 260 int select) { 261 if (ND && ND->isDeprecated()) { 262 S.Diag(ImplLoc, diag::warn_deprecated_def) << select; 263 if (select == 0) 264 S.Diag(ND->getLocation(), diag::note_method_declared_at) 265 << ND->getDeclName(); 266 else 267 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class"; 268 } 269 } 270 271 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 272 /// pool. 273 void Sema::AddAnyMethodToGlobalPool(Decl *D) { 274 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 275 276 // If we don't have a valid method decl, simply return. 277 if (!MDecl) 278 return; 279 if (MDecl->isInstanceMethod()) 280 AddInstanceMethodToGlobalPool(MDecl, true); 281 else 282 AddFactoryMethodToGlobalPool(MDecl, true); 283 } 284 285 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer 286 /// has explicit ownership attribute; false otherwise. 287 static bool 288 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { 289 QualType T = Param->getType(); 290 291 if (const PointerType *PT = T->getAs<PointerType>()) { 292 T = PT->getPointeeType(); 293 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 294 T = RT->getPointeeType(); 295 } else { 296 return true; 297 } 298 299 // If we have a lifetime qualifier, but it's local, we must have 300 // inferred it. So, it is implicit. 301 return !T.getLocalQualifiers().hasObjCLifetime(); 302 } 303 304 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible 305 /// and user declared, in the method definition's AST. 306 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { 307 assert((getCurMethodDecl() == 0) && "Methodparsing confused"); 308 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 309 310 // If we don't have a valid method decl, simply return. 311 if (!MDecl) 312 return; 313 314 // Allow all of Sema to see that we are entering a method definition. 315 PushDeclContext(FnBodyScope, MDecl); 316 PushFunctionScope(); 317 318 // Create Decl objects for each parameter, entrring them in the scope for 319 // binding to their use. 320 321 // Insert the invisible arguments, self and _cmd! 322 MDecl->createImplicitParams(Context, MDecl->getClassInterface()); 323 324 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope); 325 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope); 326 327 // The ObjC parser requires parameter names so there's no need to check. 328 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(), 329 /*CheckParameterNames=*/false); 330 331 // Introduce all of the other parameters into this scope. 332 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(), 333 E = MDecl->param_end(); PI != E; ++PI) { 334 ParmVarDecl *Param = (*PI); 335 if (!Param->isInvalidDecl() && 336 getLangOpts().ObjCAutoRefCount && 337 !HasExplicitOwnershipAttr(*this, Param)) 338 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) << 339 Param->getType(); 340 341 if ((*PI)->getIdentifier()) 342 PushOnScopeChains(*PI, FnBodyScope); 343 } 344 345 // In ARC, disallow definition of retain/release/autorelease/retainCount 346 if (getLangOpts().ObjCAutoRefCount) { 347 switch (MDecl->getMethodFamily()) { 348 case OMF_retain: 349 case OMF_retainCount: 350 case OMF_release: 351 case OMF_autorelease: 352 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def) 353 << 0 << MDecl->getSelector(); 354 break; 355 356 case OMF_None: 357 case OMF_dealloc: 358 case OMF_finalize: 359 case OMF_alloc: 360 case OMF_init: 361 case OMF_mutableCopy: 362 case OMF_copy: 363 case OMF_new: 364 case OMF_self: 365 case OMF_performSelector: 366 break; 367 } 368 } 369 370 // Warn on deprecated methods under -Wdeprecated-implementations, 371 // and prepare for warning on missing super calls. 372 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) { 373 ObjCMethodDecl *IMD = 374 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()); 375 376 if (IMD) { 377 ObjCImplDecl *ImplDeclOfMethodDef = 378 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext()); 379 ObjCContainerDecl *ContDeclOfMethodDecl = 380 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext()); 381 ObjCImplDecl *ImplDeclOfMethodDecl = 0; 382 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl)) 383 ImplDeclOfMethodDecl = OID->getImplementation(); 384 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) 385 ImplDeclOfMethodDecl = CD->getImplementation(); 386 // No need to issue deprecated warning if deprecated mehod in class/category 387 // is being implemented in its own implementation (no overriding is involved). 388 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef) 389 DiagnoseObjCImplementedDeprecations(*this, 390 dyn_cast<NamedDecl>(IMD), 391 MDecl->getLocation(), 0); 392 } 393 394 if (MDecl->getMethodFamily() == OMF_init) { 395 if (MDecl->isDesignatedInitializerForTheInterface()) { 396 getCurFunction()->ObjCIsDesignatedInit = true; 397 getCurFunction()->ObjCWarnForNoDesignatedInitChain = 398 IC->getSuperClass() != 0; 399 } else if (IC->hasDesignatedInitializers()) { 400 getCurFunction()->ObjCIsSecondaryInit = true; 401 getCurFunction()->ObjCWarnForNoInitDelegation = true; 402 } 403 } 404 405 // If this is "dealloc" or "finalize", set some bit here. 406 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false. 407 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set. 408 // Only do this if the current class actually has a superclass. 409 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) { 410 ObjCMethodFamily Family = MDecl->getMethodFamily(); 411 if (Family == OMF_dealloc) { 412 if (!(getLangOpts().ObjCAutoRefCount || 413 getLangOpts().getGC() == LangOptions::GCOnly)) 414 getCurFunction()->ObjCShouldCallSuper = true; 415 416 } else if (Family == OMF_finalize) { 417 if (Context.getLangOpts().getGC() != LangOptions::NonGC) 418 getCurFunction()->ObjCShouldCallSuper = true; 419 420 } else { 421 const ObjCMethodDecl *SuperMethod = 422 SuperClass->lookupMethod(MDecl->getSelector(), 423 MDecl->isInstanceMethod()); 424 getCurFunction()->ObjCShouldCallSuper = 425 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>()); 426 } 427 } 428 } 429 } 430 431 namespace { 432 433 // Callback to only accept typo corrections that are Objective-C classes. 434 // If an ObjCInterfaceDecl* is given to the constructor, then the validation 435 // function will reject corrections to that class. 436 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback { 437 public: 438 ObjCInterfaceValidatorCCC() : CurrentIDecl(0) {} 439 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl) 440 : CurrentIDecl(IDecl) {} 441 442 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 443 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>(); 444 return ID && !declaresSameEntity(ID, CurrentIDecl); 445 } 446 447 private: 448 ObjCInterfaceDecl *CurrentIDecl; 449 }; 450 451 } 452 453 Decl *Sema:: 454 ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 455 IdentifierInfo *ClassName, SourceLocation ClassLoc, 456 IdentifierInfo *SuperName, SourceLocation SuperLoc, 457 Decl * const *ProtoRefs, unsigned NumProtoRefs, 458 const SourceLocation *ProtoLocs, 459 SourceLocation EndProtoLoc, AttributeList *AttrList) { 460 assert(ClassName && "Missing class identifier"); 461 462 // Check for another declaration kind with the same name. 463 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc, 464 LookupOrdinaryName, ForRedeclaration); 465 466 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 467 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 468 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 469 } 470 471 // Create a declaration to describe this @interface. 472 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 473 474 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 475 // A previous decl with a different name is because of 476 // @compatibility_alias, for example: 477 // \code 478 // @class NewImage; 479 // @compatibility_alias OldImage NewImage; 480 // \endcode 481 // A lookup for 'OldImage' will return the 'NewImage' decl. 482 // 483 // In such a case use the real declaration name, instead of the alias one, 484 // otherwise we will break IdentifierResolver and redecls-chain invariants. 485 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 486 // has been aliased. 487 ClassName = PrevIDecl->getIdentifier(); 488 } 489 490 ObjCInterfaceDecl *IDecl 491 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName, 492 PrevIDecl, ClassLoc); 493 494 if (PrevIDecl) { 495 // Class already seen. Was it a definition? 496 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 497 Diag(AtInterfaceLoc, diag::err_duplicate_class_def) 498 << PrevIDecl->getDeclName(); 499 Diag(Def->getLocation(), diag::note_previous_definition); 500 IDecl->setInvalidDecl(); 501 } 502 } 503 504 if (AttrList) 505 ProcessDeclAttributeList(TUScope, IDecl, AttrList); 506 PushOnScopeChains(IDecl, TUScope); 507 508 // Start the definition of this class. If we're in a redefinition case, there 509 // may already be a definition, so we'll end up adding to it. 510 if (!IDecl->hasDefinition()) 511 IDecl->startDefinition(); 512 513 if (SuperName) { 514 // Check if a different kind of symbol declared in this scope. 515 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 516 LookupOrdinaryName); 517 518 if (!PrevDecl) { 519 // Try to correct for a typo in the superclass name without correcting 520 // to the class we're defining. 521 ObjCInterfaceValidatorCCC Validator(IDecl); 522 if (TypoCorrection Corrected = CorrectTypo( 523 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope, 524 NULL, Validator)) { 525 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest) 526 << SuperName << ClassName); 527 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>(); 528 } 529 } 530 531 if (declaresSameEntity(PrevDecl, IDecl)) { 532 Diag(SuperLoc, diag::err_recursive_superclass) 533 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 534 IDecl->setEndOfDefinitionLoc(ClassLoc); 535 } else { 536 ObjCInterfaceDecl *SuperClassDecl = 537 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 538 539 // Diagnose classes that inherit from deprecated classes. 540 if (SuperClassDecl) 541 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc); 542 543 if (PrevDecl && SuperClassDecl == 0) { 544 // The previous declaration was not a class decl. Check if we have a 545 // typedef. If we do, get the underlying class type. 546 if (const TypedefNameDecl *TDecl = 547 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 548 QualType T = TDecl->getUnderlyingType(); 549 if (T->isObjCObjectType()) { 550 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) { 551 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl); 552 // This handles the following case: 553 // @interface NewI @end 554 // typedef NewI DeprI __attribute__((deprecated("blah"))) 555 // @interface SI : DeprI /* warn here */ @end 556 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc); 557 } 558 } 559 } 560 561 // This handles the following case: 562 // 563 // typedef int SuperClass; 564 // @interface MyClass : SuperClass {} @end 565 // 566 if (!SuperClassDecl) { 567 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName; 568 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 569 } 570 } 571 572 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 573 if (!SuperClassDecl) 574 Diag(SuperLoc, diag::err_undef_superclass) 575 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 576 else if (RequireCompleteType(SuperLoc, 577 Context.getObjCInterfaceType(SuperClassDecl), 578 diag::err_forward_superclass, 579 SuperClassDecl->getDeclName(), 580 ClassName, 581 SourceRange(AtInterfaceLoc, ClassLoc))) { 582 SuperClassDecl = 0; 583 } 584 } 585 IDecl->setSuperClass(SuperClassDecl); 586 IDecl->setSuperClassLoc(SuperLoc); 587 IDecl->setEndOfDefinitionLoc(SuperLoc); 588 } 589 } else { // we have a root class. 590 IDecl->setEndOfDefinitionLoc(ClassLoc); 591 } 592 593 // Check then save referenced protocols. 594 if (NumProtoRefs) { 595 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 596 ProtoLocs, Context); 597 IDecl->setEndOfDefinitionLoc(EndProtoLoc); 598 } 599 600 CheckObjCDeclScope(IDecl); 601 return ActOnObjCContainerStartDefinition(IDecl); 602 } 603 604 /// ActOnTypedefedProtocols - this action finds protocol list as part of the 605 /// typedef'ed use for a qualified super class and adds them to the list 606 /// of the protocols. 607 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 608 IdentifierInfo *SuperName, 609 SourceLocation SuperLoc) { 610 if (!SuperName) 611 return; 612 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 613 LookupOrdinaryName); 614 if (!IDecl) 615 return; 616 617 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) { 618 QualType T = TDecl->getUnderlyingType(); 619 if (T->isObjCObjectType()) 620 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) 621 for (ObjCObjectType::qual_iterator I = OPT->qual_begin(), 622 E = OPT->qual_end(); I != E; ++I) 623 ProtocolRefs.push_back(*I); 624 } 625 } 626 627 /// ActOnCompatibilityAlias - this action is called after complete parsing of 628 /// a \@compatibility_alias declaration. It sets up the alias relationships. 629 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc, 630 IdentifierInfo *AliasName, 631 SourceLocation AliasLocation, 632 IdentifierInfo *ClassName, 633 SourceLocation ClassLocation) { 634 // Look for previous declaration of alias name 635 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation, 636 LookupOrdinaryName, ForRedeclaration); 637 if (ADecl) { 638 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName; 639 Diag(ADecl->getLocation(), diag::note_previous_declaration); 640 return 0; 641 } 642 // Check for class declaration 643 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 644 LookupOrdinaryName, ForRedeclaration); 645 if (const TypedefNameDecl *TDecl = 646 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) { 647 QualType T = TDecl->getUnderlyingType(); 648 if (T->isObjCObjectType()) { 649 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) { 650 ClassName = IDecl->getIdentifier(); 651 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 652 LookupOrdinaryName, ForRedeclaration); 653 } 654 } 655 } 656 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU); 657 if (CDecl == 0) { 658 Diag(ClassLocation, diag::warn_undef_interface) << ClassName; 659 if (CDeclU) 660 Diag(CDeclU->getLocation(), diag::note_previous_declaration); 661 return 0; 662 } 663 664 // Everything checked out, instantiate a new alias declaration AST. 665 ObjCCompatibleAliasDecl *AliasDecl = 666 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl); 667 668 if (!CheckObjCDeclScope(AliasDecl)) 669 PushOnScopeChains(AliasDecl, TUScope); 670 671 return AliasDecl; 672 } 673 674 bool Sema::CheckForwardProtocolDeclarationForCircularDependency( 675 IdentifierInfo *PName, 676 SourceLocation &Ploc, SourceLocation PrevLoc, 677 const ObjCList<ObjCProtocolDecl> &PList) { 678 679 bool res = false; 680 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(), 681 E = PList.end(); I != E; ++I) { 682 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(), 683 Ploc)) { 684 if (PDecl->getIdentifier() == PName) { 685 Diag(Ploc, diag::err_protocol_has_circular_dependency); 686 Diag(PrevLoc, diag::note_previous_definition); 687 res = true; 688 } 689 690 if (!PDecl->hasDefinition()) 691 continue; 692 693 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc, 694 PDecl->getLocation(), PDecl->getReferencedProtocols())) 695 res = true; 696 } 697 } 698 return res; 699 } 700 701 Decl * 702 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc, 703 IdentifierInfo *ProtocolName, 704 SourceLocation ProtocolLoc, 705 Decl * const *ProtoRefs, 706 unsigned NumProtoRefs, 707 const SourceLocation *ProtoLocs, 708 SourceLocation EndProtoLoc, 709 AttributeList *AttrList) { 710 bool err = false; 711 // FIXME: Deal with AttrList. 712 assert(ProtocolName && "Missing protocol identifier"); 713 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc, 714 ForRedeclaration); 715 ObjCProtocolDecl *PDecl = 0; 716 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : 0) { 717 // If we already have a definition, complain. 718 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName; 719 Diag(Def->getLocation(), diag::note_previous_definition); 720 721 // Create a new protocol that is completely distinct from previous 722 // declarations, and do not make this protocol available for name lookup. 723 // That way, we'll end up completely ignoring the duplicate. 724 // FIXME: Can we turn this into an error? 725 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 726 ProtocolLoc, AtProtoInterfaceLoc, 727 /*PrevDecl=*/0); 728 PDecl->startDefinition(); 729 } else { 730 if (PrevDecl) { 731 // Check for circular dependencies among protocol declarations. This can 732 // only happen if this protocol was forward-declared. 733 ObjCList<ObjCProtocolDecl> PList; 734 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context); 735 err = CheckForwardProtocolDeclarationForCircularDependency( 736 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList); 737 } 738 739 // Create the new declaration. 740 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 741 ProtocolLoc, AtProtoInterfaceLoc, 742 /*PrevDecl=*/PrevDecl); 743 744 PushOnScopeChains(PDecl, TUScope); 745 PDecl->startDefinition(); 746 } 747 748 if (AttrList) 749 ProcessDeclAttributeList(TUScope, PDecl, AttrList); 750 751 // Merge attributes from previous declarations. 752 if (PrevDecl) 753 mergeDeclAttributes(PDecl, PrevDecl); 754 755 if (!err && NumProtoRefs ) { 756 /// Check then save referenced protocols. 757 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 758 ProtoLocs, Context); 759 } 760 761 CheckObjCDeclScope(PDecl); 762 return ActOnObjCContainerStartDefinition(PDecl); 763 } 764 765 /// FindProtocolDeclaration - This routine looks up protocols and 766 /// issues an error if they are not declared. It returns list of 767 /// protocol declarations in its 'Protocols' argument. 768 void 769 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, 770 const IdentifierLocPair *ProtocolId, 771 unsigned NumProtocols, 772 SmallVectorImpl<Decl *> &Protocols) { 773 for (unsigned i = 0; i != NumProtocols; ++i) { 774 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first, 775 ProtocolId[i].second); 776 if (!PDecl) { 777 DeclFilterCCC<ObjCProtocolDecl> Validator; 778 TypoCorrection Corrected = CorrectTypo( 779 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second), 780 LookupObjCProtocolName, TUScope, NULL, Validator); 781 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) 782 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest) 783 << ProtocolId[i].first); 784 } 785 786 if (!PDecl) { 787 Diag(ProtocolId[i].second, diag::err_undeclared_protocol) 788 << ProtocolId[i].first; 789 continue; 790 } 791 // If this is a forward protocol declaration, get its definition. 792 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition()) 793 PDecl = PDecl->getDefinition(); 794 795 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second); 796 797 // If this is a forward declaration and we are supposed to warn in this 798 // case, do it. 799 // FIXME: Recover nicely in the hidden case. 800 if (WarnOnDeclarations && 801 (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden())) 802 Diag(ProtocolId[i].second, diag::warn_undef_protocolref) 803 << ProtocolId[i].first; 804 Protocols.push_back(PDecl); 805 } 806 } 807 808 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of 809 /// a class method in its extension. 810 /// 811 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 812 ObjCInterfaceDecl *ID) { 813 if (!ID) 814 return; // Possibly due to previous error 815 816 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap; 817 for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(), 818 e = ID->meth_end(); i != e; ++i) { 819 ObjCMethodDecl *MD = *i; 820 MethodMap[MD->getSelector()] = MD; 821 } 822 823 if (MethodMap.empty()) 824 return; 825 for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(), 826 e = CAT->meth_end(); i != e; ++i) { 827 ObjCMethodDecl *Method = *i; 828 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()]; 829 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) { 830 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 831 << Method->getDeclName(); 832 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 833 } 834 } 835 } 836 837 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo; 838 Sema::DeclGroupPtrTy 839 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc, 840 const IdentifierLocPair *IdentList, 841 unsigned NumElts, 842 AttributeList *attrList) { 843 SmallVector<Decl *, 8> DeclsInGroup; 844 for (unsigned i = 0; i != NumElts; ++i) { 845 IdentifierInfo *Ident = IdentList[i].first; 846 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second, 847 ForRedeclaration); 848 ObjCProtocolDecl *PDecl 849 = ObjCProtocolDecl::Create(Context, CurContext, Ident, 850 IdentList[i].second, AtProtocolLoc, 851 PrevDecl); 852 853 PushOnScopeChains(PDecl, TUScope); 854 CheckObjCDeclScope(PDecl); 855 856 if (attrList) 857 ProcessDeclAttributeList(TUScope, PDecl, attrList); 858 859 if (PrevDecl) 860 mergeDeclAttributes(PDecl, PrevDecl); 861 862 DeclsInGroup.push_back(PDecl); 863 } 864 865 return BuildDeclaratorGroup(DeclsInGroup, false); 866 } 867 868 Decl *Sema:: 869 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 870 IdentifierInfo *ClassName, SourceLocation ClassLoc, 871 IdentifierInfo *CategoryName, 872 SourceLocation CategoryLoc, 873 Decl * const *ProtoRefs, 874 unsigned NumProtoRefs, 875 const SourceLocation *ProtoLocs, 876 SourceLocation EndProtoLoc) { 877 ObjCCategoryDecl *CDecl; 878 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 879 880 /// Check that class of this category is already completely declared. 881 882 if (!IDecl 883 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 884 diag::err_category_forward_interface, 885 CategoryName == 0)) { 886 // Create an invalid ObjCCategoryDecl to serve as context for 887 // the enclosing method declarations. We mark the decl invalid 888 // to make it clear that this isn't a valid AST. 889 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 890 ClassLoc, CategoryLoc, CategoryName,IDecl); 891 CDecl->setInvalidDecl(); 892 CurContext->addDecl(CDecl); 893 894 if (!IDecl) 895 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 896 return ActOnObjCContainerStartDefinition(CDecl); 897 } 898 899 if (!CategoryName && IDecl->getImplementation()) { 900 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName; 901 Diag(IDecl->getImplementation()->getLocation(), 902 diag::note_implementation_declared); 903 } 904 905 if (CategoryName) { 906 /// Check for duplicate interface declaration for this category 907 if (ObjCCategoryDecl *Previous 908 = IDecl->FindCategoryDeclaration(CategoryName)) { 909 // Class extensions can be declared multiple times, categories cannot. 910 Diag(CategoryLoc, diag::warn_dup_category_def) 911 << ClassName << CategoryName; 912 Diag(Previous->getLocation(), diag::note_previous_definition); 913 } 914 } 915 916 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 917 ClassLoc, CategoryLoc, CategoryName, IDecl); 918 // FIXME: PushOnScopeChains? 919 CurContext->addDecl(CDecl); 920 921 if (NumProtoRefs) { 922 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 923 ProtoLocs, Context); 924 // Protocols in the class extension belong to the class. 925 if (CDecl->IsClassExtension()) 926 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, 927 NumProtoRefs, Context); 928 } 929 930 CheckObjCDeclScope(CDecl); 931 return ActOnObjCContainerStartDefinition(CDecl); 932 } 933 934 /// ActOnStartCategoryImplementation - Perform semantic checks on the 935 /// category implementation declaration and build an ObjCCategoryImplDecl 936 /// object. 937 Decl *Sema::ActOnStartCategoryImplementation( 938 SourceLocation AtCatImplLoc, 939 IdentifierInfo *ClassName, SourceLocation ClassLoc, 940 IdentifierInfo *CatName, SourceLocation CatLoc) { 941 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 942 ObjCCategoryDecl *CatIDecl = 0; 943 if (IDecl && IDecl->hasDefinition()) { 944 CatIDecl = IDecl->FindCategoryDeclaration(CatName); 945 if (!CatIDecl) { 946 // Category @implementation with no corresponding @interface. 947 // Create and install one. 948 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc, 949 ClassLoc, CatLoc, 950 CatName, IDecl); 951 CatIDecl->setImplicit(); 952 } 953 } 954 955 ObjCCategoryImplDecl *CDecl = 956 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl, 957 ClassLoc, AtCatImplLoc, CatLoc); 958 /// Check that class of this category is already completely declared. 959 if (!IDecl) { 960 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 961 CDecl->setInvalidDecl(); 962 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 963 diag::err_undef_interface)) { 964 CDecl->setInvalidDecl(); 965 } 966 967 // FIXME: PushOnScopeChains? 968 CurContext->addDecl(CDecl); 969 970 // If the interface is deprecated/unavailable, warn/error about it. 971 if (IDecl) 972 DiagnoseUseOfDecl(IDecl, ClassLoc); 973 974 /// Check that CatName, category name, is not used in another implementation. 975 if (CatIDecl) { 976 if (CatIDecl->getImplementation()) { 977 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName 978 << CatName; 979 Diag(CatIDecl->getImplementation()->getLocation(), 980 diag::note_previous_definition); 981 CDecl->setInvalidDecl(); 982 } else { 983 CatIDecl->setImplementation(CDecl); 984 // Warn on implementating category of deprecated class under 985 // -Wdeprecated-implementations flag. 986 DiagnoseObjCImplementedDeprecations(*this, 987 dyn_cast<NamedDecl>(IDecl), 988 CDecl->getLocation(), 2); 989 } 990 } 991 992 CheckObjCDeclScope(CDecl); 993 return ActOnObjCContainerStartDefinition(CDecl); 994 } 995 996 Decl *Sema::ActOnStartClassImplementation( 997 SourceLocation AtClassImplLoc, 998 IdentifierInfo *ClassName, SourceLocation ClassLoc, 999 IdentifierInfo *SuperClassname, 1000 SourceLocation SuperClassLoc) { 1001 ObjCInterfaceDecl *IDecl = 0; 1002 // Check for another declaration kind with the same name. 1003 NamedDecl *PrevDecl 1004 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName, 1005 ForRedeclaration); 1006 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1007 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 1008 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1009 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) { 1010 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1011 diag::warn_undef_interface); 1012 } else { 1013 // We did not find anything with the name ClassName; try to correct for 1014 // typos in the class name. 1015 ObjCInterfaceValidatorCCC Validator; 1016 TypoCorrection Corrected = 1017 CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc), 1018 LookupOrdinaryName, TUScope, NULL, Validator); 1019 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 1020 // Suggest the (potentially) correct interface name. Don't provide a 1021 // code-modification hint or use the typo name for recovery, because 1022 // this is just a warning. The program may actually be correct. 1023 diagnoseTypo(Corrected, 1024 PDiag(diag::warn_undef_interface_suggest) << ClassName, 1025 /*ErrorRecovery*/false); 1026 } else { 1027 Diag(ClassLoc, diag::warn_undef_interface) << ClassName; 1028 } 1029 } 1030 1031 // Check that super class name is valid class name 1032 ObjCInterfaceDecl* SDecl = 0; 1033 if (SuperClassname) { 1034 // Check if a different kind of symbol declared in this scope. 1035 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc, 1036 LookupOrdinaryName); 1037 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1038 Diag(SuperClassLoc, diag::err_redefinition_different_kind) 1039 << SuperClassname; 1040 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1041 } else { 1042 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 1043 if (SDecl && !SDecl->hasDefinition()) 1044 SDecl = 0; 1045 if (!SDecl) 1046 Diag(SuperClassLoc, diag::err_undef_superclass) 1047 << SuperClassname << ClassName; 1048 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) { 1049 // This implementation and its interface do not have the same 1050 // super class. 1051 Diag(SuperClassLoc, diag::err_conflicting_super_class) 1052 << SDecl->getDeclName(); 1053 Diag(SDecl->getLocation(), diag::note_previous_definition); 1054 } 1055 } 1056 } 1057 1058 if (!IDecl) { 1059 // Legacy case of @implementation with no corresponding @interface. 1060 // Build, chain & install the interface decl into the identifier. 1061 1062 // FIXME: Do we support attributes on the @implementation? If so we should 1063 // copy them over. 1064 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc, 1065 ClassName, /*PrevDecl=*/0, ClassLoc, 1066 true); 1067 IDecl->startDefinition(); 1068 if (SDecl) { 1069 IDecl->setSuperClass(SDecl); 1070 IDecl->setSuperClassLoc(SuperClassLoc); 1071 IDecl->setEndOfDefinitionLoc(SuperClassLoc); 1072 } else { 1073 IDecl->setEndOfDefinitionLoc(ClassLoc); 1074 } 1075 1076 PushOnScopeChains(IDecl, TUScope); 1077 } else { 1078 // Mark the interface as being completed, even if it was just as 1079 // @class ....; 1080 // declaration; the user cannot reopen it. 1081 if (!IDecl->hasDefinition()) 1082 IDecl->startDefinition(); 1083 } 1084 1085 ObjCImplementationDecl* IMPDecl = 1086 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl, 1087 ClassLoc, AtClassImplLoc, SuperClassLoc); 1088 1089 if (CheckObjCDeclScope(IMPDecl)) 1090 return ActOnObjCContainerStartDefinition(IMPDecl); 1091 1092 // Check that there is no duplicate implementation of this class. 1093 if (IDecl->getImplementation()) { 1094 // FIXME: Don't leak everything! 1095 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName; 1096 Diag(IDecl->getImplementation()->getLocation(), 1097 diag::note_previous_definition); 1098 IMPDecl->setInvalidDecl(); 1099 } else { // add it to the list. 1100 IDecl->setImplementation(IMPDecl); 1101 PushOnScopeChains(IMPDecl, TUScope); 1102 // Warn on implementating deprecated class under 1103 // -Wdeprecated-implementations flag. 1104 DiagnoseObjCImplementedDeprecations(*this, 1105 dyn_cast<NamedDecl>(IDecl), 1106 IMPDecl->getLocation(), 1); 1107 } 1108 return ActOnObjCContainerStartDefinition(IMPDecl); 1109 } 1110 1111 Sema::DeclGroupPtrTy 1112 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) { 1113 SmallVector<Decl *, 64> DeclsInGroup; 1114 DeclsInGroup.reserve(Decls.size() + 1); 1115 1116 for (unsigned i = 0, e = Decls.size(); i != e; ++i) { 1117 Decl *Dcl = Decls[i]; 1118 if (!Dcl) 1119 continue; 1120 if (Dcl->getDeclContext()->isFileContext()) 1121 Dcl->setTopLevelDeclInObjCContainer(); 1122 DeclsInGroup.push_back(Dcl); 1123 } 1124 1125 DeclsInGroup.push_back(ObjCImpDecl); 1126 1127 return BuildDeclaratorGroup(DeclsInGroup, false); 1128 } 1129 1130 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 1131 ObjCIvarDecl **ivars, unsigned numIvars, 1132 SourceLocation RBrace) { 1133 assert(ImpDecl && "missing implementation decl"); 1134 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface(); 1135 if (!IDecl) 1136 return; 1137 /// Check case of non-existing \@interface decl. 1138 /// (legacy objective-c \@implementation decl without an \@interface decl). 1139 /// Add implementations's ivar to the synthesize class's ivar list. 1140 if (IDecl->isImplicitInterfaceDecl()) { 1141 IDecl->setEndOfDefinitionLoc(RBrace); 1142 // Add ivar's to class's DeclContext. 1143 for (unsigned i = 0, e = numIvars; i != e; ++i) { 1144 ivars[i]->setLexicalDeclContext(ImpDecl); 1145 IDecl->makeDeclVisibleInContext(ivars[i]); 1146 ImpDecl->addDecl(ivars[i]); 1147 } 1148 1149 return; 1150 } 1151 // If implementation has empty ivar list, just return. 1152 if (numIvars == 0) 1153 return; 1154 1155 assert(ivars && "missing @implementation ivars"); 1156 if (LangOpts.ObjCRuntime.isNonFragile()) { 1157 if (ImpDecl->getSuperClass()) 1158 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use); 1159 for (unsigned i = 0; i < numIvars; i++) { 1160 ObjCIvarDecl* ImplIvar = ivars[i]; 1161 if (const ObjCIvarDecl *ClsIvar = 1162 IDecl->getIvarDecl(ImplIvar->getIdentifier())) { 1163 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 1164 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 1165 continue; 1166 } 1167 // Check class extensions (unnamed categories) for duplicate ivars. 1168 for (ObjCInterfaceDecl::visible_extensions_iterator 1169 Ext = IDecl->visible_extensions_begin(), 1170 ExtEnd = IDecl->visible_extensions_end(); 1171 Ext != ExtEnd; ++Ext) { 1172 ObjCCategoryDecl *CDecl = *Ext; 1173 if (const ObjCIvarDecl *ClsExtIvar = 1174 CDecl->getIvarDecl(ImplIvar->getIdentifier())) { 1175 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 1176 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 1177 continue; 1178 } 1179 } 1180 // Instance ivar to Implementation's DeclContext. 1181 ImplIvar->setLexicalDeclContext(ImpDecl); 1182 IDecl->makeDeclVisibleInContext(ImplIvar); 1183 ImpDecl->addDecl(ImplIvar); 1184 } 1185 return; 1186 } 1187 // Check interface's Ivar list against those in the implementation. 1188 // names and types must match. 1189 // 1190 unsigned j = 0; 1191 ObjCInterfaceDecl::ivar_iterator 1192 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end(); 1193 for (; numIvars > 0 && IVI != IVE; ++IVI) { 1194 ObjCIvarDecl* ImplIvar = ivars[j++]; 1195 ObjCIvarDecl* ClsIvar = *IVI; 1196 assert (ImplIvar && "missing implementation ivar"); 1197 assert (ClsIvar && "missing class ivar"); 1198 1199 // First, make sure the types match. 1200 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) { 1201 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type) 1202 << ImplIvar->getIdentifier() 1203 << ImplIvar->getType() << ClsIvar->getType(); 1204 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 1205 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() && 1206 ImplIvar->getBitWidthValue(Context) != 1207 ClsIvar->getBitWidthValue(Context)) { 1208 Diag(ImplIvar->getBitWidth()->getLocStart(), 1209 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier(); 1210 Diag(ClsIvar->getBitWidth()->getLocStart(), 1211 diag::note_previous_definition); 1212 } 1213 // Make sure the names are identical. 1214 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) { 1215 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name) 1216 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier(); 1217 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 1218 } 1219 --numIvars; 1220 } 1221 1222 if (numIvars > 0) 1223 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count); 1224 else if (IVI != IVE) 1225 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count); 1226 } 1227 1228 void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method, 1229 bool &IncompleteImpl, unsigned DiagID) { 1230 // No point warning no definition of method which is 'unavailable'. 1231 switch (method->getAvailability()) { 1232 case AR_Available: 1233 case AR_Deprecated: 1234 break; 1235 1236 // Don't warn about unavailable or not-yet-introduced methods. 1237 case AR_NotYetIntroduced: 1238 case AR_Unavailable: 1239 return; 1240 } 1241 1242 // FIXME: For now ignore 'IncompleteImpl'. 1243 // Previously we grouped all unimplemented methods under a single 1244 // warning, but some users strongly voiced that they would prefer 1245 // separate warnings. We will give that approach a try, as that 1246 // matches what we do with protocols. 1247 1248 Diag(ImpLoc, DiagID) << method->getDeclName(); 1249 1250 // Issue a note to the original declaration. 1251 SourceLocation MethodLoc = method->getLocStart(); 1252 if (MethodLoc.isValid()) 1253 Diag(MethodLoc, diag::note_method_declared_at) << method; 1254 } 1255 1256 /// Determines if type B can be substituted for type A. Returns true if we can 1257 /// guarantee that anything that the user will do to an object of type A can 1258 /// also be done to an object of type B. This is trivially true if the two 1259 /// types are the same, or if B is a subclass of A. It becomes more complex 1260 /// in cases where protocols are involved. 1261 /// 1262 /// Object types in Objective-C describe the minimum requirements for an 1263 /// object, rather than providing a complete description of a type. For 1264 /// example, if A is a subclass of B, then B* may refer to an instance of A. 1265 /// The principle of substitutability means that we may use an instance of A 1266 /// anywhere that we may use an instance of B - it will implement all of the 1267 /// ivars of B and all of the methods of B. 1268 /// 1269 /// This substitutability is important when type checking methods, because 1270 /// the implementation may have stricter type definitions than the interface. 1271 /// The interface specifies minimum requirements, but the implementation may 1272 /// have more accurate ones. For example, a method may privately accept 1273 /// instances of B, but only publish that it accepts instances of A. Any 1274 /// object passed to it will be type checked against B, and so will implicitly 1275 /// by a valid A*. Similarly, a method may return a subclass of the class that 1276 /// it is declared as returning. 1277 /// 1278 /// This is most important when considering subclassing. A method in a 1279 /// subclass must accept any object as an argument that its superclass's 1280 /// implementation accepts. It may, however, accept a more general type 1281 /// without breaking substitutability (i.e. you can still use the subclass 1282 /// anywhere that you can use the superclass, but not vice versa). The 1283 /// converse requirement applies to return types: the return type for a 1284 /// subclass method must be a valid object of the kind that the superclass 1285 /// advertises, but it may be specified more accurately. This avoids the need 1286 /// for explicit down-casting by callers. 1287 /// 1288 /// Note: This is a stricter requirement than for assignment. 1289 static bool isObjCTypeSubstitutable(ASTContext &Context, 1290 const ObjCObjectPointerType *A, 1291 const ObjCObjectPointerType *B, 1292 bool rejectId) { 1293 // Reject a protocol-unqualified id. 1294 if (rejectId && B->isObjCIdType()) return false; 1295 1296 // If B is a qualified id, then A must also be a qualified id and it must 1297 // implement all of the protocols in B. It may not be a qualified class. 1298 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a 1299 // stricter definition so it is not substitutable for id<A>. 1300 if (B->isObjCQualifiedIdType()) { 1301 return A->isObjCQualifiedIdType() && 1302 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0), 1303 QualType(B,0), 1304 false); 1305 } 1306 1307 /* 1308 // id is a special type that bypasses type checking completely. We want a 1309 // warning when it is used in one place but not another. 1310 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false; 1311 1312 1313 // If B is a qualified id, then A must also be a qualified id (which it isn't 1314 // if we've got this far) 1315 if (B->isObjCQualifiedIdType()) return false; 1316 */ 1317 1318 // Now we know that A and B are (potentially-qualified) class types. The 1319 // normal rules for assignment apply. 1320 return Context.canAssignObjCInterfaces(A, B); 1321 } 1322 1323 static SourceRange getTypeRange(TypeSourceInfo *TSI) { 1324 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange()); 1325 } 1326 1327 static bool CheckMethodOverrideReturn(Sema &S, 1328 ObjCMethodDecl *MethodImpl, 1329 ObjCMethodDecl *MethodDecl, 1330 bool IsProtocolMethodDecl, 1331 bool IsOverridingMode, 1332 bool Warn) { 1333 if (IsProtocolMethodDecl && 1334 (MethodDecl->getObjCDeclQualifier() != 1335 MethodImpl->getObjCDeclQualifier())) { 1336 if (Warn) { 1337 S.Diag(MethodImpl->getLocation(), 1338 (IsOverridingMode ? 1339 diag::warn_conflicting_overriding_ret_type_modifiers 1340 : diag::warn_conflicting_ret_type_modifiers)) 1341 << MethodImpl->getDeclName() 1342 << getTypeRange(MethodImpl->getResultTypeSourceInfo()); 1343 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration) 1344 << getTypeRange(MethodDecl->getResultTypeSourceInfo()); 1345 } 1346 else 1347 return false; 1348 } 1349 1350 if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(), 1351 MethodDecl->getResultType())) 1352 return true; 1353 if (!Warn) 1354 return false; 1355 1356 unsigned DiagID = 1357 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types 1358 : diag::warn_conflicting_ret_types; 1359 1360 // Mismatches between ObjC pointers go into a different warning 1361 // category, and sometimes they're even completely whitelisted. 1362 if (const ObjCObjectPointerType *ImplPtrTy = 1363 MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) { 1364 if (const ObjCObjectPointerType *IfacePtrTy = 1365 MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) { 1366 // Allow non-matching return types as long as they don't violate 1367 // the principle of substitutability. Specifically, we permit 1368 // return types that are subclasses of the declared return type, 1369 // or that are more-qualified versions of the declared type. 1370 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false)) 1371 return false; 1372 1373 DiagID = 1374 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types 1375 : diag::warn_non_covariant_ret_types; 1376 } 1377 } 1378 1379 S.Diag(MethodImpl->getLocation(), DiagID) 1380 << MethodImpl->getDeclName() 1381 << MethodDecl->getResultType() 1382 << MethodImpl->getResultType() 1383 << getTypeRange(MethodImpl->getResultTypeSourceInfo()); 1384 S.Diag(MethodDecl->getLocation(), 1385 IsOverridingMode ? diag::note_previous_declaration 1386 : diag::note_previous_definition) 1387 << getTypeRange(MethodDecl->getResultTypeSourceInfo()); 1388 return false; 1389 } 1390 1391 static bool CheckMethodOverrideParam(Sema &S, 1392 ObjCMethodDecl *MethodImpl, 1393 ObjCMethodDecl *MethodDecl, 1394 ParmVarDecl *ImplVar, 1395 ParmVarDecl *IfaceVar, 1396 bool IsProtocolMethodDecl, 1397 bool IsOverridingMode, 1398 bool Warn) { 1399 if (IsProtocolMethodDecl && 1400 (ImplVar->getObjCDeclQualifier() != 1401 IfaceVar->getObjCDeclQualifier())) { 1402 if (Warn) { 1403 if (IsOverridingMode) 1404 S.Diag(ImplVar->getLocation(), 1405 diag::warn_conflicting_overriding_param_modifiers) 1406 << getTypeRange(ImplVar->getTypeSourceInfo()) 1407 << MethodImpl->getDeclName(); 1408 else S.Diag(ImplVar->getLocation(), 1409 diag::warn_conflicting_param_modifiers) 1410 << getTypeRange(ImplVar->getTypeSourceInfo()) 1411 << MethodImpl->getDeclName(); 1412 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration) 1413 << getTypeRange(IfaceVar->getTypeSourceInfo()); 1414 } 1415 else 1416 return false; 1417 } 1418 1419 QualType ImplTy = ImplVar->getType(); 1420 QualType IfaceTy = IfaceVar->getType(); 1421 1422 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy)) 1423 return true; 1424 1425 if (!Warn) 1426 return false; 1427 unsigned DiagID = 1428 IsOverridingMode ? diag::warn_conflicting_overriding_param_types 1429 : diag::warn_conflicting_param_types; 1430 1431 // Mismatches between ObjC pointers go into a different warning 1432 // category, and sometimes they're even completely whitelisted. 1433 if (const ObjCObjectPointerType *ImplPtrTy = 1434 ImplTy->getAs<ObjCObjectPointerType>()) { 1435 if (const ObjCObjectPointerType *IfacePtrTy = 1436 IfaceTy->getAs<ObjCObjectPointerType>()) { 1437 // Allow non-matching argument types as long as they don't 1438 // violate the principle of substitutability. Specifically, the 1439 // implementation must accept any objects that the superclass 1440 // accepts, however it may also accept others. 1441 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true)) 1442 return false; 1443 1444 DiagID = 1445 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types 1446 : diag::warn_non_contravariant_param_types; 1447 } 1448 } 1449 1450 S.Diag(ImplVar->getLocation(), DiagID) 1451 << getTypeRange(ImplVar->getTypeSourceInfo()) 1452 << MethodImpl->getDeclName() << IfaceTy << ImplTy; 1453 S.Diag(IfaceVar->getLocation(), 1454 (IsOverridingMode ? diag::note_previous_declaration 1455 : diag::note_previous_definition)) 1456 << getTypeRange(IfaceVar->getTypeSourceInfo()); 1457 return false; 1458 } 1459 1460 /// In ARC, check whether the conventional meanings of the two methods 1461 /// match. If they don't, it's a hard error. 1462 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl, 1463 ObjCMethodDecl *decl) { 1464 ObjCMethodFamily implFamily = impl->getMethodFamily(); 1465 ObjCMethodFamily declFamily = decl->getMethodFamily(); 1466 if (implFamily == declFamily) return false; 1467 1468 // Since conventions are sorted by selector, the only possibility is 1469 // that the types differ enough to cause one selector or the other 1470 // to fall out of the family. 1471 assert(implFamily == OMF_None || declFamily == OMF_None); 1472 1473 // No further diagnostics required on invalid declarations. 1474 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true; 1475 1476 const ObjCMethodDecl *unmatched = impl; 1477 ObjCMethodFamily family = declFamily; 1478 unsigned errorID = diag::err_arc_lost_method_convention; 1479 unsigned noteID = diag::note_arc_lost_method_convention; 1480 if (declFamily == OMF_None) { 1481 unmatched = decl; 1482 family = implFamily; 1483 errorID = diag::err_arc_gained_method_convention; 1484 noteID = diag::note_arc_gained_method_convention; 1485 } 1486 1487 // Indexes into a %select clause in the diagnostic. 1488 enum FamilySelector { 1489 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new 1490 }; 1491 FamilySelector familySelector = FamilySelector(); 1492 1493 switch (family) { 1494 case OMF_None: llvm_unreachable("logic error, no method convention"); 1495 case OMF_retain: 1496 case OMF_release: 1497 case OMF_autorelease: 1498 case OMF_dealloc: 1499 case OMF_finalize: 1500 case OMF_retainCount: 1501 case OMF_self: 1502 case OMF_performSelector: 1503 // Mismatches for these methods don't change ownership 1504 // conventions, so we don't care. 1505 return false; 1506 1507 case OMF_init: familySelector = F_init; break; 1508 case OMF_alloc: familySelector = F_alloc; break; 1509 case OMF_copy: familySelector = F_copy; break; 1510 case OMF_mutableCopy: familySelector = F_mutableCopy; break; 1511 case OMF_new: familySelector = F_new; break; 1512 } 1513 1514 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn }; 1515 ReasonSelector reasonSelector; 1516 1517 // The only reason these methods don't fall within their families is 1518 // due to unusual result types. 1519 if (unmatched->getResultType()->isObjCObjectPointerType()) { 1520 reasonSelector = R_UnrelatedReturn; 1521 } else { 1522 reasonSelector = R_NonObjectReturn; 1523 } 1524 1525 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector); 1526 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector); 1527 1528 return true; 1529 } 1530 1531 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, 1532 ObjCMethodDecl *MethodDecl, 1533 bool IsProtocolMethodDecl) { 1534 if (getLangOpts().ObjCAutoRefCount && 1535 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)) 1536 return; 1537 1538 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 1539 IsProtocolMethodDecl, false, 1540 true); 1541 1542 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 1543 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 1544 EF = MethodDecl->param_end(); 1545 IM != EM && IF != EF; ++IM, ++IF) { 1546 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF, 1547 IsProtocolMethodDecl, false, true); 1548 } 1549 1550 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) { 1551 Diag(ImpMethodDecl->getLocation(), 1552 diag::warn_conflicting_variadic); 1553 Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 1554 } 1555 } 1556 1557 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 1558 ObjCMethodDecl *Overridden, 1559 bool IsProtocolMethodDecl) { 1560 1561 CheckMethodOverrideReturn(*this, Method, Overridden, 1562 IsProtocolMethodDecl, true, 1563 true); 1564 1565 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(), 1566 IF = Overridden->param_begin(), EM = Method->param_end(), 1567 EF = Overridden->param_end(); 1568 IM != EM && IF != EF; ++IM, ++IF) { 1569 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF, 1570 IsProtocolMethodDecl, true, true); 1571 } 1572 1573 if (Method->isVariadic() != Overridden->isVariadic()) { 1574 Diag(Method->getLocation(), 1575 diag::warn_conflicting_overriding_variadic); 1576 Diag(Overridden->getLocation(), diag::note_previous_declaration); 1577 } 1578 } 1579 1580 /// WarnExactTypedMethods - This routine issues a warning if method 1581 /// implementation declaration matches exactly that of its declaration. 1582 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, 1583 ObjCMethodDecl *MethodDecl, 1584 bool IsProtocolMethodDecl) { 1585 // don't issue warning when protocol method is optional because primary 1586 // class is not required to implement it and it is safe for protocol 1587 // to implement it. 1588 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional) 1589 return; 1590 // don't issue warning when primary class's method is 1591 // depecated/unavailable. 1592 if (MethodDecl->hasAttr<UnavailableAttr>() || 1593 MethodDecl->hasAttr<DeprecatedAttr>()) 1594 return; 1595 1596 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 1597 IsProtocolMethodDecl, false, false); 1598 if (match) 1599 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 1600 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 1601 EF = MethodDecl->param_end(); 1602 IM != EM && IF != EF; ++IM, ++IF) { 1603 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, 1604 *IM, *IF, 1605 IsProtocolMethodDecl, false, false); 1606 if (!match) 1607 break; 1608 } 1609 if (match) 1610 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic()); 1611 if (match) 1612 match = !(MethodDecl->isClassMethod() && 1613 MethodDecl->getSelector() == GetNullarySelector("load", Context)); 1614 1615 if (match) { 1616 Diag(ImpMethodDecl->getLocation(), 1617 diag::warn_category_method_impl_match); 1618 Diag(MethodDecl->getLocation(), diag::note_method_declared_at) 1619 << MethodDecl->getDeclName(); 1620 } 1621 } 1622 1623 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely 1624 /// improve the efficiency of selector lookups and type checking by associating 1625 /// with each protocol / interface / category the flattened instance tables. If 1626 /// we used an immutable set to keep the table then it wouldn't add significant 1627 /// memory cost and it would be handy for lookups. 1628 1629 /// CheckProtocolMethodDefs - This routine checks unimplemented methods 1630 /// Declared in protocol, and those referenced by it. 1631 void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc, 1632 ObjCProtocolDecl *PDecl, 1633 bool& IncompleteImpl, 1634 const SelectorSet &InsMap, 1635 const SelectorSet &ClsMap, 1636 ObjCContainerDecl *CDecl) { 1637 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); 1638 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() 1639 : dyn_cast<ObjCInterfaceDecl>(CDecl); 1640 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null"); 1641 1642 ObjCInterfaceDecl *Super = IDecl->getSuperClass(); 1643 ObjCInterfaceDecl *NSIDecl = 0; 1644 if (getLangOpts().ObjCRuntime.isNeXTFamily()) { 1645 // check to see if class implements forwardInvocation method and objects 1646 // of this class are derived from 'NSProxy' so that to forward requests 1647 // from one object to another. 1648 // Under such conditions, which means that every method possible is 1649 // implemented in the class, we should not issue "Method definition not 1650 // found" warnings. 1651 // FIXME: Use a general GetUnarySelector method for this. 1652 IdentifierInfo* II = &Context.Idents.get("forwardInvocation"); 1653 Selector fISelector = Context.Selectors.getSelector(1, &II); 1654 if (InsMap.count(fISelector)) 1655 // Is IDecl derived from 'NSProxy'? If so, no instance methods 1656 // need be implemented in the implementation. 1657 NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy")); 1658 } 1659 1660 // If this is a forward protocol declaration, get its definition. 1661 if (!PDecl->isThisDeclarationADefinition() && 1662 PDecl->getDefinition()) 1663 PDecl = PDecl->getDefinition(); 1664 1665 // If a method lookup fails locally we still need to look and see if 1666 // the method was implemented by a base class or an inherited 1667 // protocol. This lookup is slow, but occurs rarely in correct code 1668 // and otherwise would terminate in a warning. 1669 1670 // check unimplemented instance methods. 1671 if (!NSIDecl) 1672 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(), 1673 E = PDecl->instmeth_end(); I != E; ++I) { 1674 ObjCMethodDecl *method = *I; 1675 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 1676 !method->isPropertyAccessor() && 1677 !InsMap.count(method->getSelector()) && 1678 (!Super || !Super->lookupMethod(method->getSelector(), 1679 true /* instance */, 1680 false /* shallowCategory */, 1681 true /* followsSuper */, 1682 NULL /* category */, 1683 PDecl /* protocol */))) { 1684 // If a method is not implemented in the category implementation but 1685 // has been declared in its primary class, superclass, 1686 // or in one of their protocols, no need to issue the warning. 1687 // This is because method will be implemented in the primary class 1688 // or one of its super class implementation. 1689 1690 // Ugly, but necessary. Method declared in protcol might have 1691 // have been synthesized due to a property declared in the class which 1692 // uses the protocol. 1693 if (ObjCMethodDecl *MethodInClass = 1694 IDecl->lookupMethod(method->getSelector(), 1695 true /* instance */, 1696 true /* shallowCategoryLookup */, 1697 false /* followSuper */)) 1698 if (C || MethodInClass->isPropertyAccessor()) 1699 continue; 1700 unsigned DIAG = diag::warn_unimplemented_protocol_method; 1701 if (Diags.getDiagnosticLevel(DIAG, ImpLoc) 1702 != DiagnosticsEngine::Ignored) { 1703 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG); 1704 Diag(CDecl->getLocation(), diag::note_required_for_protocol_at) 1705 << PDecl->getDeclName(); 1706 } 1707 } 1708 } 1709 // check unimplemented class methods 1710 for (ObjCProtocolDecl::classmeth_iterator 1711 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); 1712 I != E; ++I) { 1713 ObjCMethodDecl *method = *I; 1714 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 1715 !ClsMap.count(method->getSelector()) && 1716 (!Super || !Super->lookupMethod(method->getSelector(), 1717 false /* class method */, 1718 false /* shallowCategoryLookup */, 1719 true /* followSuper */, 1720 NULL /* category */, 1721 PDecl /* protocol */))) { 1722 // See above comment for instance method lookups. 1723 if (C && IDecl->lookupMethod(method->getSelector(), 1724 false /* class */, 1725 true /* shallowCategoryLookup */, 1726 false /* followSuper */)) 1727 continue; 1728 1729 unsigned DIAG = diag::warn_unimplemented_protocol_method; 1730 if (Diags.getDiagnosticLevel(DIAG, ImpLoc) != 1731 DiagnosticsEngine::Ignored) { 1732 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG); 1733 Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) << 1734 PDecl->getDeclName(); 1735 } 1736 } 1737 } 1738 // Check on this protocols's referenced protocols, recursively. 1739 for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(), 1740 E = PDecl->protocol_end(); PI != E; ++PI) 1741 CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, CDecl); 1742 } 1743 1744 /// MatchAllMethodDeclarations - Check methods declared in interface 1745 /// or protocol against those declared in their implementations. 1746 /// 1747 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, 1748 const SelectorSet &ClsMap, 1749 SelectorSet &InsMapSeen, 1750 SelectorSet &ClsMapSeen, 1751 ObjCImplDecl* IMPDecl, 1752 ObjCContainerDecl* CDecl, 1753 bool &IncompleteImpl, 1754 bool ImmediateClass, 1755 bool WarnCategoryMethodImpl) { 1756 // Check and see if instance methods in class interface have been 1757 // implemented in the implementation class. If so, their types match. 1758 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(), 1759 E = CDecl->instmeth_end(); I != E; ++I) { 1760 if (!InsMapSeen.insert((*I)->getSelector())) 1761 continue; 1762 if (!(*I)->isPropertyAccessor() && 1763 !InsMap.count((*I)->getSelector())) { 1764 if (ImmediateClass) 1765 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl, 1766 diag::warn_undef_method_impl); 1767 continue; 1768 } else { 1769 ObjCMethodDecl *ImpMethodDecl = 1770 IMPDecl->getInstanceMethod((*I)->getSelector()); 1771 assert(CDecl->getInstanceMethod((*I)->getSelector()) && 1772 "Expected to find the method through lookup as well"); 1773 ObjCMethodDecl *MethodDecl = *I; 1774 // ImpMethodDecl may be null as in a @dynamic property. 1775 if (ImpMethodDecl) { 1776 if (!WarnCategoryMethodImpl) 1777 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl, 1778 isa<ObjCProtocolDecl>(CDecl)); 1779 else if (!MethodDecl->isPropertyAccessor()) 1780 WarnExactTypedMethods(ImpMethodDecl, MethodDecl, 1781 isa<ObjCProtocolDecl>(CDecl)); 1782 } 1783 } 1784 } 1785 1786 // Check and see if class methods in class interface have been 1787 // implemented in the implementation class. If so, their types match. 1788 for (ObjCInterfaceDecl::classmeth_iterator I = CDecl->classmeth_begin(), 1789 E = CDecl->classmeth_end(); 1790 I != E; ++I) { 1791 if (!ClsMapSeen.insert((*I)->getSelector())) 1792 continue; 1793 if (!ClsMap.count((*I)->getSelector())) { 1794 if (ImmediateClass) 1795 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl, 1796 diag::warn_undef_method_impl); 1797 } else { 1798 ObjCMethodDecl *ImpMethodDecl = 1799 IMPDecl->getClassMethod((*I)->getSelector()); 1800 assert(CDecl->getClassMethod((*I)->getSelector()) && 1801 "Expected to find the method through lookup as well"); 1802 ObjCMethodDecl *MethodDecl = *I; 1803 if (!WarnCategoryMethodImpl) 1804 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl, 1805 isa<ObjCProtocolDecl>(CDecl)); 1806 else 1807 WarnExactTypedMethods(ImpMethodDecl, MethodDecl, 1808 isa<ObjCProtocolDecl>(CDecl)); 1809 } 1810 } 1811 1812 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) { 1813 // Also, check for methods declared in protocols inherited by 1814 // this protocol. 1815 for (ObjCProtocolDecl::protocol_iterator 1816 PI = PD->protocol_begin(), E = PD->protocol_end(); PI != E; ++PI) 1817 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1818 IMPDecl, (*PI), IncompleteImpl, false, 1819 WarnCategoryMethodImpl); 1820 } 1821 1822 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 1823 // when checking that methods in implementation match their declaration, 1824 // i.e. when WarnCategoryMethodImpl is false, check declarations in class 1825 // extension; as well as those in categories. 1826 if (!WarnCategoryMethodImpl) { 1827 for (ObjCInterfaceDecl::visible_categories_iterator 1828 Cat = I->visible_categories_begin(), 1829 CatEnd = I->visible_categories_end(); 1830 Cat != CatEnd; ++Cat) { 1831 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1832 IMPDecl, *Cat, IncompleteImpl, false, 1833 WarnCategoryMethodImpl); 1834 } 1835 } else { 1836 // Also methods in class extensions need be looked at next. 1837 for (ObjCInterfaceDecl::visible_extensions_iterator 1838 Ext = I->visible_extensions_begin(), 1839 ExtEnd = I->visible_extensions_end(); 1840 Ext != ExtEnd; ++Ext) { 1841 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1842 IMPDecl, *Ext, IncompleteImpl, false, 1843 WarnCategoryMethodImpl); 1844 } 1845 } 1846 1847 // Check for any implementation of a methods declared in protocol. 1848 for (ObjCInterfaceDecl::all_protocol_iterator 1849 PI = I->all_referenced_protocol_begin(), 1850 E = I->all_referenced_protocol_end(); PI != E; ++PI) 1851 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1852 IMPDecl, 1853 (*PI), IncompleteImpl, false, 1854 WarnCategoryMethodImpl); 1855 1856 // FIXME. For now, we are not checking for extact match of methods 1857 // in category implementation and its primary class's super class. 1858 if (!WarnCategoryMethodImpl && I->getSuperClass()) 1859 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1860 IMPDecl, 1861 I->getSuperClass(), IncompleteImpl, false); 1862 } 1863 } 1864 1865 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 1866 /// category matches with those implemented in its primary class and 1867 /// warns each time an exact match is found. 1868 void Sema::CheckCategoryVsClassMethodMatches( 1869 ObjCCategoryImplDecl *CatIMPDecl) { 1870 // Get category's primary class. 1871 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl(); 1872 if (!CatDecl) 1873 return; 1874 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface(); 1875 if (!IDecl) 1876 return; 1877 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass(); 1878 SelectorSet InsMap, ClsMap; 1879 1880 for (ObjCImplementationDecl::instmeth_iterator 1881 I = CatIMPDecl->instmeth_begin(), 1882 E = CatIMPDecl->instmeth_end(); I!=E; ++I) { 1883 Selector Sel = (*I)->getSelector(); 1884 // When checking for methods implemented in the category, skip over 1885 // those declared in category class's super class. This is because 1886 // the super class must implement the method. 1887 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true)) 1888 continue; 1889 InsMap.insert(Sel); 1890 } 1891 1892 for (ObjCImplementationDecl::classmeth_iterator 1893 I = CatIMPDecl->classmeth_begin(), 1894 E = CatIMPDecl->classmeth_end(); I != E; ++I) { 1895 Selector Sel = (*I)->getSelector(); 1896 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false)) 1897 continue; 1898 ClsMap.insert(Sel); 1899 } 1900 if (InsMap.empty() && ClsMap.empty()) 1901 return; 1902 1903 SelectorSet InsMapSeen, ClsMapSeen; 1904 bool IncompleteImpl = false; 1905 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1906 CatIMPDecl, IDecl, 1907 IncompleteImpl, false, 1908 true /*WarnCategoryMethodImpl*/); 1909 } 1910 1911 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 1912 ObjCContainerDecl* CDecl, 1913 bool IncompleteImpl) { 1914 SelectorSet InsMap; 1915 // Check and see if instance methods in class interface have been 1916 // implemented in the implementation class. 1917 for (ObjCImplementationDecl::instmeth_iterator 1918 I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I) 1919 InsMap.insert((*I)->getSelector()); 1920 1921 // Check and see if properties declared in the interface have either 1) 1922 // an implementation or 2) there is a @synthesize/@dynamic implementation 1923 // of the property in the @implementation. 1924 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) 1925 if (!(LangOpts.ObjCDefaultSynthProperties && 1926 LangOpts.ObjCRuntime.isNonFragile()) || 1927 IDecl->isObjCRequiresPropertyDefs()) 1928 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl); 1929 1930 SelectorSet ClsMap; 1931 for (ObjCImplementationDecl::classmeth_iterator 1932 I = IMPDecl->classmeth_begin(), 1933 E = IMPDecl->classmeth_end(); I != E; ++I) 1934 ClsMap.insert((*I)->getSelector()); 1935 1936 // Check for type conflict of methods declared in a class/protocol and 1937 // its implementation; if any. 1938 SelectorSet InsMapSeen, ClsMapSeen; 1939 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1940 IMPDecl, CDecl, 1941 IncompleteImpl, true); 1942 1943 // check all methods implemented in category against those declared 1944 // in its primary class. 1945 if (ObjCCategoryImplDecl *CatDecl = 1946 dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) 1947 CheckCategoryVsClassMethodMatches(CatDecl); 1948 1949 // Check the protocol list for unimplemented methods in the @implementation 1950 // class. 1951 // Check and see if class methods in class interface have been 1952 // implemented in the implementation class. 1953 1954 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 1955 for (ObjCInterfaceDecl::all_protocol_iterator 1956 PI = I->all_referenced_protocol_begin(), 1957 E = I->all_referenced_protocol_end(); PI != E; ++PI) 1958 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl, 1959 InsMap, ClsMap, I); 1960 // Check class extensions (unnamed categories) 1961 for (ObjCInterfaceDecl::visible_extensions_iterator 1962 Ext = I->visible_extensions_begin(), 1963 ExtEnd = I->visible_extensions_end(); 1964 Ext != ExtEnd; ++Ext) { 1965 ImplMethodsVsClassMethods(S, IMPDecl, *Ext, IncompleteImpl); 1966 } 1967 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1968 // For extended class, unimplemented methods in its protocols will 1969 // be reported in the primary class. 1970 if (!C->IsClassExtension()) { 1971 for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(), 1972 E = C->protocol_end(); PI != E; ++PI) 1973 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl, 1974 InsMap, ClsMap, CDecl); 1975 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl); 1976 } 1977 } else 1978 llvm_unreachable("invalid ObjCContainerDecl type."); 1979 } 1980 1981 /// ActOnForwardClassDeclaration - 1982 Sema::DeclGroupPtrTy 1983 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, 1984 IdentifierInfo **IdentList, 1985 SourceLocation *IdentLocs, 1986 unsigned NumElts) { 1987 SmallVector<Decl *, 8> DeclsInGroup; 1988 for (unsigned i = 0; i != NumElts; ++i) { 1989 // Check for another declaration kind with the same name. 1990 NamedDecl *PrevDecl 1991 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 1992 LookupOrdinaryName, ForRedeclaration); 1993 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1994 // GCC apparently allows the following idiom: 1995 // 1996 // typedef NSObject < XCElementTogglerP > XCElementToggler; 1997 // @class XCElementToggler; 1998 // 1999 // Here we have chosen to ignore the forward class declaration 2000 // with a warning. Since this is the implied behavior. 2001 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl); 2002 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) { 2003 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; 2004 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2005 } else { 2006 // a forward class declaration matching a typedef name of a class refers 2007 // to the underlying class. Just ignore the forward class with a warning 2008 // as this will force the intended behavior which is to lookup the typedef 2009 // name. 2010 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) { 2011 Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i]; 2012 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2013 continue; 2014 } 2015 } 2016 } 2017 2018 // Create a declaration to describe this forward declaration. 2019 ObjCInterfaceDecl *PrevIDecl 2020 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 2021 2022 IdentifierInfo *ClassName = IdentList[i]; 2023 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 2024 // A previous decl with a different name is because of 2025 // @compatibility_alias, for example: 2026 // \code 2027 // @class NewImage; 2028 // @compatibility_alias OldImage NewImage; 2029 // \endcode 2030 // A lookup for 'OldImage' will return the 'NewImage' decl. 2031 // 2032 // In such a case use the real declaration name, instead of the alias one, 2033 // otherwise we will break IdentifierResolver and redecls-chain invariants. 2034 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 2035 // has been aliased. 2036 ClassName = PrevIDecl->getIdentifier(); 2037 } 2038 2039 ObjCInterfaceDecl *IDecl 2040 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, 2041 ClassName, PrevIDecl, IdentLocs[i]); 2042 IDecl->setAtEndRange(IdentLocs[i]); 2043 2044 PushOnScopeChains(IDecl, TUScope); 2045 CheckObjCDeclScope(IDecl); 2046 DeclsInGroup.push_back(IDecl); 2047 } 2048 2049 return BuildDeclaratorGroup(DeclsInGroup, false); 2050 } 2051 2052 static bool tryMatchRecordTypes(ASTContext &Context, 2053 Sema::MethodMatchStrategy strategy, 2054 const Type *left, const Type *right); 2055 2056 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, 2057 QualType leftQT, QualType rightQT) { 2058 const Type *left = 2059 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr(); 2060 const Type *right = 2061 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr(); 2062 2063 if (left == right) return true; 2064 2065 // If we're doing a strict match, the types have to match exactly. 2066 if (strategy == Sema::MMS_strict) return false; 2067 2068 if (left->isIncompleteType() || right->isIncompleteType()) return false; 2069 2070 // Otherwise, use this absurdly complicated algorithm to try to 2071 // validate the basic, low-level compatibility of the two types. 2072 2073 // As a minimum, require the sizes and alignments to match. 2074 if (Context.getTypeInfo(left) != Context.getTypeInfo(right)) 2075 return false; 2076 2077 // Consider all the kinds of non-dependent canonical types: 2078 // - functions and arrays aren't possible as return and parameter types 2079 2080 // - vector types of equal size can be arbitrarily mixed 2081 if (isa<VectorType>(left)) return isa<VectorType>(right); 2082 if (isa<VectorType>(right)) return false; 2083 2084 // - references should only match references of identical type 2085 // - structs, unions, and Objective-C objects must match more-or-less 2086 // exactly 2087 // - everything else should be a scalar 2088 if (!left->isScalarType() || !right->isScalarType()) 2089 return tryMatchRecordTypes(Context, strategy, left, right); 2090 2091 // Make scalars agree in kind, except count bools as chars, and group 2092 // all non-member pointers together. 2093 Type::ScalarTypeKind leftSK = left->getScalarTypeKind(); 2094 Type::ScalarTypeKind rightSK = right->getScalarTypeKind(); 2095 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral; 2096 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral; 2097 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer) 2098 leftSK = Type::STK_ObjCObjectPointer; 2099 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer) 2100 rightSK = Type::STK_ObjCObjectPointer; 2101 2102 // Note that data member pointers and function member pointers don't 2103 // intermix because of the size differences. 2104 2105 return (leftSK == rightSK); 2106 } 2107 2108 static bool tryMatchRecordTypes(ASTContext &Context, 2109 Sema::MethodMatchStrategy strategy, 2110 const Type *lt, const Type *rt) { 2111 assert(lt && rt && lt != rt); 2112 2113 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false; 2114 RecordDecl *left = cast<RecordType>(lt)->getDecl(); 2115 RecordDecl *right = cast<RecordType>(rt)->getDecl(); 2116 2117 // Require union-hood to match. 2118 if (left->isUnion() != right->isUnion()) return false; 2119 2120 // Require an exact match if either is non-POD. 2121 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) || 2122 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD())) 2123 return false; 2124 2125 // Require size and alignment to match. 2126 if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false; 2127 2128 // Require fields to match. 2129 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end(); 2130 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end(); 2131 for (; li != le && ri != re; ++li, ++ri) { 2132 if (!matchTypes(Context, strategy, li->getType(), ri->getType())) 2133 return false; 2134 } 2135 return (li == le && ri == re); 2136 } 2137 2138 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and 2139 /// returns true, or false, accordingly. 2140 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons 2141 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left, 2142 const ObjCMethodDecl *right, 2143 MethodMatchStrategy strategy) { 2144 if (!matchTypes(Context, strategy, 2145 left->getResultType(), right->getResultType())) 2146 return false; 2147 2148 // If either is hidden, it is not considered to match. 2149 if (left->isHidden() || right->isHidden()) 2150 return false; 2151 2152 if (getLangOpts().ObjCAutoRefCount && 2153 (left->hasAttr<NSReturnsRetainedAttr>() 2154 != right->hasAttr<NSReturnsRetainedAttr>() || 2155 left->hasAttr<NSConsumesSelfAttr>() 2156 != right->hasAttr<NSConsumesSelfAttr>())) 2157 return false; 2158 2159 ObjCMethodDecl::param_const_iterator 2160 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(), 2161 re = right->param_end(); 2162 2163 for (; li != le && ri != re; ++li, ++ri) { 2164 assert(ri != right->param_end() && "Param mismatch"); 2165 const ParmVarDecl *lparm = *li, *rparm = *ri; 2166 2167 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType())) 2168 return false; 2169 2170 if (getLangOpts().ObjCAutoRefCount && 2171 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()) 2172 return false; 2173 } 2174 return true; 2175 } 2176 2177 void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) { 2178 // Record at the head of the list whether there were 0, 1, or >= 2 methods 2179 // inside categories. 2180 if (ObjCCategoryDecl * 2181 CD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) 2182 if (!CD->IsClassExtension() && List->getBits() < 2) 2183 List->setBits(List->getBits()+1); 2184 2185 // If the list is empty, make it a singleton list. 2186 if (List->Method == 0) { 2187 List->Method = Method; 2188 List->setNext(0); 2189 return; 2190 } 2191 2192 // We've seen a method with this name, see if we have already seen this type 2193 // signature. 2194 ObjCMethodList *Previous = List; 2195 for (; List; Previous = List, List = List->getNext()) { 2196 // If we are building a module, keep all of the methods. 2197 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) 2198 continue; 2199 2200 if (!MatchTwoMethodDeclarations(Method, List->Method)) 2201 continue; 2202 2203 ObjCMethodDecl *PrevObjCMethod = List->Method; 2204 2205 // Propagate the 'defined' bit. 2206 if (Method->isDefined()) 2207 PrevObjCMethod->setDefined(true); 2208 2209 // If a method is deprecated, push it in the global pool. 2210 // This is used for better diagnostics. 2211 if (Method->isDeprecated()) { 2212 if (!PrevObjCMethod->isDeprecated()) 2213 List->Method = Method; 2214 } 2215 // If new method is unavailable, push it into global pool 2216 // unless previous one is deprecated. 2217 if (Method->isUnavailable()) { 2218 if (PrevObjCMethod->getAvailability() < AR_Deprecated) 2219 List->Method = Method; 2220 } 2221 2222 return; 2223 } 2224 2225 // We have a new signature for an existing method - add it. 2226 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". 2227 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>(); 2228 Previous->setNext(new (Mem) ObjCMethodList(Method, 0)); 2229 } 2230 2231 /// \brief Read the contents of the method pool for a given selector from 2232 /// external storage. 2233 void Sema::ReadMethodPool(Selector Sel) { 2234 assert(ExternalSource && "We need an external AST source"); 2235 ExternalSource->ReadMethodPool(Sel); 2236 } 2237 2238 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, 2239 bool instance) { 2240 // Ignore methods of invalid containers. 2241 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl()) 2242 return; 2243 2244 if (ExternalSource) 2245 ReadMethodPool(Method->getSelector()); 2246 2247 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); 2248 if (Pos == MethodPool.end()) 2249 Pos = MethodPool.insert(std::make_pair(Method->getSelector(), 2250 GlobalMethods())).first; 2251 2252 Method->setDefined(impl); 2253 2254 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; 2255 addMethodToGlobalList(&Entry, Method); 2256 } 2257 2258 /// Determines if this is an "acceptable" loose mismatch in the global 2259 /// method pool. This exists mostly as a hack to get around certain 2260 /// global mismatches which we can't afford to make warnings / errors. 2261 /// Really, what we want is a way to take a method out of the global 2262 /// method pool. 2263 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen, 2264 ObjCMethodDecl *other) { 2265 if (!chosen->isInstanceMethod()) 2266 return false; 2267 2268 Selector sel = chosen->getSelector(); 2269 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length") 2270 return false; 2271 2272 // Don't complain about mismatches for -length if the method we 2273 // chose has an integral result type. 2274 return (chosen->getResultType()->isIntegerType()); 2275 } 2276 2277 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, 2278 bool receiverIdOrClass, 2279 bool warn, bool instance) { 2280 if (ExternalSource) 2281 ReadMethodPool(Sel); 2282 2283 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 2284 if (Pos == MethodPool.end()) 2285 return 0; 2286 2287 // Gather the non-hidden methods. 2288 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 2289 SmallVector<ObjCMethodDecl *, 4> Methods; 2290 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) { 2291 if (M->Method && !M->Method->isHidden()) { 2292 // If we're not supposed to warn about mismatches, we're done. 2293 if (!warn) 2294 return M->Method; 2295 2296 Methods.push_back(M->Method); 2297 } 2298 } 2299 2300 // If there aren't any visible methods, we're done. 2301 // FIXME: Recover if there are any known-but-hidden methods? 2302 if (Methods.empty()) 2303 return 0; 2304 2305 if (Methods.size() == 1) 2306 return Methods[0]; 2307 2308 // We found multiple methods, so we may have to complain. 2309 bool issueDiagnostic = false, issueError = false; 2310 2311 // We support a warning which complains about *any* difference in 2312 // method signature. 2313 bool strictSelectorMatch = 2314 (receiverIdOrClass && warn && 2315 (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl, 2316 R.getBegin()) 2317 != DiagnosticsEngine::Ignored)); 2318 if (strictSelectorMatch) { 2319 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2320 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) { 2321 issueDiagnostic = true; 2322 break; 2323 } 2324 } 2325 } 2326 2327 // If we didn't see any strict differences, we won't see any loose 2328 // differences. In ARC, however, we also need to check for loose 2329 // mismatches, because most of them are errors. 2330 if (!strictSelectorMatch || 2331 (issueDiagnostic && getLangOpts().ObjCAutoRefCount)) 2332 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2333 // This checks if the methods differ in type mismatch. 2334 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) && 2335 !isAcceptableMethodMismatch(Methods[0], Methods[I])) { 2336 issueDiagnostic = true; 2337 if (getLangOpts().ObjCAutoRefCount) 2338 issueError = true; 2339 break; 2340 } 2341 } 2342 2343 if (issueDiagnostic) { 2344 if (issueError) 2345 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; 2346 else if (strictSelectorMatch) 2347 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; 2348 else 2349 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; 2350 2351 Diag(Methods[0]->getLocStart(), 2352 issueError ? diag::note_possibility : diag::note_using) 2353 << Methods[0]->getSourceRange(); 2354 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2355 Diag(Methods[I]->getLocStart(), diag::note_also_found) 2356 << Methods[I]->getSourceRange(); 2357 } 2358 } 2359 return Methods[0]; 2360 } 2361 2362 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { 2363 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 2364 if (Pos == MethodPool.end()) 2365 return 0; 2366 2367 GlobalMethods &Methods = Pos->second; 2368 2369 if (Methods.first.Method && Methods.first.Method->isDefined()) 2370 return Methods.first.Method; 2371 if (Methods.second.Method && Methods.second.Method->isDefined()) 2372 return Methods.second.Method; 2373 return 0; 2374 } 2375 2376 static void 2377 HelperSelectorsForTypoCorrection( 2378 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod, 2379 StringRef Typo, const ObjCMethodDecl * Method) { 2380 const unsigned MaxEditDistance = 1; 2381 unsigned BestEditDistance = MaxEditDistance + 1; 2382 std::string MethodName = Method->getSelector().getAsString(); 2383 2384 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size()); 2385 if (MinPossibleEditDistance > 0 && 2386 Typo.size() / MinPossibleEditDistance < 1) 2387 return; 2388 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance); 2389 if (EditDistance > MaxEditDistance) 2390 return; 2391 if (EditDistance == BestEditDistance) 2392 BestMethod.push_back(Method); 2393 else if (EditDistance < BestEditDistance) { 2394 BestMethod.clear(); 2395 BestMethod.push_back(Method); 2396 } 2397 } 2398 2399 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel, 2400 QualType ObjectType) { 2401 if (ObjectType.isNull()) 2402 return true; 2403 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/)) 2404 return true; 2405 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) != 0; 2406 } 2407 2408 const ObjCMethodDecl * 2409 Sema::SelectorsForTypoCorrection(Selector Sel, 2410 QualType ObjectType) { 2411 unsigned NumArgs = Sel.getNumArgs(); 2412 SmallVector<const ObjCMethodDecl *, 8> Methods; 2413 bool ObjectIsId = true, ObjectIsClass = true; 2414 if (ObjectType.isNull()) 2415 ObjectIsId = ObjectIsClass = false; 2416 else if (!ObjectType->isObjCObjectPointerType()) 2417 return 0; 2418 else if (const ObjCObjectPointerType *ObjCPtr = 2419 ObjectType->getAsObjCInterfacePointerType()) { 2420 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0); 2421 ObjectIsId = ObjectIsClass = false; 2422 } 2423 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType()) 2424 ObjectIsClass = false; 2425 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType()) 2426 ObjectIsId = false; 2427 else 2428 return 0; 2429 2430 for (GlobalMethodPool::iterator b = MethodPool.begin(), 2431 e = MethodPool.end(); b != e; b++) { 2432 // instance methods 2433 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext()) 2434 if (M->Method && 2435 (M->Method->getSelector().getNumArgs() == NumArgs) && 2436 (M->Method->getSelector() != Sel)) { 2437 if (ObjectIsId) 2438 Methods.push_back(M->Method); 2439 else if (!ObjectIsClass && 2440 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType)) 2441 Methods.push_back(M->Method); 2442 } 2443 // class methods 2444 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext()) 2445 if (M->Method && 2446 (M->Method->getSelector().getNumArgs() == NumArgs) && 2447 (M->Method->getSelector() != Sel)) { 2448 if (ObjectIsClass) 2449 Methods.push_back(M->Method); 2450 else if (!ObjectIsId && 2451 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType)) 2452 Methods.push_back(M->Method); 2453 } 2454 } 2455 2456 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods; 2457 for (unsigned i = 0, e = Methods.size(); i < e; i++) { 2458 HelperSelectorsForTypoCorrection(SelectedMethods, 2459 Sel.getAsString(), Methods[i]); 2460 } 2461 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : NULL; 2462 } 2463 2464 static void 2465 HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S, 2466 ObjCMethodList &MethList) { 2467 ObjCMethodList *M = &MethList; 2468 ObjCMethodDecl *TargetMethod = M->Method; 2469 while (TargetMethod && 2470 isa<ObjCImplDecl>(TargetMethod->getDeclContext())) { 2471 M = M->getNext(); 2472 TargetMethod = M ? M->Method : 0; 2473 } 2474 if (!TargetMethod) 2475 return; 2476 bool FirstTime = true; 2477 for (M = M->getNext(); M; M=M->getNext()) { 2478 ObjCMethodDecl *MatchingMethodDecl = M->Method; 2479 if (isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext())) 2480 continue; 2481 if (!S.MatchTwoMethodDeclarations(TargetMethod, 2482 MatchingMethodDecl, Sema::MMS_loose)) { 2483 if (FirstTime) { 2484 FirstTime = false; 2485 S.Diag(TargetMethod->getLocation(), diag::warning_multiple_selectors) 2486 << TargetMethod->getSelector(); 2487 } 2488 S.Diag(MatchingMethodDecl->getLocation(), diag::note_also_found); 2489 } 2490 } 2491 } 2492 2493 void Sema::DiagnoseMismatchedMethodsInGlobalPool() { 2494 unsigned DIAG = diag::warning_multiple_selectors; 2495 if (Diags.getDiagnosticLevel(DIAG, SourceLocation()) 2496 == DiagnosticsEngine::Ignored) 2497 return; 2498 for (GlobalMethodPool::iterator b = MethodPool.begin(), 2499 e = MethodPool.end(); b != e; b++) { 2500 // first, instance methods 2501 ObjCMethodList &InstMethList = b->second.first; 2502 HelperToDiagnoseMismatchedMethodsInGlobalPool(*this, InstMethList); 2503 // second, class methods 2504 ObjCMethodList &ClsMethList = b->second.second; 2505 HelperToDiagnoseMismatchedMethodsInGlobalPool(*this, ClsMethList); 2506 } 2507 } 2508 2509 /// DiagnoseDuplicateIvars - 2510 /// Check for duplicate ivars in the entire class at the start of 2511 /// \@implementation. This becomes necesssary because class extension can 2512 /// add ivars to a class in random order which will not be known until 2513 /// class's \@implementation is seen. 2514 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 2515 ObjCInterfaceDecl *SID) { 2516 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(), 2517 IVE = ID->ivar_end(); IVI != IVE; ++IVI) { 2518 ObjCIvarDecl* Ivar = *IVI; 2519 if (Ivar->isInvalidDecl()) 2520 continue; 2521 if (IdentifierInfo *II = Ivar->getIdentifier()) { 2522 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II); 2523 if (prevIvar) { 2524 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 2525 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 2526 Ivar->setInvalidDecl(); 2527 } 2528 } 2529 } 2530 } 2531 2532 Sema::ObjCContainerKind Sema::getObjCContainerKind() const { 2533 switch (CurContext->getDeclKind()) { 2534 case Decl::ObjCInterface: 2535 return Sema::OCK_Interface; 2536 case Decl::ObjCProtocol: 2537 return Sema::OCK_Protocol; 2538 case Decl::ObjCCategory: 2539 if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension()) 2540 return Sema::OCK_ClassExtension; 2541 else 2542 return Sema::OCK_Category; 2543 case Decl::ObjCImplementation: 2544 return Sema::OCK_Implementation; 2545 case Decl::ObjCCategoryImpl: 2546 return Sema::OCK_CategoryImplementation; 2547 2548 default: 2549 return Sema::OCK_None; 2550 } 2551 } 2552 2553 // Note: For class/category implementations, allMethods is always null. 2554 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods, 2555 ArrayRef<DeclGroupPtrTy> allTUVars) { 2556 if (getObjCContainerKind() == Sema::OCK_None) 2557 return 0; 2558 2559 assert(AtEnd.isValid() && "Invalid location for '@end'"); 2560 2561 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 2562 Decl *ClassDecl = cast<Decl>(OCD); 2563 2564 bool isInterfaceDeclKind = 2565 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) 2566 || isa<ObjCProtocolDecl>(ClassDecl); 2567 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); 2568 2569 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. 2570 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; 2571 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; 2572 2573 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) { 2574 ObjCMethodDecl *Method = 2575 cast_or_null<ObjCMethodDecl>(allMethods[i]); 2576 2577 if (!Method) continue; // Already issued a diagnostic. 2578 if (Method->isInstanceMethod()) { 2579 /// Check for instance method of the same name with incompatible types 2580 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; 2581 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 2582 : false; 2583 if ((isInterfaceDeclKind && PrevMethod && !match) 2584 || (checkIdenticalMethods && match)) { 2585 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 2586 << Method->getDeclName(); 2587 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2588 Method->setInvalidDecl(); 2589 } else { 2590 if (PrevMethod) { 2591 Method->setAsRedeclaration(PrevMethod); 2592 if (!Context.getSourceManager().isInSystemHeader( 2593 Method->getLocation())) 2594 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 2595 << Method->getDeclName(); 2596 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2597 } 2598 InsMap[Method->getSelector()] = Method; 2599 /// The following allows us to typecheck messages to "id". 2600 AddInstanceMethodToGlobalPool(Method); 2601 } 2602 } else { 2603 /// Check for class method of the same name with incompatible types 2604 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; 2605 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 2606 : false; 2607 if ((isInterfaceDeclKind && PrevMethod && !match) 2608 || (checkIdenticalMethods && match)) { 2609 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 2610 << Method->getDeclName(); 2611 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2612 Method->setInvalidDecl(); 2613 } else { 2614 if (PrevMethod) { 2615 Method->setAsRedeclaration(PrevMethod); 2616 if (!Context.getSourceManager().isInSystemHeader( 2617 Method->getLocation())) 2618 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 2619 << Method->getDeclName(); 2620 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2621 } 2622 ClsMap[Method->getSelector()] = Method; 2623 AddFactoryMethodToGlobalPool(Method); 2624 } 2625 } 2626 } 2627 if (isa<ObjCInterfaceDecl>(ClassDecl)) { 2628 // Nothing to do here. 2629 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 2630 // Categories are used to extend the class by declaring new methods. 2631 // By the same token, they are also used to add new properties. No 2632 // need to compare the added property to those in the class. 2633 2634 if (C->IsClassExtension()) { 2635 ObjCInterfaceDecl *CCPrimary = C->getClassInterface(); 2636 DiagnoseClassExtensionDupMethods(C, CCPrimary); 2637 } 2638 } 2639 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { 2640 if (CDecl->getIdentifier()) 2641 // ProcessPropertyDecl is responsible for diagnosing conflicts with any 2642 // user-defined setter/getter. It also synthesizes setter/getter methods 2643 // and adds them to the DeclContext and global method pools. 2644 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(), 2645 E = CDecl->prop_end(); 2646 I != E; ++I) 2647 ProcessPropertyDecl(*I, CDecl); 2648 CDecl->setAtEndRange(AtEnd); 2649 } 2650 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { 2651 IC->setAtEndRange(AtEnd); 2652 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) { 2653 // Any property declared in a class extension might have user 2654 // declared setter or getter in current class extension or one 2655 // of the other class extensions. Mark them as synthesized as 2656 // property will be synthesized when property with same name is 2657 // seen in the @implementation. 2658 for (ObjCInterfaceDecl::visible_extensions_iterator 2659 Ext = IDecl->visible_extensions_begin(), 2660 ExtEnd = IDecl->visible_extensions_end(); 2661 Ext != ExtEnd; ++Ext) { 2662 for (ObjCContainerDecl::prop_iterator I = Ext->prop_begin(), 2663 E = Ext->prop_end(); I != E; ++I) { 2664 ObjCPropertyDecl *Property = *I; 2665 // Skip over properties declared @dynamic 2666 if (const ObjCPropertyImplDecl *PIDecl 2667 = IC->FindPropertyImplDecl(Property->getIdentifier())) 2668 if (PIDecl->getPropertyImplementation() 2669 == ObjCPropertyImplDecl::Dynamic) 2670 continue; 2671 2672 for (ObjCInterfaceDecl::visible_extensions_iterator 2673 Ext = IDecl->visible_extensions_begin(), 2674 ExtEnd = IDecl->visible_extensions_end(); 2675 Ext != ExtEnd; ++Ext) { 2676 if (ObjCMethodDecl *GetterMethod 2677 = Ext->getInstanceMethod(Property->getGetterName())) 2678 GetterMethod->setPropertyAccessor(true); 2679 if (!Property->isReadOnly()) 2680 if (ObjCMethodDecl *SetterMethod 2681 = Ext->getInstanceMethod(Property->getSetterName())) 2682 SetterMethod->setPropertyAccessor(true); 2683 } 2684 } 2685 } 2686 ImplMethodsVsClassMethods(S, IC, IDecl); 2687 AtomicPropertySetterGetterRules(IC, IDecl); 2688 DiagnoseOwningPropertyGetterSynthesis(IC); 2689 if (IDecl->hasDesignatedInitializers()) 2690 DiagnoseMissingDesignatedInitOverrides(IC, IDecl); 2691 2692 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>(); 2693 if (IDecl->getSuperClass() == NULL) { 2694 // This class has no superclass, so check that it has been marked with 2695 // __attribute((objc_root_class)). 2696 if (!HasRootClassAttr) { 2697 SourceLocation DeclLoc(IDecl->getLocation()); 2698 SourceLocation SuperClassLoc(PP.getLocForEndOfToken(DeclLoc)); 2699 Diag(DeclLoc, diag::warn_objc_root_class_missing) 2700 << IDecl->getIdentifier(); 2701 // See if NSObject is in the current scope, and if it is, suggest 2702 // adding " : NSObject " to the class declaration. 2703 NamedDecl *IF = LookupSingleName(TUScope, 2704 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject), 2705 DeclLoc, LookupOrdinaryName); 2706 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 2707 if (NSObjectDecl && NSObjectDecl->getDefinition()) { 2708 Diag(SuperClassLoc, diag::note_objc_needs_superclass) 2709 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject "); 2710 } else { 2711 Diag(SuperClassLoc, diag::note_objc_needs_superclass); 2712 } 2713 } 2714 } else if (HasRootClassAttr) { 2715 // Complain that only root classes may have this attribute. 2716 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass); 2717 } 2718 2719 if (LangOpts.ObjCRuntime.isNonFragile()) { 2720 while (IDecl->getSuperClass()) { 2721 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass()); 2722 IDecl = IDecl->getSuperClass(); 2723 } 2724 } 2725 } 2726 SetIvarInitializers(IC); 2727 } else if (ObjCCategoryImplDecl* CatImplClass = 2728 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { 2729 CatImplClass->setAtEndRange(AtEnd); 2730 2731 // Find category interface decl and then check that all methods declared 2732 // in this interface are implemented in the category @implementation. 2733 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { 2734 if (ObjCCategoryDecl *Cat 2735 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) { 2736 ImplMethodsVsClassMethods(S, CatImplClass, Cat); 2737 } 2738 } 2739 } 2740 if (isInterfaceDeclKind) { 2741 // Reject invalid vardecls. 2742 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 2743 DeclGroupRef DG = allTUVars[i].get(); 2744 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 2745 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { 2746 if (!VDecl->hasExternalStorage()) 2747 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); 2748 } 2749 } 2750 } 2751 ActOnObjCContainerFinishDefinition(); 2752 2753 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 2754 DeclGroupRef DG = allTUVars[i].get(); 2755 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 2756 (*I)->setTopLevelDeclInObjCContainer(); 2757 Consumer.HandleTopLevelDeclInObjCContainer(DG); 2758 } 2759 2760 ActOnDocumentableDecl(ClassDecl); 2761 return ClassDecl; 2762 } 2763 2764 2765 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for 2766 /// objective-c's type qualifier from the parser version of the same info. 2767 static Decl::ObjCDeclQualifier 2768 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { 2769 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal; 2770 } 2771 2772 /// \brief Check whether the declared result type of the given Objective-C 2773 /// method declaration is compatible with the method's class. 2774 /// 2775 static Sema::ResultTypeCompatibilityKind 2776 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, 2777 ObjCInterfaceDecl *CurrentClass) { 2778 QualType ResultType = Method->getResultType(); 2779 2780 // If an Objective-C method inherits its related result type, then its 2781 // declared result type must be compatible with its own class type. The 2782 // declared result type is compatible if: 2783 if (const ObjCObjectPointerType *ResultObjectType 2784 = ResultType->getAs<ObjCObjectPointerType>()) { 2785 // - it is id or qualified id, or 2786 if (ResultObjectType->isObjCIdType() || 2787 ResultObjectType->isObjCQualifiedIdType()) 2788 return Sema::RTC_Compatible; 2789 2790 if (CurrentClass) { 2791 if (ObjCInterfaceDecl *ResultClass 2792 = ResultObjectType->getInterfaceDecl()) { 2793 // - it is the same as the method's class type, or 2794 if (declaresSameEntity(CurrentClass, ResultClass)) 2795 return Sema::RTC_Compatible; 2796 2797 // - it is a superclass of the method's class type 2798 if (ResultClass->isSuperClassOf(CurrentClass)) 2799 return Sema::RTC_Compatible; 2800 } 2801 } else { 2802 // Any Objective-C pointer type might be acceptable for a protocol 2803 // method; we just don't know. 2804 return Sema::RTC_Unknown; 2805 } 2806 } 2807 2808 return Sema::RTC_Incompatible; 2809 } 2810 2811 namespace { 2812 /// A helper class for searching for methods which a particular method 2813 /// overrides. 2814 class OverrideSearch { 2815 public: 2816 Sema &S; 2817 ObjCMethodDecl *Method; 2818 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden; 2819 bool Recursive; 2820 2821 public: 2822 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) { 2823 Selector selector = method->getSelector(); 2824 2825 // Bypass this search if we've never seen an instance/class method 2826 // with this selector before. 2827 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector); 2828 if (it == S.MethodPool.end()) { 2829 if (!S.getExternalSource()) return; 2830 S.ReadMethodPool(selector); 2831 2832 it = S.MethodPool.find(selector); 2833 if (it == S.MethodPool.end()) 2834 return; 2835 } 2836 ObjCMethodList &list = 2837 method->isInstanceMethod() ? it->second.first : it->second.second; 2838 if (!list.Method) return; 2839 2840 ObjCContainerDecl *container 2841 = cast<ObjCContainerDecl>(method->getDeclContext()); 2842 2843 // Prevent the search from reaching this container again. This is 2844 // important with categories, which override methods from the 2845 // interface and each other. 2846 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) { 2847 searchFromContainer(container); 2848 if (ObjCInterfaceDecl *Interface = Category->getClassInterface()) 2849 searchFromContainer(Interface); 2850 } else { 2851 searchFromContainer(container); 2852 } 2853 } 2854 2855 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator; 2856 iterator begin() const { return Overridden.begin(); } 2857 iterator end() const { return Overridden.end(); } 2858 2859 private: 2860 void searchFromContainer(ObjCContainerDecl *container) { 2861 if (container->isInvalidDecl()) return; 2862 2863 switch (container->getDeclKind()) { 2864 #define OBJCCONTAINER(type, base) \ 2865 case Decl::type: \ 2866 searchFrom(cast<type##Decl>(container)); \ 2867 break; 2868 #define ABSTRACT_DECL(expansion) 2869 #define DECL(type, base) \ 2870 case Decl::type: 2871 #include "clang/AST/DeclNodes.inc" 2872 llvm_unreachable("not an ObjC container!"); 2873 } 2874 } 2875 2876 void searchFrom(ObjCProtocolDecl *protocol) { 2877 if (!protocol->hasDefinition()) 2878 return; 2879 2880 // A method in a protocol declaration overrides declarations from 2881 // referenced ("parent") protocols. 2882 search(protocol->getReferencedProtocols()); 2883 } 2884 2885 void searchFrom(ObjCCategoryDecl *category) { 2886 // A method in a category declaration overrides declarations from 2887 // the main class and from protocols the category references. 2888 // The main class is handled in the constructor. 2889 search(category->getReferencedProtocols()); 2890 } 2891 2892 void searchFrom(ObjCCategoryImplDecl *impl) { 2893 // A method in a category definition that has a category 2894 // declaration overrides declarations from the category 2895 // declaration. 2896 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) { 2897 search(category); 2898 if (ObjCInterfaceDecl *Interface = category->getClassInterface()) 2899 search(Interface); 2900 2901 // Otherwise it overrides declarations from the class. 2902 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) { 2903 search(Interface); 2904 } 2905 } 2906 2907 void searchFrom(ObjCInterfaceDecl *iface) { 2908 // A method in a class declaration overrides declarations from 2909 if (!iface->hasDefinition()) 2910 return; 2911 2912 // - categories, 2913 for (ObjCInterfaceDecl::known_categories_iterator 2914 cat = iface->known_categories_begin(), 2915 catEnd = iface->known_categories_end(); 2916 cat != catEnd; ++cat) { 2917 search(*cat); 2918 } 2919 2920 // - the super class, and 2921 if (ObjCInterfaceDecl *super = iface->getSuperClass()) 2922 search(super); 2923 2924 // - any referenced protocols. 2925 search(iface->getReferencedProtocols()); 2926 } 2927 2928 void searchFrom(ObjCImplementationDecl *impl) { 2929 // A method in a class implementation overrides declarations from 2930 // the class interface. 2931 if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) 2932 search(Interface); 2933 } 2934 2935 2936 void search(const ObjCProtocolList &protocols) { 2937 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end(); 2938 i != e; ++i) 2939 search(*i); 2940 } 2941 2942 void search(ObjCContainerDecl *container) { 2943 // Check for a method in this container which matches this selector. 2944 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(), 2945 Method->isInstanceMethod(), 2946 /*AllowHidden=*/true); 2947 2948 // If we find one, record it and bail out. 2949 if (meth) { 2950 Overridden.insert(meth); 2951 return; 2952 } 2953 2954 // Otherwise, search for methods that a hypothetical method here 2955 // would have overridden. 2956 2957 // Note that we're now in a recursive case. 2958 Recursive = true; 2959 2960 searchFromContainer(container); 2961 } 2962 }; 2963 } 2964 2965 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 2966 ObjCInterfaceDecl *CurrentClass, 2967 ResultTypeCompatibilityKind RTC) { 2968 // Search for overridden methods and merge information down from them. 2969 OverrideSearch overrides(*this, ObjCMethod); 2970 // Keep track if the method overrides any method in the class's base classes, 2971 // its protocols, or its categories' protocols; we will keep that info 2972 // in the ObjCMethodDecl. 2973 // For this info, a method in an implementation is not considered as 2974 // overriding the same method in the interface or its categories. 2975 bool hasOverriddenMethodsInBaseOrProtocol = false; 2976 for (OverrideSearch::iterator 2977 i = overrides.begin(), e = overrides.end(); i != e; ++i) { 2978 ObjCMethodDecl *overridden = *i; 2979 2980 if (!hasOverriddenMethodsInBaseOrProtocol) { 2981 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) || 2982 CurrentClass != overridden->getClassInterface() || 2983 overridden->isOverriding()) { 2984 hasOverriddenMethodsInBaseOrProtocol = true; 2985 2986 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) { 2987 // OverrideSearch will return as "overridden" the same method in the 2988 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to 2989 // check whether a category of a base class introduced a method with the 2990 // same selector, after the interface method declaration. 2991 // To avoid unnecessary lookups in the majority of cases, we use the 2992 // extra info bits in GlobalMethodPool to check whether there were any 2993 // category methods with this selector. 2994 GlobalMethodPool::iterator It = 2995 MethodPool.find(ObjCMethod->getSelector()); 2996 if (It != MethodPool.end()) { 2997 ObjCMethodList &List = 2998 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second; 2999 unsigned CategCount = List.getBits(); 3000 if (CategCount > 0) { 3001 // If the method is in a category we'll do lookup if there were at 3002 // least 2 category methods recorded, otherwise only one will do. 3003 if (CategCount > 1 || 3004 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) { 3005 OverrideSearch overrides(*this, overridden); 3006 for (OverrideSearch::iterator 3007 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) { 3008 ObjCMethodDecl *SuperOverridden = *OI; 3009 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) || 3010 CurrentClass != SuperOverridden->getClassInterface()) { 3011 hasOverriddenMethodsInBaseOrProtocol = true; 3012 overridden->setOverriding(true); 3013 break; 3014 } 3015 } 3016 } 3017 } 3018 } 3019 } 3020 } 3021 3022 // Propagate down the 'related result type' bit from overridden methods. 3023 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType()) 3024 ObjCMethod->SetRelatedResultType(); 3025 3026 // Then merge the declarations. 3027 mergeObjCMethodDecls(ObjCMethod, overridden); 3028 3029 if (ObjCMethod->isImplicit() && overridden->isImplicit()) 3030 continue; // Conflicting properties are detected elsewhere. 3031 3032 // Check for overriding methods 3033 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 3034 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) 3035 CheckConflictingOverridingMethod(ObjCMethod, overridden, 3036 isa<ObjCProtocolDecl>(overridden->getDeclContext())); 3037 3038 if (CurrentClass && overridden->getDeclContext() != CurrentClass && 3039 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && 3040 !overridden->isImplicit() /* not meant for properties */) { 3041 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(), 3042 E = ObjCMethod->param_end(); 3043 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(), 3044 PrevE = overridden->param_end(); 3045 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) { 3046 assert(PrevI != overridden->param_end() && "Param mismatch"); 3047 QualType T1 = Context.getCanonicalType((*ParamI)->getType()); 3048 QualType T2 = Context.getCanonicalType((*PrevI)->getType()); 3049 // If type of argument of method in this class does not match its 3050 // respective argument type in the super class method, issue warning; 3051 if (!Context.typesAreCompatible(T1, T2)) { 3052 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super) 3053 << T1 << T2; 3054 Diag(overridden->getLocation(), diag::note_previous_declaration); 3055 break; 3056 } 3057 } 3058 } 3059 } 3060 3061 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol); 3062 } 3063 3064 Decl *Sema::ActOnMethodDeclaration( 3065 Scope *S, 3066 SourceLocation MethodLoc, SourceLocation EndLoc, 3067 tok::TokenKind MethodType, 3068 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 3069 ArrayRef<SourceLocation> SelectorLocs, 3070 Selector Sel, 3071 // optional arguments. The number of types/arguments is obtained 3072 // from the Sel.getNumArgs(). 3073 ObjCArgInfo *ArgInfo, 3074 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 3075 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind, 3076 bool isVariadic, bool MethodDefinition) { 3077 // Make sure we can establish a context for the method. 3078 if (!CurContext->isObjCContainer()) { 3079 Diag(MethodLoc, diag::error_missing_method_context); 3080 return 0; 3081 } 3082 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 3083 Decl *ClassDecl = cast<Decl>(OCD); 3084 QualType resultDeclType; 3085 3086 bool HasRelatedResultType = false; 3087 TypeSourceInfo *ResultTInfo = 0; 3088 if (ReturnType) { 3089 resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo); 3090 3091 if (CheckFunctionReturnType(resultDeclType, MethodLoc)) 3092 return 0; 3093 3094 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType()); 3095 } else { // get the type for "id". 3096 resultDeclType = Context.getObjCIdType(); 3097 Diag(MethodLoc, diag::warn_missing_method_return_type) 3098 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)"); 3099 } 3100 3101 ObjCMethodDecl* ObjCMethod = 3102 ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, 3103 resultDeclType, 3104 ResultTInfo, 3105 CurContext, 3106 MethodType == tok::minus, isVariadic, 3107 /*isPropertyAccessor=*/false, 3108 /*isImplicitlyDeclared=*/false, /*isDefined=*/false, 3109 MethodDeclKind == tok::objc_optional 3110 ? ObjCMethodDecl::Optional 3111 : ObjCMethodDecl::Required, 3112 HasRelatedResultType); 3113 3114 SmallVector<ParmVarDecl*, 16> Params; 3115 3116 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { 3117 QualType ArgType; 3118 TypeSourceInfo *DI; 3119 3120 if (!ArgInfo[i].Type) { 3121 ArgType = Context.getObjCIdType(); 3122 DI = 0; 3123 } else { 3124 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); 3125 } 3126 3127 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 3128 LookupOrdinaryName, ForRedeclaration); 3129 LookupName(R, S); 3130 if (R.isSingleResult()) { 3131 NamedDecl *PrevDecl = R.getFoundDecl(); 3132 if (S->isDeclScope(PrevDecl)) { 3133 Diag(ArgInfo[i].NameLoc, 3134 (MethodDefinition ? diag::warn_method_param_redefinition 3135 : diag::warn_method_param_declaration)) 3136 << ArgInfo[i].Name; 3137 Diag(PrevDecl->getLocation(), 3138 diag::note_previous_declaration); 3139 } 3140 } 3141 3142 SourceLocation StartLoc = DI 3143 ? DI->getTypeLoc().getBeginLoc() 3144 : ArgInfo[i].NameLoc; 3145 3146 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc, 3147 ArgInfo[i].NameLoc, ArgInfo[i].Name, 3148 ArgType, DI, SC_None); 3149 3150 Param->setObjCMethodScopeInfo(i); 3151 3152 Param->setObjCDeclQualifier( 3153 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); 3154 3155 // Apply the attributes to the parameter. 3156 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs); 3157 3158 if (Param->hasAttr<BlocksAttr>()) { 3159 Diag(Param->getLocation(), diag::err_block_on_nonlocal); 3160 Param->setInvalidDecl(); 3161 } 3162 S->AddDecl(Param); 3163 IdResolver.AddDecl(Param); 3164 3165 Params.push_back(Param); 3166 } 3167 3168 for (unsigned i = 0, e = CNumArgs; i != e; ++i) { 3169 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); 3170 QualType ArgType = Param->getType(); 3171 if (ArgType.isNull()) 3172 ArgType = Context.getObjCIdType(); 3173 else 3174 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 3175 ArgType = Context.getAdjustedParameterType(ArgType); 3176 3177 Param->setDeclContext(ObjCMethod); 3178 Params.push_back(Param); 3179 } 3180 3181 ObjCMethod->setMethodParams(Context, Params, SelectorLocs); 3182 ObjCMethod->setObjCDeclQualifier( 3183 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); 3184 3185 if (AttrList) 3186 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList); 3187 3188 // Add the method now. 3189 const ObjCMethodDecl *PrevMethod = 0; 3190 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) { 3191 if (MethodType == tok::minus) { 3192 PrevMethod = ImpDecl->getInstanceMethod(Sel); 3193 ImpDecl->addInstanceMethod(ObjCMethod); 3194 } else { 3195 PrevMethod = ImpDecl->getClassMethod(Sel); 3196 ImpDecl->addClassMethod(ObjCMethod); 3197 } 3198 3199 ObjCMethodDecl *IMD = 0; 3200 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) 3201 IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 3202 ObjCMethod->isInstanceMethod()); 3203 if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() && 3204 !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) { 3205 // merge the attribute into implementation. 3206 ObjCMethod->addAttr( 3207 new (Context) ObjCRequiresSuperAttr(ObjCMethod->getLocation(), Context)); 3208 } 3209 } else { 3210 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); 3211 } 3212 3213 if (PrevMethod) { 3214 // You can never have two method definitions with the same name. 3215 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) 3216 << ObjCMethod->getDeclName(); 3217 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3218 ObjCMethod->setInvalidDecl(); 3219 return ObjCMethod; 3220 } 3221 3222 // If this Objective-C method does not have a related result type, but we 3223 // are allowed to infer related result types, try to do so based on the 3224 // method family. 3225 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 3226 if (!CurrentClass) { 3227 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) 3228 CurrentClass = Cat->getClassInterface(); 3229 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl)) 3230 CurrentClass = Impl->getClassInterface(); 3231 else if (ObjCCategoryImplDecl *CatImpl 3232 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) 3233 CurrentClass = CatImpl->getClassInterface(); 3234 } 3235 3236 ResultTypeCompatibilityKind RTC 3237 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass); 3238 3239 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC); 3240 3241 bool ARCError = false; 3242 if (getLangOpts().ObjCAutoRefCount) 3243 ARCError = CheckARCMethodDecl(ObjCMethod); 3244 3245 // Infer the related result type when possible. 3246 if (!ARCError && RTC == Sema::RTC_Compatible && 3247 !ObjCMethod->hasRelatedResultType() && 3248 LangOpts.ObjCInferRelatedResultType) { 3249 bool InferRelatedResultType = false; 3250 switch (ObjCMethod->getMethodFamily()) { 3251 case OMF_None: 3252 case OMF_copy: 3253 case OMF_dealloc: 3254 case OMF_finalize: 3255 case OMF_mutableCopy: 3256 case OMF_release: 3257 case OMF_retainCount: 3258 case OMF_performSelector: 3259 break; 3260 3261 case OMF_alloc: 3262 case OMF_new: 3263 InferRelatedResultType = ObjCMethod->isClassMethod(); 3264 break; 3265 3266 case OMF_init: 3267 case OMF_autorelease: 3268 case OMF_retain: 3269 case OMF_self: 3270 InferRelatedResultType = ObjCMethod->isInstanceMethod(); 3271 break; 3272 } 3273 3274 if (InferRelatedResultType) 3275 ObjCMethod->SetRelatedResultType(); 3276 } 3277 3278 ActOnDocumentableDecl(ObjCMethod); 3279 3280 return ObjCMethod; 3281 } 3282 3283 bool Sema::CheckObjCDeclScope(Decl *D) { 3284 // Following is also an error. But it is caused by a missing @end 3285 // and diagnostic is issued elsewhere. 3286 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) 3287 return false; 3288 3289 // If we switched context to translation unit while we are still lexically in 3290 // an objc container, it means the parser missed emitting an error. 3291 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) 3292 return false; 3293 3294 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); 3295 D->setInvalidDecl(); 3296 3297 return true; 3298 } 3299 3300 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the 3301 /// instance variables of ClassName into Decls. 3302 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 3303 IdentifierInfo *ClassName, 3304 SmallVectorImpl<Decl*> &Decls) { 3305 // Check that ClassName is a valid class 3306 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart); 3307 if (!Class) { 3308 Diag(DeclStart, diag::err_undef_interface) << ClassName; 3309 return; 3310 } 3311 if (LangOpts.ObjCRuntime.isNonFragile()) { 3312 Diag(DeclStart, diag::err_atdef_nonfragile_interface); 3313 return; 3314 } 3315 3316 // Collect the instance variables 3317 SmallVector<const ObjCIvarDecl*, 32> Ivars; 3318 Context.DeepCollectObjCIvars(Class, true, Ivars); 3319 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 3320 for (unsigned i = 0; i < Ivars.size(); i++) { 3321 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]); 3322 RecordDecl *Record = dyn_cast<RecordDecl>(TagD); 3323 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, 3324 /*FIXME: StartL=*/ID->getLocation(), 3325 ID->getLocation(), 3326 ID->getIdentifier(), ID->getType(), 3327 ID->getBitWidth()); 3328 Decls.push_back(FD); 3329 } 3330 3331 // Introduce all of these fields into the appropriate scope. 3332 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin(); 3333 D != Decls.end(); ++D) { 3334 FieldDecl *FD = cast<FieldDecl>(*D); 3335 if (getLangOpts().CPlusPlus) 3336 PushOnScopeChains(cast<FieldDecl>(FD), S); 3337 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD)) 3338 Record->addDecl(FD); 3339 } 3340 } 3341 3342 /// \brief Build a type-check a new Objective-C exception variable declaration. 3343 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, 3344 SourceLocation StartLoc, 3345 SourceLocation IdLoc, 3346 IdentifierInfo *Id, 3347 bool Invalid) { 3348 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 3349 // duration shall not be qualified by an address-space qualifier." 3350 // Since all parameters have automatic store duration, they can not have 3351 // an address space. 3352 if (T.getAddressSpace() != 0) { 3353 Diag(IdLoc, diag::err_arg_with_address_space); 3354 Invalid = true; 3355 } 3356 3357 // An @catch parameter must be an unqualified object pointer type; 3358 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? 3359 if (Invalid) { 3360 // Don't do any further checking. 3361 } else if (T->isDependentType()) { 3362 // Okay: we don't know what this type will instantiate to. 3363 } else if (!T->isObjCObjectPointerType()) { 3364 Invalid = true; 3365 Diag(IdLoc ,diag::err_catch_param_not_objc_type); 3366 } else if (T->isObjCQualifiedIdType()) { 3367 Invalid = true; 3368 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm); 3369 } 3370 3371 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, 3372 T, TInfo, SC_None); 3373 New->setExceptionVariable(true); 3374 3375 // In ARC, infer 'retaining' for variables of retainable type. 3376 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) 3377 Invalid = true; 3378 3379 if (Invalid) 3380 New->setInvalidDecl(); 3381 return New; 3382 } 3383 3384 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { 3385 const DeclSpec &DS = D.getDeclSpec(); 3386 3387 // We allow the "register" storage class on exception variables because 3388 // GCC did, but we drop it completely. Any other storage class is an error. 3389 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 3390 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm) 3391 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc())); 3392 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3393 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm) 3394 << DeclSpec::getSpecifierName(SCS); 3395 } 3396 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 3397 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 3398 diag::err_invalid_thread) 3399 << DeclSpec::getSpecifierName(TSCS); 3400 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3401 3402 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 3403 3404 // Check that there are no default arguments inside the type of this 3405 // exception object (C++ only). 3406 if (getLangOpts().CPlusPlus) 3407 CheckExtraCXXDefaultArguments(D); 3408 3409 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3410 QualType ExceptionType = TInfo->getType(); 3411 3412 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, 3413 D.getSourceRange().getBegin(), 3414 D.getIdentifierLoc(), 3415 D.getIdentifier(), 3416 D.isInvalidType()); 3417 3418 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 3419 if (D.getCXXScopeSpec().isSet()) { 3420 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) 3421 << D.getCXXScopeSpec().getRange(); 3422 New->setInvalidDecl(); 3423 } 3424 3425 // Add the parameter declaration into this scope. 3426 S->AddDecl(New); 3427 if (D.getIdentifier()) 3428 IdResolver.AddDecl(New); 3429 3430 ProcessDeclAttributes(S, New, D); 3431 3432 if (New->hasAttr<BlocksAttr>()) 3433 Diag(New->getLocation(), diag::err_block_on_nonlocal); 3434 return New; 3435 } 3436 3437 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 3438 /// initialization. 3439 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 3440 SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 3441 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 3442 Iv= Iv->getNextIvar()) { 3443 QualType QT = Context.getBaseElementType(Iv->getType()); 3444 if (QT->isRecordType()) 3445 Ivars.push_back(Iv); 3446 } 3447 } 3448 3449 void Sema::DiagnoseUseOfUnimplementedSelectors() { 3450 // Load referenced selectors from the external source. 3451 if (ExternalSource) { 3452 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels; 3453 ExternalSource->ReadReferencedSelectors(Sels); 3454 for (unsigned I = 0, N = Sels.size(); I != N; ++I) 3455 ReferencedSelectors[Sels[I].first] = Sels[I].second; 3456 } 3457 3458 DiagnoseMismatchedMethodsInGlobalPool(); 3459 3460 // Warning will be issued only when selector table is 3461 // generated (which means there is at lease one implementation 3462 // in the TU). This is to match gcc's behavior. 3463 if (ReferencedSelectors.empty() || 3464 !Context.AnyObjCImplementation()) 3465 return; 3466 for (llvm::DenseMap<Selector, SourceLocation>::iterator S = 3467 ReferencedSelectors.begin(), 3468 E = ReferencedSelectors.end(); S != E; ++S) { 3469 Selector Sel = (*S).first; 3470 if (!LookupImplementedMethodInGlobalPool(Sel)) 3471 Diag((*S).second, diag::warn_unimplemented_selector) << Sel; 3472 } 3473 return; 3474 } 3475 3476 ObjCIvarDecl * 3477 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 3478 const ObjCPropertyDecl *&PDecl) const { 3479 3480 const ObjCInterfaceDecl *IDecl = Method->getClassInterface(); 3481 if (!IDecl) 3482 return 0; 3483 Method = IDecl->lookupMethod(Method->getSelector(), true); 3484 if (!Method || !Method->isPropertyAccessor()) 3485 return 0; 3486 if ((PDecl = Method->findPropertyDecl())) { 3487 if (!PDecl->getDeclContext()) 3488 return 0; 3489 // Make sure property belongs to accessor's class and not to 3490 // one of its super classes. 3491 if (const ObjCInterfaceDecl *CID = 3492 dyn_cast<ObjCInterfaceDecl>(PDecl->getDeclContext())) 3493 if (CID != IDecl) 3494 return 0; 3495 return PDecl->getPropertyIvarDecl(); 3496 } 3497 return 0; 3498 } 3499 3500 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S) { 3501 if (S->hasUnrecoverableErrorOccurred() || !S->isInObjcMethodScope()) 3502 return; 3503 3504 const ObjCMethodDecl *CurMethod = getCurMethodDecl(); 3505 if (!CurMethod) 3506 return; 3507 const ObjCPropertyDecl *PDecl; 3508 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl); 3509 if (IV && !IV->getBackingIvarReferencedInAccessor()) { 3510 Diag(getCurMethodDecl()->getLocation(), diag::warn_unused_property_backing_ivar) 3511 << IV->getDeclName(); 3512 Diag(PDecl->getLocation(), diag::note_property_declare); 3513 } 3514 } 3515