1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for Objective C declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/DataRecursiveASTVisitor.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprObjC.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "clang/Sema/DeclSpec.h" 25 #include "clang/Sema/ExternalSemaSource.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/Scope.h" 28 #include "clang/Sema/ScopeInfo.h" 29 #include "llvm/ADT/DenseSet.h" 30 31 using namespace clang; 32 33 /// Check whether the given method, which must be in the 'init' 34 /// family, is a valid member of that family. 35 /// 36 /// \param receiverTypeIfCall - if null, check this as if declaring it; 37 /// if non-null, check this as if making a call to it with the given 38 /// receiver type 39 /// 40 /// \return true to indicate that there was an error and appropriate 41 /// actions were taken 42 bool Sema::checkInitMethod(ObjCMethodDecl *method, 43 QualType receiverTypeIfCall) { 44 if (method->isInvalidDecl()) return true; 45 46 // This castAs is safe: methods that don't return an object 47 // pointer won't be inferred as inits and will reject an explicit 48 // objc_method_family(init). 49 50 // We ignore protocols here. Should we? What about Class? 51 52 const ObjCObjectType *result = method->getResultType() 53 ->castAs<ObjCObjectPointerType>()->getObjectType(); 54 55 if (result->isObjCId()) { 56 return false; 57 } else if (result->isObjCClass()) { 58 // fall through: always an error 59 } else { 60 ObjCInterfaceDecl *resultClass = result->getInterface(); 61 assert(resultClass && "unexpected object type!"); 62 63 // It's okay for the result type to still be a forward declaration 64 // if we're checking an interface declaration. 65 if (!resultClass->hasDefinition()) { 66 if (receiverTypeIfCall.isNull() && 67 !isa<ObjCImplementationDecl>(method->getDeclContext())) 68 return false; 69 70 // Otherwise, we try to compare class types. 71 } else { 72 // If this method was declared in a protocol, we can't check 73 // anything unless we have a receiver type that's an interface. 74 const ObjCInterfaceDecl *receiverClass = 0; 75 if (isa<ObjCProtocolDecl>(method->getDeclContext())) { 76 if (receiverTypeIfCall.isNull()) 77 return false; 78 79 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>() 80 ->getInterfaceDecl(); 81 82 // This can be null for calls to e.g. id<Foo>. 83 if (!receiverClass) return false; 84 } else { 85 receiverClass = method->getClassInterface(); 86 assert(receiverClass && "method not associated with a class!"); 87 } 88 89 // If either class is a subclass of the other, it's fine. 90 if (receiverClass->isSuperClassOf(resultClass) || 91 resultClass->isSuperClassOf(receiverClass)) 92 return false; 93 } 94 } 95 96 SourceLocation loc = method->getLocation(); 97 98 // If we're in a system header, and this is not a call, just make 99 // the method unusable. 100 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) { 101 method->addAttr(UnavailableAttr::CreateImplicit(Context, 102 "init method returns a type unrelated to its receiver type", 103 loc)); 104 return true; 105 } 106 107 // Otherwise, it's an error. 108 Diag(loc, diag::err_arc_init_method_unrelated_result_type); 109 method->setInvalidDecl(); 110 return true; 111 } 112 113 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 114 const ObjCMethodDecl *Overridden) { 115 if (Overridden->hasRelatedResultType() && 116 !NewMethod->hasRelatedResultType()) { 117 // This can only happen when the method follows a naming convention that 118 // implies a related result type, and the original (overridden) method has 119 // a suitable return type, but the new (overriding) method does not have 120 // a suitable return type. 121 QualType ResultType = NewMethod->getResultType(); 122 SourceRange ResultTypeRange; 123 if (const TypeSourceInfo *ResultTypeInfo 124 = NewMethod->getResultTypeSourceInfo()) 125 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange(); 126 127 // Figure out which class this method is part of, if any. 128 ObjCInterfaceDecl *CurrentClass 129 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext()); 130 if (!CurrentClass) { 131 DeclContext *DC = NewMethod->getDeclContext(); 132 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC)) 133 CurrentClass = Cat->getClassInterface(); 134 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC)) 135 CurrentClass = Impl->getClassInterface(); 136 else if (ObjCCategoryImplDecl *CatImpl 137 = dyn_cast<ObjCCategoryImplDecl>(DC)) 138 CurrentClass = CatImpl->getClassInterface(); 139 } 140 141 if (CurrentClass) { 142 Diag(NewMethod->getLocation(), 143 diag::warn_related_result_type_compatibility_class) 144 << Context.getObjCInterfaceType(CurrentClass) 145 << ResultType 146 << ResultTypeRange; 147 } else { 148 Diag(NewMethod->getLocation(), 149 diag::warn_related_result_type_compatibility_protocol) 150 << ResultType 151 << ResultTypeRange; 152 } 153 154 if (ObjCMethodFamily Family = Overridden->getMethodFamily()) 155 Diag(Overridden->getLocation(), 156 diag::note_related_result_type_family) 157 << /*overridden method*/ 0 158 << Family; 159 else 160 Diag(Overridden->getLocation(), 161 diag::note_related_result_type_overridden); 162 } 163 if (getLangOpts().ObjCAutoRefCount) { 164 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() != 165 Overridden->hasAttr<NSReturnsRetainedAttr>())) { 166 Diag(NewMethod->getLocation(), 167 diag::err_nsreturns_retained_attribute_mismatch) << 1; 168 Diag(Overridden->getLocation(), diag::note_previous_decl) 169 << "method"; 170 } 171 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() != 172 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) { 173 Diag(NewMethod->getLocation(), 174 diag::err_nsreturns_retained_attribute_mismatch) << 0; 175 Diag(Overridden->getLocation(), diag::note_previous_decl) 176 << "method"; 177 } 178 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(), 179 oe = Overridden->param_end(); 180 for (ObjCMethodDecl::param_iterator 181 ni = NewMethod->param_begin(), ne = NewMethod->param_end(); 182 ni != ne && oi != oe; ++ni, ++oi) { 183 const ParmVarDecl *oldDecl = (*oi); 184 ParmVarDecl *newDecl = (*ni); 185 if (newDecl->hasAttr<NSConsumedAttr>() != 186 oldDecl->hasAttr<NSConsumedAttr>()) { 187 Diag(newDecl->getLocation(), 188 diag::err_nsconsumed_attribute_mismatch); 189 Diag(oldDecl->getLocation(), diag::note_previous_decl) 190 << "parameter"; 191 } 192 } 193 } 194 } 195 196 /// \brief Check a method declaration for compatibility with the Objective-C 197 /// ARC conventions. 198 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) { 199 ObjCMethodFamily family = method->getMethodFamily(); 200 switch (family) { 201 case OMF_None: 202 case OMF_finalize: 203 case OMF_retain: 204 case OMF_release: 205 case OMF_autorelease: 206 case OMF_retainCount: 207 case OMF_self: 208 case OMF_performSelector: 209 return false; 210 211 case OMF_dealloc: 212 if (!Context.hasSameType(method->getResultType(), Context.VoidTy)) { 213 SourceRange ResultTypeRange; 214 if (const TypeSourceInfo *ResultTypeInfo 215 = method->getResultTypeSourceInfo()) 216 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange(); 217 if (ResultTypeRange.isInvalid()) 218 Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 219 << method->getResultType() 220 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)"); 221 else 222 Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 223 << method->getResultType() 224 << FixItHint::CreateReplacement(ResultTypeRange, "void"); 225 return true; 226 } 227 return false; 228 229 case OMF_init: 230 // If the method doesn't obey the init rules, don't bother annotating it. 231 if (checkInitMethod(method, QualType())) 232 return true; 233 234 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context)); 235 236 // Don't add a second copy of this attribute, but otherwise don't 237 // let it be suppressed. 238 if (method->hasAttr<NSReturnsRetainedAttr>()) 239 return false; 240 break; 241 242 case OMF_alloc: 243 case OMF_copy: 244 case OMF_mutableCopy: 245 case OMF_new: 246 if (method->hasAttr<NSReturnsRetainedAttr>() || 247 method->hasAttr<NSReturnsNotRetainedAttr>() || 248 method->hasAttr<NSReturnsAutoreleasedAttr>()) 249 return false; 250 break; 251 } 252 253 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(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 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc, 1229 ObjCMethodDecl *method, 1230 bool &IncompleteImpl, 1231 unsigned DiagID, 1232 NamedDecl *NeededFor = 0) { 1233 // No point warning no definition of method which is 'unavailable'. 1234 switch (method->getAvailability()) { 1235 case AR_Available: 1236 case AR_Deprecated: 1237 break; 1238 1239 // Don't warn about unavailable or not-yet-introduced methods. 1240 case AR_NotYetIntroduced: 1241 case AR_Unavailable: 1242 return; 1243 } 1244 1245 // FIXME: For now ignore 'IncompleteImpl'. 1246 // Previously we grouped all unimplemented methods under a single 1247 // warning, but some users strongly voiced that they would prefer 1248 // separate warnings. We will give that approach a try, as that 1249 // matches what we do with protocols. 1250 { 1251 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID); 1252 B << method; 1253 if (NeededFor) 1254 B << NeededFor; 1255 } 1256 1257 // Issue a note to the original declaration. 1258 SourceLocation MethodLoc = method->getLocStart(); 1259 if (MethodLoc.isValid()) 1260 S.Diag(MethodLoc, diag::note_method_declared_at) << method; 1261 } 1262 1263 /// Determines if type B can be substituted for type A. Returns true if we can 1264 /// guarantee that anything that the user will do to an object of type A can 1265 /// also be done to an object of type B. This is trivially true if the two 1266 /// types are the same, or if B is a subclass of A. It becomes more complex 1267 /// in cases where protocols are involved. 1268 /// 1269 /// Object types in Objective-C describe the minimum requirements for an 1270 /// object, rather than providing a complete description of a type. For 1271 /// example, if A is a subclass of B, then B* may refer to an instance of A. 1272 /// The principle of substitutability means that we may use an instance of A 1273 /// anywhere that we may use an instance of B - it will implement all of the 1274 /// ivars of B and all of the methods of B. 1275 /// 1276 /// This substitutability is important when type checking methods, because 1277 /// the implementation may have stricter type definitions than the interface. 1278 /// The interface specifies minimum requirements, but the implementation may 1279 /// have more accurate ones. For example, a method may privately accept 1280 /// instances of B, but only publish that it accepts instances of A. Any 1281 /// object passed to it will be type checked against B, and so will implicitly 1282 /// by a valid A*. Similarly, a method may return a subclass of the class that 1283 /// it is declared as returning. 1284 /// 1285 /// This is most important when considering subclassing. A method in a 1286 /// subclass must accept any object as an argument that its superclass's 1287 /// implementation accepts. It may, however, accept a more general type 1288 /// without breaking substitutability (i.e. you can still use the subclass 1289 /// anywhere that you can use the superclass, but not vice versa). The 1290 /// converse requirement applies to return types: the return type for a 1291 /// subclass method must be a valid object of the kind that the superclass 1292 /// advertises, but it may be specified more accurately. This avoids the need 1293 /// for explicit down-casting by callers. 1294 /// 1295 /// Note: This is a stricter requirement than for assignment. 1296 static bool isObjCTypeSubstitutable(ASTContext &Context, 1297 const ObjCObjectPointerType *A, 1298 const ObjCObjectPointerType *B, 1299 bool rejectId) { 1300 // Reject a protocol-unqualified id. 1301 if (rejectId && B->isObjCIdType()) return false; 1302 1303 // If B is a qualified id, then A must also be a qualified id and it must 1304 // implement all of the protocols in B. It may not be a qualified class. 1305 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a 1306 // stricter definition so it is not substitutable for id<A>. 1307 if (B->isObjCQualifiedIdType()) { 1308 return A->isObjCQualifiedIdType() && 1309 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0), 1310 QualType(B,0), 1311 false); 1312 } 1313 1314 /* 1315 // id is a special type that bypasses type checking completely. We want a 1316 // warning when it is used in one place but not another. 1317 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false; 1318 1319 1320 // If B is a qualified id, then A must also be a qualified id (which it isn't 1321 // if we've got this far) 1322 if (B->isObjCQualifiedIdType()) return false; 1323 */ 1324 1325 // Now we know that A and B are (potentially-qualified) class types. The 1326 // normal rules for assignment apply. 1327 return Context.canAssignObjCInterfaces(A, B); 1328 } 1329 1330 static SourceRange getTypeRange(TypeSourceInfo *TSI) { 1331 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange()); 1332 } 1333 1334 static bool CheckMethodOverrideReturn(Sema &S, 1335 ObjCMethodDecl *MethodImpl, 1336 ObjCMethodDecl *MethodDecl, 1337 bool IsProtocolMethodDecl, 1338 bool IsOverridingMode, 1339 bool Warn) { 1340 if (IsProtocolMethodDecl && 1341 (MethodDecl->getObjCDeclQualifier() != 1342 MethodImpl->getObjCDeclQualifier())) { 1343 if (Warn) { 1344 S.Diag(MethodImpl->getLocation(), 1345 (IsOverridingMode ? 1346 diag::warn_conflicting_overriding_ret_type_modifiers 1347 : diag::warn_conflicting_ret_type_modifiers)) 1348 << MethodImpl->getDeclName() 1349 << getTypeRange(MethodImpl->getResultTypeSourceInfo()); 1350 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration) 1351 << getTypeRange(MethodDecl->getResultTypeSourceInfo()); 1352 } 1353 else 1354 return false; 1355 } 1356 1357 if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(), 1358 MethodDecl->getResultType())) 1359 return true; 1360 if (!Warn) 1361 return false; 1362 1363 unsigned DiagID = 1364 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types 1365 : diag::warn_conflicting_ret_types; 1366 1367 // Mismatches between ObjC pointers go into a different warning 1368 // category, and sometimes they're even completely whitelisted. 1369 if (const ObjCObjectPointerType *ImplPtrTy = 1370 MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) { 1371 if (const ObjCObjectPointerType *IfacePtrTy = 1372 MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) { 1373 // Allow non-matching return types as long as they don't violate 1374 // the principle of substitutability. Specifically, we permit 1375 // return types that are subclasses of the declared return type, 1376 // or that are more-qualified versions of the declared type. 1377 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false)) 1378 return false; 1379 1380 DiagID = 1381 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types 1382 : diag::warn_non_covariant_ret_types; 1383 } 1384 } 1385 1386 S.Diag(MethodImpl->getLocation(), DiagID) 1387 << MethodImpl->getDeclName() 1388 << MethodDecl->getResultType() 1389 << MethodImpl->getResultType() 1390 << getTypeRange(MethodImpl->getResultTypeSourceInfo()); 1391 S.Diag(MethodDecl->getLocation(), 1392 IsOverridingMode ? diag::note_previous_declaration 1393 : diag::note_previous_definition) 1394 << getTypeRange(MethodDecl->getResultTypeSourceInfo()); 1395 return false; 1396 } 1397 1398 static bool CheckMethodOverrideParam(Sema &S, 1399 ObjCMethodDecl *MethodImpl, 1400 ObjCMethodDecl *MethodDecl, 1401 ParmVarDecl *ImplVar, 1402 ParmVarDecl *IfaceVar, 1403 bool IsProtocolMethodDecl, 1404 bool IsOverridingMode, 1405 bool Warn) { 1406 if (IsProtocolMethodDecl && 1407 (ImplVar->getObjCDeclQualifier() != 1408 IfaceVar->getObjCDeclQualifier())) { 1409 if (Warn) { 1410 if (IsOverridingMode) 1411 S.Diag(ImplVar->getLocation(), 1412 diag::warn_conflicting_overriding_param_modifiers) 1413 << getTypeRange(ImplVar->getTypeSourceInfo()) 1414 << MethodImpl->getDeclName(); 1415 else S.Diag(ImplVar->getLocation(), 1416 diag::warn_conflicting_param_modifiers) 1417 << getTypeRange(ImplVar->getTypeSourceInfo()) 1418 << MethodImpl->getDeclName(); 1419 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration) 1420 << getTypeRange(IfaceVar->getTypeSourceInfo()); 1421 } 1422 else 1423 return false; 1424 } 1425 1426 QualType ImplTy = ImplVar->getType(); 1427 QualType IfaceTy = IfaceVar->getType(); 1428 1429 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy)) 1430 return true; 1431 1432 if (!Warn) 1433 return false; 1434 unsigned DiagID = 1435 IsOverridingMode ? diag::warn_conflicting_overriding_param_types 1436 : diag::warn_conflicting_param_types; 1437 1438 // Mismatches between ObjC pointers go into a different warning 1439 // category, and sometimes they're even completely whitelisted. 1440 if (const ObjCObjectPointerType *ImplPtrTy = 1441 ImplTy->getAs<ObjCObjectPointerType>()) { 1442 if (const ObjCObjectPointerType *IfacePtrTy = 1443 IfaceTy->getAs<ObjCObjectPointerType>()) { 1444 // Allow non-matching argument types as long as they don't 1445 // violate the principle of substitutability. Specifically, the 1446 // implementation must accept any objects that the superclass 1447 // accepts, however it may also accept others. 1448 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true)) 1449 return false; 1450 1451 DiagID = 1452 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types 1453 : diag::warn_non_contravariant_param_types; 1454 } 1455 } 1456 1457 S.Diag(ImplVar->getLocation(), DiagID) 1458 << getTypeRange(ImplVar->getTypeSourceInfo()) 1459 << MethodImpl->getDeclName() << IfaceTy << ImplTy; 1460 S.Diag(IfaceVar->getLocation(), 1461 (IsOverridingMode ? diag::note_previous_declaration 1462 : diag::note_previous_definition)) 1463 << getTypeRange(IfaceVar->getTypeSourceInfo()); 1464 return false; 1465 } 1466 1467 /// In ARC, check whether the conventional meanings of the two methods 1468 /// match. If they don't, it's a hard error. 1469 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl, 1470 ObjCMethodDecl *decl) { 1471 ObjCMethodFamily implFamily = impl->getMethodFamily(); 1472 ObjCMethodFamily declFamily = decl->getMethodFamily(); 1473 if (implFamily == declFamily) return false; 1474 1475 // Since conventions are sorted by selector, the only possibility is 1476 // that the types differ enough to cause one selector or the other 1477 // to fall out of the family. 1478 assert(implFamily == OMF_None || declFamily == OMF_None); 1479 1480 // No further diagnostics required on invalid declarations. 1481 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true; 1482 1483 const ObjCMethodDecl *unmatched = impl; 1484 ObjCMethodFamily family = declFamily; 1485 unsigned errorID = diag::err_arc_lost_method_convention; 1486 unsigned noteID = diag::note_arc_lost_method_convention; 1487 if (declFamily == OMF_None) { 1488 unmatched = decl; 1489 family = implFamily; 1490 errorID = diag::err_arc_gained_method_convention; 1491 noteID = diag::note_arc_gained_method_convention; 1492 } 1493 1494 // Indexes into a %select clause in the diagnostic. 1495 enum FamilySelector { 1496 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new 1497 }; 1498 FamilySelector familySelector = FamilySelector(); 1499 1500 switch (family) { 1501 case OMF_None: llvm_unreachable("logic error, no method convention"); 1502 case OMF_retain: 1503 case OMF_release: 1504 case OMF_autorelease: 1505 case OMF_dealloc: 1506 case OMF_finalize: 1507 case OMF_retainCount: 1508 case OMF_self: 1509 case OMF_performSelector: 1510 // Mismatches for these methods don't change ownership 1511 // conventions, so we don't care. 1512 return false; 1513 1514 case OMF_init: familySelector = F_init; break; 1515 case OMF_alloc: familySelector = F_alloc; break; 1516 case OMF_copy: familySelector = F_copy; break; 1517 case OMF_mutableCopy: familySelector = F_mutableCopy; break; 1518 case OMF_new: familySelector = F_new; break; 1519 } 1520 1521 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn }; 1522 ReasonSelector reasonSelector; 1523 1524 // The only reason these methods don't fall within their families is 1525 // due to unusual result types. 1526 if (unmatched->getResultType()->isObjCObjectPointerType()) { 1527 reasonSelector = R_UnrelatedReturn; 1528 } else { 1529 reasonSelector = R_NonObjectReturn; 1530 } 1531 1532 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector); 1533 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector); 1534 1535 return true; 1536 } 1537 1538 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, 1539 ObjCMethodDecl *MethodDecl, 1540 bool IsProtocolMethodDecl) { 1541 if (getLangOpts().ObjCAutoRefCount && 1542 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)) 1543 return; 1544 1545 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 1546 IsProtocolMethodDecl, false, 1547 true); 1548 1549 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 1550 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 1551 EF = MethodDecl->param_end(); 1552 IM != EM && IF != EF; ++IM, ++IF) { 1553 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF, 1554 IsProtocolMethodDecl, false, true); 1555 } 1556 1557 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) { 1558 Diag(ImpMethodDecl->getLocation(), 1559 diag::warn_conflicting_variadic); 1560 Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 1561 } 1562 } 1563 1564 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 1565 ObjCMethodDecl *Overridden, 1566 bool IsProtocolMethodDecl) { 1567 1568 CheckMethodOverrideReturn(*this, Method, Overridden, 1569 IsProtocolMethodDecl, true, 1570 true); 1571 1572 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(), 1573 IF = Overridden->param_begin(), EM = Method->param_end(), 1574 EF = Overridden->param_end(); 1575 IM != EM && IF != EF; ++IM, ++IF) { 1576 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF, 1577 IsProtocolMethodDecl, true, true); 1578 } 1579 1580 if (Method->isVariadic() != Overridden->isVariadic()) { 1581 Diag(Method->getLocation(), 1582 diag::warn_conflicting_overriding_variadic); 1583 Diag(Overridden->getLocation(), diag::note_previous_declaration); 1584 } 1585 } 1586 1587 /// WarnExactTypedMethods - This routine issues a warning if method 1588 /// implementation declaration matches exactly that of its declaration. 1589 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, 1590 ObjCMethodDecl *MethodDecl, 1591 bool IsProtocolMethodDecl) { 1592 // don't issue warning when protocol method is optional because primary 1593 // class is not required to implement it and it is safe for protocol 1594 // to implement it. 1595 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional) 1596 return; 1597 // don't issue warning when primary class's method is 1598 // depecated/unavailable. 1599 if (MethodDecl->hasAttr<UnavailableAttr>() || 1600 MethodDecl->hasAttr<DeprecatedAttr>()) 1601 return; 1602 1603 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 1604 IsProtocolMethodDecl, false, false); 1605 if (match) 1606 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 1607 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 1608 EF = MethodDecl->param_end(); 1609 IM != EM && IF != EF; ++IM, ++IF) { 1610 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, 1611 *IM, *IF, 1612 IsProtocolMethodDecl, false, false); 1613 if (!match) 1614 break; 1615 } 1616 if (match) 1617 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic()); 1618 if (match) 1619 match = !(MethodDecl->isClassMethod() && 1620 MethodDecl->getSelector() == GetNullarySelector("load", Context)); 1621 1622 if (match) { 1623 Diag(ImpMethodDecl->getLocation(), 1624 diag::warn_category_method_impl_match); 1625 Diag(MethodDecl->getLocation(), diag::note_method_declared_at) 1626 << MethodDecl->getDeclName(); 1627 } 1628 } 1629 1630 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely 1631 /// improve the efficiency of selector lookups and type checking by associating 1632 /// with each protocol / interface / category the flattened instance tables. If 1633 /// we used an immutable set to keep the table then it wouldn't add significant 1634 /// memory cost and it would be handy for lookups. 1635 1636 /// CheckProtocolMethodDefs - This routine checks unimplemented methods 1637 /// Declared in protocol, and those referenced by it. 1638 static void CheckProtocolMethodDefs(Sema &S, 1639 SourceLocation ImpLoc, 1640 ObjCProtocolDecl *PDecl, 1641 bool& IncompleteImpl, 1642 const Sema::SelectorSet &InsMap, 1643 const Sema::SelectorSet &ClsMap, 1644 ObjCContainerDecl *CDecl, 1645 bool isExplicitProtocol = true) { 1646 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); 1647 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() 1648 : dyn_cast<ObjCInterfaceDecl>(CDecl); 1649 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null"); 1650 1651 ObjCInterfaceDecl *Super = IDecl->getSuperClass(); 1652 ObjCInterfaceDecl *NSIDecl = 0; 1653 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) { 1654 // check to see if class implements forwardInvocation method and objects 1655 // of this class are derived from 'NSProxy' so that to forward requests 1656 // from one object to another. 1657 // Under such conditions, which means that every method possible is 1658 // implemented in the class, we should not issue "Method definition not 1659 // found" warnings. 1660 // FIXME: Use a general GetUnarySelector method for this. 1661 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation"); 1662 Selector fISelector = S.Context.Selectors.getSelector(1, &II); 1663 if (InsMap.count(fISelector)) 1664 // Is IDecl derived from 'NSProxy'? If so, no instance methods 1665 // need be implemented in the implementation. 1666 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy")); 1667 } 1668 1669 // If this is a forward protocol declaration, get its definition. 1670 if (!PDecl->isThisDeclarationADefinition() && 1671 PDecl->getDefinition()) 1672 PDecl = PDecl->getDefinition(); 1673 1674 // If a method lookup fails locally we still need to look and see if 1675 // the method was implemented by a base class or an inherited 1676 // protocol. This lookup is slow, but occurs rarely in correct code 1677 // and otherwise would terminate in a warning. 1678 if (isExplicitProtocol && PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) 1679 Super = NULL; 1680 1681 // check unimplemented instance methods. 1682 if (!NSIDecl) 1683 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(), 1684 E = PDecl->instmeth_end(); I != E; ++I) { 1685 ObjCMethodDecl *method = *I; 1686 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 1687 !method->isPropertyAccessor() && 1688 !InsMap.count(method->getSelector()) && 1689 (!Super || !Super->lookupMethod(method->getSelector(), 1690 true /* instance */, 1691 false /* shallowCategory */, 1692 true /* followsSuper */, 1693 NULL /* category */))) { 1694 // If a method is not implemented in the category implementation but 1695 // has been declared in its primary class, superclass, 1696 // or in one of their protocols, no need to issue the warning. 1697 // This is because method will be implemented in the primary class 1698 // or one of its super class implementation. 1699 1700 // Ugly, but necessary. Method declared in protcol might have 1701 // have been synthesized due to a property declared in the class which 1702 // uses the protocol. 1703 if (ObjCMethodDecl *MethodInClass = 1704 IDecl->lookupMethod(method->getSelector(), 1705 true /* instance */, 1706 true /* shallowCategoryLookup */, 1707 false /* followSuper */)) 1708 if (C || MethodInClass->isPropertyAccessor()) 1709 continue; 1710 unsigned DIAG = diag::warn_unimplemented_protocol_method; 1711 if (S.Diags.getDiagnosticLevel(DIAG, ImpLoc) 1712 != DiagnosticsEngine::Ignored) { 1713 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, 1714 PDecl); 1715 } 1716 } 1717 } 1718 // check unimplemented class methods 1719 for (ObjCProtocolDecl::classmeth_iterator 1720 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); 1721 I != E; ++I) { 1722 ObjCMethodDecl *method = *I; 1723 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 1724 !ClsMap.count(method->getSelector()) && 1725 (!Super || !Super->lookupMethod(method->getSelector(), 1726 false /* class method */, 1727 false /* shallowCategoryLookup */, 1728 true /* followSuper */, 1729 NULL /* category */))) { 1730 // See above comment for instance method lookups. 1731 if (C && IDecl->lookupMethod(method->getSelector(), 1732 false /* class */, 1733 true /* shallowCategoryLookup */, 1734 false /* followSuper */)) 1735 continue; 1736 1737 unsigned DIAG = diag::warn_unimplemented_protocol_method; 1738 if (S.Diags.getDiagnosticLevel(DIAG, ImpLoc) != 1739 DiagnosticsEngine::Ignored) { 1740 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl); 1741 } 1742 } 1743 } 1744 // Check on this protocols's referenced protocols, recursively. 1745 for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(), 1746 E = PDecl->protocol_end(); PI != E; ++PI) 1747 CheckProtocolMethodDefs(S, ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, 1748 CDecl, /* isExplicitProtocl */ false); 1749 } 1750 1751 /// MatchAllMethodDeclarations - Check methods declared in interface 1752 /// or protocol against those declared in their implementations. 1753 /// 1754 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, 1755 const SelectorSet &ClsMap, 1756 SelectorSet &InsMapSeen, 1757 SelectorSet &ClsMapSeen, 1758 ObjCImplDecl* IMPDecl, 1759 ObjCContainerDecl* CDecl, 1760 bool &IncompleteImpl, 1761 bool ImmediateClass, 1762 bool WarnCategoryMethodImpl) { 1763 // Check and see if instance methods in class interface have been 1764 // implemented in the implementation class. If so, their types match. 1765 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(), 1766 E = CDecl->instmeth_end(); I != E; ++I) { 1767 if (!InsMapSeen.insert((*I)->getSelector())) 1768 continue; 1769 if (!(*I)->isPropertyAccessor() && 1770 !InsMap.count((*I)->getSelector())) { 1771 if (ImmediateClass) 1772 WarnUndefinedMethod(*this, IMPDecl->getLocation(), *I, IncompleteImpl, 1773 diag::warn_undef_method_impl); 1774 continue; 1775 } else { 1776 ObjCMethodDecl *ImpMethodDecl = 1777 IMPDecl->getInstanceMethod((*I)->getSelector()); 1778 assert(CDecl->getInstanceMethod((*I)->getSelector()) && 1779 "Expected to find the method through lookup as well"); 1780 ObjCMethodDecl *MethodDecl = *I; 1781 // ImpMethodDecl may be null as in a @dynamic property. 1782 if (ImpMethodDecl) { 1783 if (!WarnCategoryMethodImpl) 1784 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl, 1785 isa<ObjCProtocolDecl>(CDecl)); 1786 else if (!MethodDecl->isPropertyAccessor()) 1787 WarnExactTypedMethods(ImpMethodDecl, MethodDecl, 1788 isa<ObjCProtocolDecl>(CDecl)); 1789 } 1790 } 1791 } 1792 1793 // Check and see if class methods in class interface have been 1794 // implemented in the implementation class. If so, their types match. 1795 for (ObjCInterfaceDecl::classmeth_iterator I = CDecl->classmeth_begin(), 1796 E = CDecl->classmeth_end(); 1797 I != E; ++I) { 1798 if (!ClsMapSeen.insert((*I)->getSelector())) 1799 continue; 1800 if (!ClsMap.count((*I)->getSelector())) { 1801 if (ImmediateClass) 1802 WarnUndefinedMethod(*this, IMPDecl->getLocation(), *I, IncompleteImpl, 1803 diag::warn_undef_method_impl); 1804 } else { 1805 ObjCMethodDecl *ImpMethodDecl = 1806 IMPDecl->getClassMethod((*I)->getSelector()); 1807 assert(CDecl->getClassMethod((*I)->getSelector()) && 1808 "Expected to find the method through lookup as well"); 1809 ObjCMethodDecl *MethodDecl = *I; 1810 if (!WarnCategoryMethodImpl) 1811 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl, 1812 isa<ObjCProtocolDecl>(CDecl)); 1813 else 1814 WarnExactTypedMethods(ImpMethodDecl, MethodDecl, 1815 isa<ObjCProtocolDecl>(CDecl)); 1816 } 1817 } 1818 1819 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) { 1820 // Also, check for methods declared in protocols inherited by 1821 // this protocol. 1822 for (ObjCProtocolDecl::protocol_iterator 1823 PI = PD->protocol_begin(), E = PD->protocol_end(); PI != E; ++PI) 1824 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1825 IMPDecl, (*PI), IncompleteImpl, false, 1826 WarnCategoryMethodImpl); 1827 } 1828 1829 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 1830 // when checking that methods in implementation match their declaration, 1831 // i.e. when WarnCategoryMethodImpl is false, check declarations in class 1832 // extension; as well as those in categories. 1833 if (!WarnCategoryMethodImpl) { 1834 for (ObjCInterfaceDecl::visible_categories_iterator 1835 Cat = I->visible_categories_begin(), 1836 CatEnd = I->visible_categories_end(); 1837 Cat != CatEnd; ++Cat) { 1838 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1839 IMPDecl, *Cat, IncompleteImpl, false, 1840 WarnCategoryMethodImpl); 1841 } 1842 } else { 1843 // Also methods in class extensions need be looked at next. 1844 for (ObjCInterfaceDecl::visible_extensions_iterator 1845 Ext = I->visible_extensions_begin(), 1846 ExtEnd = I->visible_extensions_end(); 1847 Ext != ExtEnd; ++Ext) { 1848 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1849 IMPDecl, *Ext, IncompleteImpl, false, 1850 WarnCategoryMethodImpl); 1851 } 1852 } 1853 1854 // Check for any implementation of a methods declared in protocol. 1855 for (ObjCInterfaceDecl::all_protocol_iterator 1856 PI = I->all_referenced_protocol_begin(), 1857 E = I->all_referenced_protocol_end(); PI != E; ++PI) 1858 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1859 IMPDecl, 1860 (*PI), IncompleteImpl, false, 1861 WarnCategoryMethodImpl); 1862 1863 // FIXME. For now, we are not checking for extact match of methods 1864 // in category implementation and its primary class's super class. 1865 if (!WarnCategoryMethodImpl && I->getSuperClass()) 1866 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1867 IMPDecl, 1868 I->getSuperClass(), IncompleteImpl, false); 1869 } 1870 } 1871 1872 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 1873 /// category matches with those implemented in its primary class and 1874 /// warns each time an exact match is found. 1875 void Sema::CheckCategoryVsClassMethodMatches( 1876 ObjCCategoryImplDecl *CatIMPDecl) { 1877 // Get category's primary class. 1878 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl(); 1879 if (!CatDecl) 1880 return; 1881 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface(); 1882 if (!IDecl) 1883 return; 1884 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass(); 1885 SelectorSet InsMap, ClsMap; 1886 1887 for (ObjCImplementationDecl::instmeth_iterator 1888 I = CatIMPDecl->instmeth_begin(), 1889 E = CatIMPDecl->instmeth_end(); I!=E; ++I) { 1890 Selector Sel = (*I)->getSelector(); 1891 // When checking for methods implemented in the category, skip over 1892 // those declared in category class's super class. This is because 1893 // the super class must implement the method. 1894 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true)) 1895 continue; 1896 InsMap.insert(Sel); 1897 } 1898 1899 for (ObjCImplementationDecl::classmeth_iterator 1900 I = CatIMPDecl->classmeth_begin(), 1901 E = CatIMPDecl->classmeth_end(); I != E; ++I) { 1902 Selector Sel = (*I)->getSelector(); 1903 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false)) 1904 continue; 1905 ClsMap.insert(Sel); 1906 } 1907 if (InsMap.empty() && ClsMap.empty()) 1908 return; 1909 1910 SelectorSet InsMapSeen, ClsMapSeen; 1911 bool IncompleteImpl = false; 1912 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1913 CatIMPDecl, IDecl, 1914 IncompleteImpl, false, 1915 true /*WarnCategoryMethodImpl*/); 1916 } 1917 1918 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 1919 ObjCContainerDecl* CDecl, 1920 bool IncompleteImpl) { 1921 SelectorSet InsMap; 1922 // Check and see if instance methods in class interface have been 1923 // implemented in the implementation class. 1924 for (ObjCImplementationDecl::instmeth_iterator 1925 I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I) 1926 InsMap.insert((*I)->getSelector()); 1927 1928 // Check and see if properties declared in the interface have either 1) 1929 // an implementation or 2) there is a @synthesize/@dynamic implementation 1930 // of the property in the @implementation. 1931 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) 1932 if (!(LangOpts.ObjCDefaultSynthProperties && 1933 LangOpts.ObjCRuntime.isNonFragile()) || 1934 IDecl->isObjCRequiresPropertyDefs()) 1935 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl); 1936 1937 SelectorSet ClsMap; 1938 for (ObjCImplementationDecl::classmeth_iterator 1939 I = IMPDecl->classmeth_begin(), 1940 E = IMPDecl->classmeth_end(); I != E; ++I) 1941 ClsMap.insert((*I)->getSelector()); 1942 1943 // Check for type conflict of methods declared in a class/protocol and 1944 // its implementation; if any. 1945 SelectorSet InsMapSeen, ClsMapSeen; 1946 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1947 IMPDecl, CDecl, 1948 IncompleteImpl, true); 1949 1950 // check all methods implemented in category against those declared 1951 // in its primary class. 1952 if (ObjCCategoryImplDecl *CatDecl = 1953 dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) 1954 CheckCategoryVsClassMethodMatches(CatDecl); 1955 1956 // Check the protocol list for unimplemented methods in the @implementation 1957 // class. 1958 // Check and see if class methods in class interface have been 1959 // implemented in the implementation class. 1960 1961 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 1962 for (ObjCInterfaceDecl::all_protocol_iterator 1963 PI = I->all_referenced_protocol_begin(), 1964 E = I->all_referenced_protocol_end(); PI != E; ++PI) 1965 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), *PI, 1966 IncompleteImpl, InsMap, ClsMap, I); 1967 // Check class extensions (unnamed categories) 1968 for (ObjCInterfaceDecl::visible_extensions_iterator 1969 Ext = I->visible_extensions_begin(), 1970 ExtEnd = I->visible_extensions_end(); 1971 Ext != ExtEnd; ++Ext) { 1972 ImplMethodsVsClassMethods(S, IMPDecl, *Ext, IncompleteImpl); 1973 } 1974 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1975 // For extended class, unimplemented methods in its protocols will 1976 // be reported in the primary class. 1977 if (!C->IsClassExtension()) { 1978 for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(), 1979 E = C->protocol_end(); PI != E; ++PI) 1980 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), *PI, 1981 IncompleteImpl, InsMap, ClsMap, CDecl); 1982 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl); 1983 } 1984 } else 1985 llvm_unreachable("invalid ObjCContainerDecl type."); 1986 } 1987 1988 /// ActOnForwardClassDeclaration - 1989 Sema::DeclGroupPtrTy 1990 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, 1991 IdentifierInfo **IdentList, 1992 SourceLocation *IdentLocs, 1993 unsigned NumElts) { 1994 SmallVector<Decl *, 8> DeclsInGroup; 1995 for (unsigned i = 0; i != NumElts; ++i) { 1996 // Check for another declaration kind with the same name. 1997 NamedDecl *PrevDecl 1998 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 1999 LookupOrdinaryName, ForRedeclaration); 2000 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 2001 // GCC apparently allows the following idiom: 2002 // 2003 // typedef NSObject < XCElementTogglerP > XCElementToggler; 2004 // @class XCElementToggler; 2005 // 2006 // Here we have chosen to ignore the forward class declaration 2007 // with a warning. Since this is the implied behavior. 2008 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl); 2009 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) { 2010 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; 2011 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2012 } else { 2013 // a forward class declaration matching a typedef name of a class refers 2014 // to the underlying class. Just ignore the forward class with a warning 2015 // as this will force the intended behavior which is to lookup the typedef 2016 // name. 2017 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) { 2018 Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i]; 2019 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2020 continue; 2021 } 2022 } 2023 } 2024 2025 // Create a declaration to describe this forward declaration. 2026 ObjCInterfaceDecl *PrevIDecl 2027 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 2028 2029 IdentifierInfo *ClassName = IdentList[i]; 2030 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 2031 // A previous decl with a different name is because of 2032 // @compatibility_alias, for example: 2033 // \code 2034 // @class NewImage; 2035 // @compatibility_alias OldImage NewImage; 2036 // \endcode 2037 // A lookup for 'OldImage' will return the 'NewImage' decl. 2038 // 2039 // In such a case use the real declaration name, instead of the alias one, 2040 // otherwise we will break IdentifierResolver and redecls-chain invariants. 2041 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 2042 // has been aliased. 2043 ClassName = PrevIDecl->getIdentifier(); 2044 } 2045 2046 ObjCInterfaceDecl *IDecl 2047 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, 2048 ClassName, PrevIDecl, IdentLocs[i]); 2049 IDecl->setAtEndRange(IdentLocs[i]); 2050 2051 PushOnScopeChains(IDecl, TUScope); 2052 CheckObjCDeclScope(IDecl); 2053 DeclsInGroup.push_back(IDecl); 2054 } 2055 2056 return BuildDeclaratorGroup(DeclsInGroup, false); 2057 } 2058 2059 static bool tryMatchRecordTypes(ASTContext &Context, 2060 Sema::MethodMatchStrategy strategy, 2061 const Type *left, const Type *right); 2062 2063 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, 2064 QualType leftQT, QualType rightQT) { 2065 const Type *left = 2066 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr(); 2067 const Type *right = 2068 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr(); 2069 2070 if (left == right) return true; 2071 2072 // If we're doing a strict match, the types have to match exactly. 2073 if (strategy == Sema::MMS_strict) return false; 2074 2075 if (left->isIncompleteType() || right->isIncompleteType()) return false; 2076 2077 // Otherwise, use this absurdly complicated algorithm to try to 2078 // validate the basic, low-level compatibility of the two types. 2079 2080 // As a minimum, require the sizes and alignments to match. 2081 if (Context.getTypeInfo(left) != Context.getTypeInfo(right)) 2082 return false; 2083 2084 // Consider all the kinds of non-dependent canonical types: 2085 // - functions and arrays aren't possible as return and parameter types 2086 2087 // - vector types of equal size can be arbitrarily mixed 2088 if (isa<VectorType>(left)) return isa<VectorType>(right); 2089 if (isa<VectorType>(right)) return false; 2090 2091 // - references should only match references of identical type 2092 // - structs, unions, and Objective-C objects must match more-or-less 2093 // exactly 2094 // - everything else should be a scalar 2095 if (!left->isScalarType() || !right->isScalarType()) 2096 return tryMatchRecordTypes(Context, strategy, left, right); 2097 2098 // Make scalars agree in kind, except count bools as chars, and group 2099 // all non-member pointers together. 2100 Type::ScalarTypeKind leftSK = left->getScalarTypeKind(); 2101 Type::ScalarTypeKind rightSK = right->getScalarTypeKind(); 2102 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral; 2103 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral; 2104 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer) 2105 leftSK = Type::STK_ObjCObjectPointer; 2106 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer) 2107 rightSK = Type::STK_ObjCObjectPointer; 2108 2109 // Note that data member pointers and function member pointers don't 2110 // intermix because of the size differences. 2111 2112 return (leftSK == rightSK); 2113 } 2114 2115 static bool tryMatchRecordTypes(ASTContext &Context, 2116 Sema::MethodMatchStrategy strategy, 2117 const Type *lt, const Type *rt) { 2118 assert(lt && rt && lt != rt); 2119 2120 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false; 2121 RecordDecl *left = cast<RecordType>(lt)->getDecl(); 2122 RecordDecl *right = cast<RecordType>(rt)->getDecl(); 2123 2124 // Require union-hood to match. 2125 if (left->isUnion() != right->isUnion()) return false; 2126 2127 // Require an exact match if either is non-POD. 2128 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) || 2129 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD())) 2130 return false; 2131 2132 // Require size and alignment to match. 2133 if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false; 2134 2135 // Require fields to match. 2136 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end(); 2137 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end(); 2138 for (; li != le && ri != re; ++li, ++ri) { 2139 if (!matchTypes(Context, strategy, li->getType(), ri->getType())) 2140 return false; 2141 } 2142 return (li == le && ri == re); 2143 } 2144 2145 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and 2146 /// returns true, or false, accordingly. 2147 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons 2148 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left, 2149 const ObjCMethodDecl *right, 2150 MethodMatchStrategy strategy) { 2151 if (!matchTypes(Context, strategy, 2152 left->getResultType(), right->getResultType())) 2153 return false; 2154 2155 // If either is hidden, it is not considered to match. 2156 if (left->isHidden() || right->isHidden()) 2157 return false; 2158 2159 if (getLangOpts().ObjCAutoRefCount && 2160 (left->hasAttr<NSReturnsRetainedAttr>() 2161 != right->hasAttr<NSReturnsRetainedAttr>() || 2162 left->hasAttr<NSConsumesSelfAttr>() 2163 != right->hasAttr<NSConsumesSelfAttr>())) 2164 return false; 2165 2166 ObjCMethodDecl::param_const_iterator 2167 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(), 2168 re = right->param_end(); 2169 2170 for (; li != le && ri != re; ++li, ++ri) { 2171 assert(ri != right->param_end() && "Param mismatch"); 2172 const ParmVarDecl *lparm = *li, *rparm = *ri; 2173 2174 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType())) 2175 return false; 2176 2177 if (getLangOpts().ObjCAutoRefCount && 2178 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()) 2179 return false; 2180 } 2181 return true; 2182 } 2183 2184 void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) { 2185 // Record at the head of the list whether there were 0, 1, or >= 2 methods 2186 // inside categories. 2187 if (ObjCCategoryDecl * 2188 CD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) 2189 if (!CD->IsClassExtension() && List->getBits() < 2) 2190 List->setBits(List->getBits()+1); 2191 2192 // If the list is empty, make it a singleton list. 2193 if (List->Method == 0) { 2194 List->Method = Method; 2195 List->setNext(0); 2196 return; 2197 } 2198 2199 // We've seen a method with this name, see if we have already seen this type 2200 // signature. 2201 ObjCMethodList *Previous = List; 2202 for (; List; Previous = List, List = List->getNext()) { 2203 // If we are building a module, keep all of the methods. 2204 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) 2205 continue; 2206 2207 if (!MatchTwoMethodDeclarations(Method, List->Method)) 2208 continue; 2209 2210 ObjCMethodDecl *PrevObjCMethod = List->Method; 2211 2212 // Propagate the 'defined' bit. 2213 if (Method->isDefined()) 2214 PrevObjCMethod->setDefined(true); 2215 2216 // If a method is deprecated, push it in the global pool. 2217 // This is used for better diagnostics. 2218 if (Method->isDeprecated()) { 2219 if (!PrevObjCMethod->isDeprecated()) 2220 List->Method = Method; 2221 } 2222 // If new method is unavailable, push it into global pool 2223 // unless previous one is deprecated. 2224 if (Method->isUnavailable()) { 2225 if (PrevObjCMethod->getAvailability() < AR_Deprecated) 2226 List->Method = Method; 2227 } 2228 2229 return; 2230 } 2231 2232 // We have a new signature for an existing method - add it. 2233 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". 2234 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>(); 2235 Previous->setNext(new (Mem) ObjCMethodList(Method, 0)); 2236 } 2237 2238 /// \brief Read the contents of the method pool for a given selector from 2239 /// external storage. 2240 void Sema::ReadMethodPool(Selector Sel) { 2241 assert(ExternalSource && "We need an external AST source"); 2242 ExternalSource->ReadMethodPool(Sel); 2243 } 2244 2245 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, 2246 bool instance) { 2247 // Ignore methods of invalid containers. 2248 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl()) 2249 return; 2250 2251 if (ExternalSource) 2252 ReadMethodPool(Method->getSelector()); 2253 2254 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); 2255 if (Pos == MethodPool.end()) 2256 Pos = MethodPool.insert(std::make_pair(Method->getSelector(), 2257 GlobalMethods())).first; 2258 2259 Method->setDefined(impl); 2260 2261 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; 2262 addMethodToGlobalList(&Entry, Method); 2263 } 2264 2265 /// Determines if this is an "acceptable" loose mismatch in the global 2266 /// method pool. This exists mostly as a hack to get around certain 2267 /// global mismatches which we can't afford to make warnings / errors. 2268 /// Really, what we want is a way to take a method out of the global 2269 /// method pool. 2270 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen, 2271 ObjCMethodDecl *other) { 2272 if (!chosen->isInstanceMethod()) 2273 return false; 2274 2275 Selector sel = chosen->getSelector(); 2276 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length") 2277 return false; 2278 2279 // Don't complain about mismatches for -length if the method we 2280 // chose has an integral result type. 2281 return (chosen->getResultType()->isIntegerType()); 2282 } 2283 2284 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, 2285 bool receiverIdOrClass, 2286 bool warn, bool instance) { 2287 if (ExternalSource) 2288 ReadMethodPool(Sel); 2289 2290 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 2291 if (Pos == MethodPool.end()) 2292 return 0; 2293 2294 // Gather the non-hidden methods. 2295 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 2296 SmallVector<ObjCMethodDecl *, 4> Methods; 2297 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) { 2298 if (M->Method && !M->Method->isHidden()) { 2299 // If we're not supposed to warn about mismatches, we're done. 2300 if (!warn) 2301 return M->Method; 2302 2303 Methods.push_back(M->Method); 2304 } 2305 } 2306 2307 // If there aren't any visible methods, we're done. 2308 // FIXME: Recover if there are any known-but-hidden methods? 2309 if (Methods.empty()) 2310 return 0; 2311 2312 if (Methods.size() == 1) 2313 return Methods[0]; 2314 2315 // We found multiple methods, so we may have to complain. 2316 bool issueDiagnostic = false, issueError = false; 2317 2318 // We support a warning which complains about *any* difference in 2319 // method signature. 2320 bool strictSelectorMatch = 2321 (receiverIdOrClass && warn && 2322 (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl, 2323 R.getBegin()) 2324 != DiagnosticsEngine::Ignored)); 2325 if (strictSelectorMatch) { 2326 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2327 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) { 2328 issueDiagnostic = true; 2329 break; 2330 } 2331 } 2332 } 2333 2334 // If we didn't see any strict differences, we won't see any loose 2335 // differences. In ARC, however, we also need to check for loose 2336 // mismatches, because most of them are errors. 2337 if (!strictSelectorMatch || 2338 (issueDiagnostic && getLangOpts().ObjCAutoRefCount)) 2339 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2340 // This checks if the methods differ in type mismatch. 2341 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) && 2342 !isAcceptableMethodMismatch(Methods[0], Methods[I])) { 2343 issueDiagnostic = true; 2344 if (getLangOpts().ObjCAutoRefCount) 2345 issueError = true; 2346 break; 2347 } 2348 } 2349 2350 if (issueDiagnostic) { 2351 if (issueError) 2352 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; 2353 else if (strictSelectorMatch) 2354 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; 2355 else 2356 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; 2357 2358 Diag(Methods[0]->getLocStart(), 2359 issueError ? diag::note_possibility : diag::note_using) 2360 << Methods[0]->getSourceRange(); 2361 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 2362 Diag(Methods[I]->getLocStart(), diag::note_also_found) 2363 << Methods[I]->getSourceRange(); 2364 } 2365 } 2366 return Methods[0]; 2367 } 2368 2369 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { 2370 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 2371 if (Pos == MethodPool.end()) 2372 return 0; 2373 2374 GlobalMethods &Methods = Pos->second; 2375 2376 if (Methods.first.Method && Methods.first.Method->isDefined()) 2377 return Methods.first.Method; 2378 if (Methods.second.Method && Methods.second.Method->isDefined()) 2379 return Methods.second.Method; 2380 return 0; 2381 } 2382 2383 static void 2384 HelperSelectorsForTypoCorrection( 2385 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod, 2386 StringRef Typo, const ObjCMethodDecl * Method) { 2387 const unsigned MaxEditDistance = 1; 2388 unsigned BestEditDistance = MaxEditDistance + 1; 2389 std::string MethodName = Method->getSelector().getAsString(); 2390 2391 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size()); 2392 if (MinPossibleEditDistance > 0 && 2393 Typo.size() / MinPossibleEditDistance < 1) 2394 return; 2395 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance); 2396 if (EditDistance > MaxEditDistance) 2397 return; 2398 if (EditDistance == BestEditDistance) 2399 BestMethod.push_back(Method); 2400 else if (EditDistance < BestEditDistance) { 2401 BestMethod.clear(); 2402 BestMethod.push_back(Method); 2403 } 2404 } 2405 2406 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel, 2407 QualType ObjectType) { 2408 if (ObjectType.isNull()) 2409 return true; 2410 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/)) 2411 return true; 2412 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) != 0; 2413 } 2414 2415 const ObjCMethodDecl * 2416 Sema::SelectorsForTypoCorrection(Selector Sel, 2417 QualType ObjectType) { 2418 unsigned NumArgs = Sel.getNumArgs(); 2419 SmallVector<const ObjCMethodDecl *, 8> Methods; 2420 bool ObjectIsId = true, ObjectIsClass = true; 2421 if (ObjectType.isNull()) 2422 ObjectIsId = ObjectIsClass = false; 2423 else if (!ObjectType->isObjCObjectPointerType()) 2424 return 0; 2425 else if (const ObjCObjectPointerType *ObjCPtr = 2426 ObjectType->getAsObjCInterfacePointerType()) { 2427 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0); 2428 ObjectIsId = ObjectIsClass = false; 2429 } 2430 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType()) 2431 ObjectIsClass = false; 2432 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType()) 2433 ObjectIsId = false; 2434 else 2435 return 0; 2436 2437 for (GlobalMethodPool::iterator b = MethodPool.begin(), 2438 e = MethodPool.end(); b != e; b++) { 2439 // instance methods 2440 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext()) 2441 if (M->Method && 2442 (M->Method->getSelector().getNumArgs() == NumArgs) && 2443 (M->Method->getSelector() != Sel)) { 2444 if (ObjectIsId) 2445 Methods.push_back(M->Method); 2446 else if (!ObjectIsClass && 2447 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType)) 2448 Methods.push_back(M->Method); 2449 } 2450 // class methods 2451 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext()) 2452 if (M->Method && 2453 (M->Method->getSelector().getNumArgs() == NumArgs) && 2454 (M->Method->getSelector() != Sel)) { 2455 if (ObjectIsClass) 2456 Methods.push_back(M->Method); 2457 else if (!ObjectIsId && 2458 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType)) 2459 Methods.push_back(M->Method); 2460 } 2461 } 2462 2463 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods; 2464 for (unsigned i = 0, e = Methods.size(); i < e; i++) { 2465 HelperSelectorsForTypoCorrection(SelectedMethods, 2466 Sel.getAsString(), Methods[i]); 2467 } 2468 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : NULL; 2469 } 2470 2471 /// DiagnoseDuplicateIvars - 2472 /// Check for duplicate ivars in the entire class at the start of 2473 /// \@implementation. This becomes necesssary because class extension can 2474 /// add ivars to a class in random order which will not be known until 2475 /// class's \@implementation is seen. 2476 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 2477 ObjCInterfaceDecl *SID) { 2478 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(), 2479 IVE = ID->ivar_end(); IVI != IVE; ++IVI) { 2480 ObjCIvarDecl* Ivar = *IVI; 2481 if (Ivar->isInvalidDecl()) 2482 continue; 2483 if (IdentifierInfo *II = Ivar->getIdentifier()) { 2484 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II); 2485 if (prevIvar) { 2486 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 2487 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 2488 Ivar->setInvalidDecl(); 2489 } 2490 } 2491 } 2492 } 2493 2494 Sema::ObjCContainerKind Sema::getObjCContainerKind() const { 2495 switch (CurContext->getDeclKind()) { 2496 case Decl::ObjCInterface: 2497 return Sema::OCK_Interface; 2498 case Decl::ObjCProtocol: 2499 return Sema::OCK_Protocol; 2500 case Decl::ObjCCategory: 2501 if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension()) 2502 return Sema::OCK_ClassExtension; 2503 else 2504 return Sema::OCK_Category; 2505 case Decl::ObjCImplementation: 2506 return Sema::OCK_Implementation; 2507 case Decl::ObjCCategoryImpl: 2508 return Sema::OCK_CategoryImplementation; 2509 2510 default: 2511 return Sema::OCK_None; 2512 } 2513 } 2514 2515 // Note: For class/category implementations, allMethods is always null. 2516 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods, 2517 ArrayRef<DeclGroupPtrTy> allTUVars) { 2518 if (getObjCContainerKind() == Sema::OCK_None) 2519 return 0; 2520 2521 assert(AtEnd.isValid() && "Invalid location for '@end'"); 2522 2523 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 2524 Decl *ClassDecl = cast<Decl>(OCD); 2525 2526 bool isInterfaceDeclKind = 2527 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) 2528 || isa<ObjCProtocolDecl>(ClassDecl); 2529 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); 2530 2531 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. 2532 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; 2533 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; 2534 2535 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) { 2536 ObjCMethodDecl *Method = 2537 cast_or_null<ObjCMethodDecl>(allMethods[i]); 2538 2539 if (!Method) continue; // Already issued a diagnostic. 2540 if (Method->isInstanceMethod()) { 2541 /// Check for instance method of the same name with incompatible types 2542 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; 2543 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 2544 : false; 2545 if ((isInterfaceDeclKind && PrevMethod && !match) 2546 || (checkIdenticalMethods && match)) { 2547 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 2548 << Method->getDeclName(); 2549 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2550 Method->setInvalidDecl(); 2551 } else { 2552 if (PrevMethod) { 2553 Method->setAsRedeclaration(PrevMethod); 2554 if (!Context.getSourceManager().isInSystemHeader( 2555 Method->getLocation())) 2556 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 2557 << Method->getDeclName(); 2558 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2559 } 2560 InsMap[Method->getSelector()] = Method; 2561 /// The following allows us to typecheck messages to "id". 2562 AddInstanceMethodToGlobalPool(Method); 2563 } 2564 } else { 2565 /// Check for class method of the same name with incompatible types 2566 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; 2567 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 2568 : false; 2569 if ((isInterfaceDeclKind && PrevMethod && !match) 2570 || (checkIdenticalMethods && match)) { 2571 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 2572 << Method->getDeclName(); 2573 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2574 Method->setInvalidDecl(); 2575 } else { 2576 if (PrevMethod) { 2577 Method->setAsRedeclaration(PrevMethod); 2578 if (!Context.getSourceManager().isInSystemHeader( 2579 Method->getLocation())) 2580 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 2581 << Method->getDeclName(); 2582 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2583 } 2584 ClsMap[Method->getSelector()] = Method; 2585 AddFactoryMethodToGlobalPool(Method); 2586 } 2587 } 2588 } 2589 if (isa<ObjCInterfaceDecl>(ClassDecl)) { 2590 // Nothing to do here. 2591 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 2592 // Categories are used to extend the class by declaring new methods. 2593 // By the same token, they are also used to add new properties. No 2594 // need to compare the added property to those in the class. 2595 2596 if (C->IsClassExtension()) { 2597 ObjCInterfaceDecl *CCPrimary = C->getClassInterface(); 2598 DiagnoseClassExtensionDupMethods(C, CCPrimary); 2599 } 2600 } 2601 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { 2602 if (CDecl->getIdentifier()) 2603 // ProcessPropertyDecl is responsible for diagnosing conflicts with any 2604 // user-defined setter/getter. It also synthesizes setter/getter methods 2605 // and adds them to the DeclContext and global method pools. 2606 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(), 2607 E = CDecl->prop_end(); 2608 I != E; ++I) 2609 ProcessPropertyDecl(*I, CDecl); 2610 CDecl->setAtEndRange(AtEnd); 2611 } 2612 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { 2613 IC->setAtEndRange(AtEnd); 2614 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) { 2615 // Any property declared in a class extension might have user 2616 // declared setter or getter in current class extension or one 2617 // of the other class extensions. Mark them as synthesized as 2618 // property will be synthesized when property with same name is 2619 // seen in the @implementation. 2620 for (ObjCInterfaceDecl::visible_extensions_iterator 2621 Ext = IDecl->visible_extensions_begin(), 2622 ExtEnd = IDecl->visible_extensions_end(); 2623 Ext != ExtEnd; ++Ext) { 2624 for (ObjCContainerDecl::prop_iterator I = Ext->prop_begin(), 2625 E = Ext->prop_end(); I != E; ++I) { 2626 ObjCPropertyDecl *Property = *I; 2627 // Skip over properties declared @dynamic 2628 if (const ObjCPropertyImplDecl *PIDecl 2629 = IC->FindPropertyImplDecl(Property->getIdentifier())) 2630 if (PIDecl->getPropertyImplementation() 2631 == ObjCPropertyImplDecl::Dynamic) 2632 continue; 2633 2634 for (ObjCInterfaceDecl::visible_extensions_iterator 2635 Ext = IDecl->visible_extensions_begin(), 2636 ExtEnd = IDecl->visible_extensions_end(); 2637 Ext != ExtEnd; ++Ext) { 2638 if (ObjCMethodDecl *GetterMethod 2639 = Ext->getInstanceMethod(Property->getGetterName())) 2640 GetterMethod->setPropertyAccessor(true); 2641 if (!Property->isReadOnly()) 2642 if (ObjCMethodDecl *SetterMethod 2643 = Ext->getInstanceMethod(Property->getSetterName())) 2644 SetterMethod->setPropertyAccessor(true); 2645 } 2646 } 2647 } 2648 ImplMethodsVsClassMethods(S, IC, IDecl); 2649 AtomicPropertySetterGetterRules(IC, IDecl); 2650 DiagnoseOwningPropertyGetterSynthesis(IC); 2651 DiagnoseUnusedBackingIvarInAccessor(S, IC); 2652 if (IDecl->hasDesignatedInitializers()) 2653 DiagnoseMissingDesignatedInitOverrides(IC, IDecl); 2654 2655 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>(); 2656 if (IDecl->getSuperClass() == NULL) { 2657 // This class has no superclass, so check that it has been marked with 2658 // __attribute((objc_root_class)). 2659 if (!HasRootClassAttr) { 2660 SourceLocation DeclLoc(IDecl->getLocation()); 2661 SourceLocation SuperClassLoc(PP.getLocForEndOfToken(DeclLoc)); 2662 Diag(DeclLoc, diag::warn_objc_root_class_missing) 2663 << IDecl->getIdentifier(); 2664 // See if NSObject is in the current scope, and if it is, suggest 2665 // adding " : NSObject " to the class declaration. 2666 NamedDecl *IF = LookupSingleName(TUScope, 2667 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject), 2668 DeclLoc, LookupOrdinaryName); 2669 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 2670 if (NSObjectDecl && NSObjectDecl->getDefinition()) { 2671 Diag(SuperClassLoc, diag::note_objc_needs_superclass) 2672 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject "); 2673 } else { 2674 Diag(SuperClassLoc, diag::note_objc_needs_superclass); 2675 } 2676 } 2677 } else if (HasRootClassAttr) { 2678 // Complain that only root classes may have this attribute. 2679 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass); 2680 } 2681 2682 if (LangOpts.ObjCRuntime.isNonFragile()) { 2683 while (IDecl->getSuperClass()) { 2684 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass()); 2685 IDecl = IDecl->getSuperClass(); 2686 } 2687 } 2688 } 2689 SetIvarInitializers(IC); 2690 } else if (ObjCCategoryImplDecl* CatImplClass = 2691 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { 2692 CatImplClass->setAtEndRange(AtEnd); 2693 2694 // Find category interface decl and then check that all methods declared 2695 // in this interface are implemented in the category @implementation. 2696 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { 2697 if (ObjCCategoryDecl *Cat 2698 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) { 2699 ImplMethodsVsClassMethods(S, CatImplClass, Cat); 2700 } 2701 } 2702 } 2703 if (isInterfaceDeclKind) { 2704 // Reject invalid vardecls. 2705 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 2706 DeclGroupRef DG = allTUVars[i].get(); 2707 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 2708 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { 2709 if (!VDecl->hasExternalStorage()) 2710 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); 2711 } 2712 } 2713 } 2714 ActOnObjCContainerFinishDefinition(); 2715 2716 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 2717 DeclGroupRef DG = allTUVars[i].get(); 2718 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 2719 (*I)->setTopLevelDeclInObjCContainer(); 2720 Consumer.HandleTopLevelDeclInObjCContainer(DG); 2721 } 2722 2723 ActOnDocumentableDecl(ClassDecl); 2724 return ClassDecl; 2725 } 2726 2727 2728 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for 2729 /// objective-c's type qualifier from the parser version of the same info. 2730 static Decl::ObjCDeclQualifier 2731 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { 2732 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal; 2733 } 2734 2735 /// \brief Check whether the declared result type of the given Objective-C 2736 /// method declaration is compatible with the method's class. 2737 /// 2738 static Sema::ResultTypeCompatibilityKind 2739 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, 2740 ObjCInterfaceDecl *CurrentClass) { 2741 QualType ResultType = Method->getResultType(); 2742 2743 // If an Objective-C method inherits its related result type, then its 2744 // declared result type must be compatible with its own class type. The 2745 // declared result type is compatible if: 2746 if (const ObjCObjectPointerType *ResultObjectType 2747 = ResultType->getAs<ObjCObjectPointerType>()) { 2748 // - it is id or qualified id, or 2749 if (ResultObjectType->isObjCIdType() || 2750 ResultObjectType->isObjCQualifiedIdType()) 2751 return Sema::RTC_Compatible; 2752 2753 if (CurrentClass) { 2754 if (ObjCInterfaceDecl *ResultClass 2755 = ResultObjectType->getInterfaceDecl()) { 2756 // - it is the same as the method's class type, or 2757 if (declaresSameEntity(CurrentClass, ResultClass)) 2758 return Sema::RTC_Compatible; 2759 2760 // - it is a superclass of the method's class type 2761 if (ResultClass->isSuperClassOf(CurrentClass)) 2762 return Sema::RTC_Compatible; 2763 } 2764 } else { 2765 // Any Objective-C pointer type might be acceptable for a protocol 2766 // method; we just don't know. 2767 return Sema::RTC_Unknown; 2768 } 2769 } 2770 2771 return Sema::RTC_Incompatible; 2772 } 2773 2774 namespace { 2775 /// A helper class for searching for methods which a particular method 2776 /// overrides. 2777 class OverrideSearch { 2778 public: 2779 Sema &S; 2780 ObjCMethodDecl *Method; 2781 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden; 2782 bool Recursive; 2783 2784 public: 2785 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) { 2786 Selector selector = method->getSelector(); 2787 2788 // Bypass this search if we've never seen an instance/class method 2789 // with this selector before. 2790 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector); 2791 if (it == S.MethodPool.end()) { 2792 if (!S.getExternalSource()) return; 2793 S.ReadMethodPool(selector); 2794 2795 it = S.MethodPool.find(selector); 2796 if (it == S.MethodPool.end()) 2797 return; 2798 } 2799 ObjCMethodList &list = 2800 method->isInstanceMethod() ? it->second.first : it->second.second; 2801 if (!list.Method) return; 2802 2803 ObjCContainerDecl *container 2804 = cast<ObjCContainerDecl>(method->getDeclContext()); 2805 2806 // Prevent the search from reaching this container again. This is 2807 // important with categories, which override methods from the 2808 // interface and each other. 2809 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) { 2810 searchFromContainer(container); 2811 if (ObjCInterfaceDecl *Interface = Category->getClassInterface()) 2812 searchFromContainer(Interface); 2813 } else { 2814 searchFromContainer(container); 2815 } 2816 } 2817 2818 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator; 2819 iterator begin() const { return Overridden.begin(); } 2820 iterator end() const { return Overridden.end(); } 2821 2822 private: 2823 void searchFromContainer(ObjCContainerDecl *container) { 2824 if (container->isInvalidDecl()) return; 2825 2826 switch (container->getDeclKind()) { 2827 #define OBJCCONTAINER(type, base) \ 2828 case Decl::type: \ 2829 searchFrom(cast<type##Decl>(container)); \ 2830 break; 2831 #define ABSTRACT_DECL(expansion) 2832 #define DECL(type, base) \ 2833 case Decl::type: 2834 #include "clang/AST/DeclNodes.inc" 2835 llvm_unreachable("not an ObjC container!"); 2836 } 2837 } 2838 2839 void searchFrom(ObjCProtocolDecl *protocol) { 2840 if (!protocol->hasDefinition()) 2841 return; 2842 2843 // A method in a protocol declaration overrides declarations from 2844 // referenced ("parent") protocols. 2845 search(protocol->getReferencedProtocols()); 2846 } 2847 2848 void searchFrom(ObjCCategoryDecl *category) { 2849 // A method in a category declaration overrides declarations from 2850 // the main class and from protocols the category references. 2851 // The main class is handled in the constructor. 2852 search(category->getReferencedProtocols()); 2853 } 2854 2855 void searchFrom(ObjCCategoryImplDecl *impl) { 2856 // A method in a category definition that has a category 2857 // declaration overrides declarations from the category 2858 // declaration. 2859 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) { 2860 search(category); 2861 if (ObjCInterfaceDecl *Interface = category->getClassInterface()) 2862 search(Interface); 2863 2864 // Otherwise it overrides declarations from the class. 2865 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) { 2866 search(Interface); 2867 } 2868 } 2869 2870 void searchFrom(ObjCInterfaceDecl *iface) { 2871 // A method in a class declaration overrides declarations from 2872 if (!iface->hasDefinition()) 2873 return; 2874 2875 // - categories, 2876 for (ObjCInterfaceDecl::known_categories_iterator 2877 cat = iface->known_categories_begin(), 2878 catEnd = iface->known_categories_end(); 2879 cat != catEnd; ++cat) { 2880 search(*cat); 2881 } 2882 2883 // - the super class, and 2884 if (ObjCInterfaceDecl *super = iface->getSuperClass()) 2885 search(super); 2886 2887 // - any referenced protocols. 2888 search(iface->getReferencedProtocols()); 2889 } 2890 2891 void searchFrom(ObjCImplementationDecl *impl) { 2892 // A method in a class implementation overrides declarations from 2893 // the class interface. 2894 if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) 2895 search(Interface); 2896 } 2897 2898 2899 void search(const ObjCProtocolList &protocols) { 2900 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end(); 2901 i != e; ++i) 2902 search(*i); 2903 } 2904 2905 void search(ObjCContainerDecl *container) { 2906 // Check for a method in this container which matches this selector. 2907 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(), 2908 Method->isInstanceMethod(), 2909 /*AllowHidden=*/true); 2910 2911 // If we find one, record it and bail out. 2912 if (meth) { 2913 Overridden.insert(meth); 2914 return; 2915 } 2916 2917 // Otherwise, search for methods that a hypothetical method here 2918 // would have overridden. 2919 2920 // Note that we're now in a recursive case. 2921 Recursive = true; 2922 2923 searchFromContainer(container); 2924 } 2925 }; 2926 } 2927 2928 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 2929 ObjCInterfaceDecl *CurrentClass, 2930 ResultTypeCompatibilityKind RTC) { 2931 // Search for overridden methods and merge information down from them. 2932 OverrideSearch overrides(*this, ObjCMethod); 2933 // Keep track if the method overrides any method in the class's base classes, 2934 // its protocols, or its categories' protocols; we will keep that info 2935 // in the ObjCMethodDecl. 2936 // For this info, a method in an implementation is not considered as 2937 // overriding the same method in the interface or its categories. 2938 bool hasOverriddenMethodsInBaseOrProtocol = false; 2939 for (OverrideSearch::iterator 2940 i = overrides.begin(), e = overrides.end(); i != e; ++i) { 2941 ObjCMethodDecl *overridden = *i; 2942 2943 if (!hasOverriddenMethodsInBaseOrProtocol) { 2944 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) || 2945 CurrentClass != overridden->getClassInterface() || 2946 overridden->isOverriding()) { 2947 hasOverriddenMethodsInBaseOrProtocol = true; 2948 2949 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) { 2950 // OverrideSearch will return as "overridden" the same method in the 2951 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to 2952 // check whether a category of a base class introduced a method with the 2953 // same selector, after the interface method declaration. 2954 // To avoid unnecessary lookups in the majority of cases, we use the 2955 // extra info bits in GlobalMethodPool to check whether there were any 2956 // category methods with this selector. 2957 GlobalMethodPool::iterator It = 2958 MethodPool.find(ObjCMethod->getSelector()); 2959 if (It != MethodPool.end()) { 2960 ObjCMethodList &List = 2961 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second; 2962 unsigned CategCount = List.getBits(); 2963 if (CategCount > 0) { 2964 // If the method is in a category we'll do lookup if there were at 2965 // least 2 category methods recorded, otherwise only one will do. 2966 if (CategCount > 1 || 2967 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) { 2968 OverrideSearch overrides(*this, overridden); 2969 for (OverrideSearch::iterator 2970 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) { 2971 ObjCMethodDecl *SuperOverridden = *OI; 2972 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) || 2973 CurrentClass != SuperOverridden->getClassInterface()) { 2974 hasOverriddenMethodsInBaseOrProtocol = true; 2975 overridden->setOverriding(true); 2976 break; 2977 } 2978 } 2979 } 2980 } 2981 } 2982 } 2983 } 2984 2985 // Propagate down the 'related result type' bit from overridden methods. 2986 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType()) 2987 ObjCMethod->SetRelatedResultType(); 2988 2989 // Then merge the declarations. 2990 mergeObjCMethodDecls(ObjCMethod, overridden); 2991 2992 if (ObjCMethod->isImplicit() && overridden->isImplicit()) 2993 continue; // Conflicting properties are detected elsewhere. 2994 2995 // Check for overriding methods 2996 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 2997 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) 2998 CheckConflictingOverridingMethod(ObjCMethod, overridden, 2999 isa<ObjCProtocolDecl>(overridden->getDeclContext())); 3000 3001 if (CurrentClass && overridden->getDeclContext() != CurrentClass && 3002 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && 3003 !overridden->isImplicit() /* not meant for properties */) { 3004 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(), 3005 E = ObjCMethod->param_end(); 3006 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(), 3007 PrevE = overridden->param_end(); 3008 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) { 3009 assert(PrevI != overridden->param_end() && "Param mismatch"); 3010 QualType T1 = Context.getCanonicalType((*ParamI)->getType()); 3011 QualType T2 = Context.getCanonicalType((*PrevI)->getType()); 3012 // If type of argument of method in this class does not match its 3013 // respective argument type in the super class method, issue warning; 3014 if (!Context.typesAreCompatible(T1, T2)) { 3015 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super) 3016 << T1 << T2; 3017 Diag(overridden->getLocation(), diag::note_previous_declaration); 3018 break; 3019 } 3020 } 3021 } 3022 } 3023 3024 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol); 3025 } 3026 3027 Decl *Sema::ActOnMethodDeclaration( 3028 Scope *S, 3029 SourceLocation MethodLoc, SourceLocation EndLoc, 3030 tok::TokenKind MethodType, 3031 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 3032 ArrayRef<SourceLocation> SelectorLocs, 3033 Selector Sel, 3034 // optional arguments. The number of types/arguments is obtained 3035 // from the Sel.getNumArgs(). 3036 ObjCArgInfo *ArgInfo, 3037 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 3038 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind, 3039 bool isVariadic, bool MethodDefinition) { 3040 // Make sure we can establish a context for the method. 3041 if (!CurContext->isObjCContainer()) { 3042 Diag(MethodLoc, diag::error_missing_method_context); 3043 return 0; 3044 } 3045 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 3046 Decl *ClassDecl = cast<Decl>(OCD); 3047 QualType resultDeclType; 3048 3049 bool HasRelatedResultType = false; 3050 TypeSourceInfo *ResultTInfo = 0; 3051 if (ReturnType) { 3052 resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo); 3053 3054 if (CheckFunctionReturnType(resultDeclType, MethodLoc)) 3055 return 0; 3056 3057 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType()); 3058 } else { // get the type for "id". 3059 resultDeclType = Context.getObjCIdType(); 3060 Diag(MethodLoc, diag::warn_missing_method_return_type) 3061 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)"); 3062 } 3063 3064 ObjCMethodDecl* ObjCMethod = 3065 ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, 3066 resultDeclType, 3067 ResultTInfo, 3068 CurContext, 3069 MethodType == tok::minus, isVariadic, 3070 /*isPropertyAccessor=*/false, 3071 /*isImplicitlyDeclared=*/false, /*isDefined=*/false, 3072 MethodDeclKind == tok::objc_optional 3073 ? ObjCMethodDecl::Optional 3074 : ObjCMethodDecl::Required, 3075 HasRelatedResultType); 3076 3077 SmallVector<ParmVarDecl*, 16> Params; 3078 3079 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { 3080 QualType ArgType; 3081 TypeSourceInfo *DI; 3082 3083 if (!ArgInfo[i].Type) { 3084 ArgType = Context.getObjCIdType(); 3085 DI = 0; 3086 } else { 3087 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); 3088 } 3089 3090 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 3091 LookupOrdinaryName, ForRedeclaration); 3092 LookupName(R, S); 3093 if (R.isSingleResult()) { 3094 NamedDecl *PrevDecl = R.getFoundDecl(); 3095 if (S->isDeclScope(PrevDecl)) { 3096 Diag(ArgInfo[i].NameLoc, 3097 (MethodDefinition ? diag::warn_method_param_redefinition 3098 : diag::warn_method_param_declaration)) 3099 << ArgInfo[i].Name; 3100 Diag(PrevDecl->getLocation(), 3101 diag::note_previous_declaration); 3102 } 3103 } 3104 3105 SourceLocation StartLoc = DI 3106 ? DI->getTypeLoc().getBeginLoc() 3107 : ArgInfo[i].NameLoc; 3108 3109 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc, 3110 ArgInfo[i].NameLoc, ArgInfo[i].Name, 3111 ArgType, DI, SC_None); 3112 3113 Param->setObjCMethodScopeInfo(i); 3114 3115 Param->setObjCDeclQualifier( 3116 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); 3117 3118 // Apply the attributes to the parameter. 3119 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs); 3120 3121 if (Param->hasAttr<BlocksAttr>()) { 3122 Diag(Param->getLocation(), diag::err_block_on_nonlocal); 3123 Param->setInvalidDecl(); 3124 } 3125 S->AddDecl(Param); 3126 IdResolver.AddDecl(Param); 3127 3128 Params.push_back(Param); 3129 } 3130 3131 for (unsigned i = 0, e = CNumArgs; i != e; ++i) { 3132 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); 3133 QualType ArgType = Param->getType(); 3134 if (ArgType.isNull()) 3135 ArgType = Context.getObjCIdType(); 3136 else 3137 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 3138 ArgType = Context.getAdjustedParameterType(ArgType); 3139 3140 Param->setDeclContext(ObjCMethod); 3141 Params.push_back(Param); 3142 } 3143 3144 ObjCMethod->setMethodParams(Context, Params, SelectorLocs); 3145 ObjCMethod->setObjCDeclQualifier( 3146 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); 3147 3148 if (AttrList) 3149 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList); 3150 3151 // Add the method now. 3152 const ObjCMethodDecl *PrevMethod = 0; 3153 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) { 3154 if (MethodType == tok::minus) { 3155 PrevMethod = ImpDecl->getInstanceMethod(Sel); 3156 ImpDecl->addInstanceMethod(ObjCMethod); 3157 } else { 3158 PrevMethod = ImpDecl->getClassMethod(Sel); 3159 ImpDecl->addClassMethod(ObjCMethod); 3160 } 3161 3162 ObjCMethodDecl *IMD = 0; 3163 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) 3164 IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 3165 ObjCMethod->isInstanceMethod()); 3166 if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() && 3167 !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) { 3168 // merge the attribute into implementation. 3169 ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context, 3170 ObjCMethod->getLocation())); 3171 } 3172 if (isa<ObjCCategoryImplDecl>(ImpDecl)) { 3173 ObjCMethodFamily family = ObjCMethod->getMethodFamily(); 3174 if (family == OMF_dealloc && IMD && IMD->isOverriding()) 3175 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category) 3176 << ObjCMethod->getDeclName(); 3177 } 3178 } else { 3179 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); 3180 } 3181 3182 if (PrevMethod) { 3183 // You can never have two method definitions with the same name. 3184 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) 3185 << ObjCMethod->getDeclName(); 3186 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3187 ObjCMethod->setInvalidDecl(); 3188 return ObjCMethod; 3189 } 3190 3191 // If this Objective-C method does not have a related result type, but we 3192 // are allowed to infer related result types, try to do so based on the 3193 // method family. 3194 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 3195 if (!CurrentClass) { 3196 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) 3197 CurrentClass = Cat->getClassInterface(); 3198 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl)) 3199 CurrentClass = Impl->getClassInterface(); 3200 else if (ObjCCategoryImplDecl *CatImpl 3201 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) 3202 CurrentClass = CatImpl->getClassInterface(); 3203 } 3204 3205 ResultTypeCompatibilityKind RTC 3206 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass); 3207 3208 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC); 3209 3210 bool ARCError = false; 3211 if (getLangOpts().ObjCAutoRefCount) 3212 ARCError = CheckARCMethodDecl(ObjCMethod); 3213 3214 // Infer the related result type when possible. 3215 if (!ARCError && RTC == Sema::RTC_Compatible && 3216 !ObjCMethod->hasRelatedResultType() && 3217 LangOpts.ObjCInferRelatedResultType) { 3218 bool InferRelatedResultType = false; 3219 switch (ObjCMethod->getMethodFamily()) { 3220 case OMF_None: 3221 case OMF_copy: 3222 case OMF_dealloc: 3223 case OMF_finalize: 3224 case OMF_mutableCopy: 3225 case OMF_release: 3226 case OMF_retainCount: 3227 case OMF_performSelector: 3228 break; 3229 3230 case OMF_alloc: 3231 case OMF_new: 3232 InferRelatedResultType = ObjCMethod->isClassMethod(); 3233 break; 3234 3235 case OMF_init: 3236 case OMF_autorelease: 3237 case OMF_retain: 3238 case OMF_self: 3239 InferRelatedResultType = ObjCMethod->isInstanceMethod(); 3240 break; 3241 } 3242 3243 if (InferRelatedResultType) 3244 ObjCMethod->SetRelatedResultType(); 3245 } 3246 3247 ActOnDocumentableDecl(ObjCMethod); 3248 3249 return ObjCMethod; 3250 } 3251 3252 bool Sema::CheckObjCDeclScope(Decl *D) { 3253 // Following is also an error. But it is caused by a missing @end 3254 // and diagnostic is issued elsewhere. 3255 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) 3256 return false; 3257 3258 // If we switched context to translation unit while we are still lexically in 3259 // an objc container, it means the parser missed emitting an error. 3260 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) 3261 return false; 3262 3263 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); 3264 D->setInvalidDecl(); 3265 3266 return true; 3267 } 3268 3269 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the 3270 /// instance variables of ClassName into Decls. 3271 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 3272 IdentifierInfo *ClassName, 3273 SmallVectorImpl<Decl*> &Decls) { 3274 // Check that ClassName is a valid class 3275 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart); 3276 if (!Class) { 3277 Diag(DeclStart, diag::err_undef_interface) << ClassName; 3278 return; 3279 } 3280 if (LangOpts.ObjCRuntime.isNonFragile()) { 3281 Diag(DeclStart, diag::err_atdef_nonfragile_interface); 3282 return; 3283 } 3284 3285 // Collect the instance variables 3286 SmallVector<const ObjCIvarDecl*, 32> Ivars; 3287 Context.DeepCollectObjCIvars(Class, true, Ivars); 3288 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 3289 for (unsigned i = 0; i < Ivars.size(); i++) { 3290 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]); 3291 RecordDecl *Record = dyn_cast<RecordDecl>(TagD); 3292 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, 3293 /*FIXME: StartL=*/ID->getLocation(), 3294 ID->getLocation(), 3295 ID->getIdentifier(), ID->getType(), 3296 ID->getBitWidth()); 3297 Decls.push_back(FD); 3298 } 3299 3300 // Introduce all of these fields into the appropriate scope. 3301 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin(); 3302 D != Decls.end(); ++D) { 3303 FieldDecl *FD = cast<FieldDecl>(*D); 3304 if (getLangOpts().CPlusPlus) 3305 PushOnScopeChains(cast<FieldDecl>(FD), S); 3306 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD)) 3307 Record->addDecl(FD); 3308 } 3309 } 3310 3311 /// \brief Build a type-check a new Objective-C exception variable declaration. 3312 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, 3313 SourceLocation StartLoc, 3314 SourceLocation IdLoc, 3315 IdentifierInfo *Id, 3316 bool Invalid) { 3317 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 3318 // duration shall not be qualified by an address-space qualifier." 3319 // Since all parameters have automatic store duration, they can not have 3320 // an address space. 3321 if (T.getAddressSpace() != 0) { 3322 Diag(IdLoc, diag::err_arg_with_address_space); 3323 Invalid = true; 3324 } 3325 3326 // An @catch parameter must be an unqualified object pointer type; 3327 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? 3328 if (Invalid) { 3329 // Don't do any further checking. 3330 } else if (T->isDependentType()) { 3331 // Okay: we don't know what this type will instantiate to. 3332 } else if (!T->isObjCObjectPointerType()) { 3333 Invalid = true; 3334 Diag(IdLoc ,diag::err_catch_param_not_objc_type); 3335 } else if (T->isObjCQualifiedIdType()) { 3336 Invalid = true; 3337 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm); 3338 } 3339 3340 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, 3341 T, TInfo, SC_None); 3342 New->setExceptionVariable(true); 3343 3344 // In ARC, infer 'retaining' for variables of retainable type. 3345 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) 3346 Invalid = true; 3347 3348 if (Invalid) 3349 New->setInvalidDecl(); 3350 return New; 3351 } 3352 3353 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { 3354 const DeclSpec &DS = D.getDeclSpec(); 3355 3356 // We allow the "register" storage class on exception variables because 3357 // GCC did, but we drop it completely. Any other storage class is an error. 3358 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 3359 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm) 3360 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc())); 3361 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3362 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm) 3363 << DeclSpec::getSpecifierName(SCS); 3364 } 3365 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 3366 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 3367 diag::err_invalid_thread) 3368 << DeclSpec::getSpecifierName(TSCS); 3369 D.getMutableDeclSpec().ClearStorageClassSpecs(); 3370 3371 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 3372 3373 // Check that there are no default arguments inside the type of this 3374 // exception object (C++ only). 3375 if (getLangOpts().CPlusPlus) 3376 CheckExtraCXXDefaultArguments(D); 3377 3378 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 3379 QualType ExceptionType = TInfo->getType(); 3380 3381 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, 3382 D.getSourceRange().getBegin(), 3383 D.getIdentifierLoc(), 3384 D.getIdentifier(), 3385 D.isInvalidType()); 3386 3387 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 3388 if (D.getCXXScopeSpec().isSet()) { 3389 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) 3390 << D.getCXXScopeSpec().getRange(); 3391 New->setInvalidDecl(); 3392 } 3393 3394 // Add the parameter declaration into this scope. 3395 S->AddDecl(New); 3396 if (D.getIdentifier()) 3397 IdResolver.AddDecl(New); 3398 3399 ProcessDeclAttributes(S, New, D); 3400 3401 if (New->hasAttr<BlocksAttr>()) 3402 Diag(New->getLocation(), diag::err_block_on_nonlocal); 3403 return New; 3404 } 3405 3406 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 3407 /// initialization. 3408 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 3409 SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 3410 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 3411 Iv= Iv->getNextIvar()) { 3412 QualType QT = Context.getBaseElementType(Iv->getType()); 3413 if (QT->isRecordType()) 3414 Ivars.push_back(Iv); 3415 } 3416 } 3417 3418 void Sema::DiagnoseUseOfUnimplementedSelectors() { 3419 // Load referenced selectors from the external source. 3420 if (ExternalSource) { 3421 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels; 3422 ExternalSource->ReadReferencedSelectors(Sels); 3423 for (unsigned I = 0, N = Sels.size(); I != N; ++I) 3424 ReferencedSelectors[Sels[I].first] = Sels[I].second; 3425 } 3426 3427 // Warning will be issued only when selector table is 3428 // generated (which means there is at lease one implementation 3429 // in the TU). This is to match gcc's behavior. 3430 if (ReferencedSelectors.empty() || 3431 !Context.AnyObjCImplementation()) 3432 return; 3433 for (llvm::DenseMap<Selector, SourceLocation>::iterator S = 3434 ReferencedSelectors.begin(), 3435 E = ReferencedSelectors.end(); S != E; ++S) { 3436 Selector Sel = (*S).first; 3437 if (!LookupImplementedMethodInGlobalPool(Sel)) 3438 Diag((*S).second, diag::warn_unimplemented_selector) << Sel; 3439 } 3440 return; 3441 } 3442 3443 ObjCIvarDecl * 3444 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 3445 const ObjCPropertyDecl *&PDecl) const { 3446 if (Method->isClassMethod()) 3447 return 0; 3448 const ObjCInterfaceDecl *IDecl = Method->getClassInterface(); 3449 if (!IDecl) 3450 return 0; 3451 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true, 3452 /*shallowCategoryLookup=*/false, 3453 /*followSuper=*/false); 3454 if (!Method || !Method->isPropertyAccessor()) 3455 return 0; 3456 if ((PDecl = Method->findPropertyDecl())) 3457 return PDecl->getPropertyIvarDecl(); 3458 3459 return 0; 3460 } 3461 3462 namespace { 3463 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property 3464 /// accessor references the backing ivar. 3465 class UnusedBackingIvarChecker : 3466 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> { 3467 public: 3468 Sema &S; 3469 const ObjCMethodDecl *Method; 3470 const ObjCIvarDecl *IvarD; 3471 bool AccessedIvar; 3472 bool InvokedSelfMethod; 3473 3474 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method, 3475 const ObjCIvarDecl *IvarD) 3476 : S(S), Method(Method), IvarD(IvarD), 3477 AccessedIvar(false), InvokedSelfMethod(false) { 3478 assert(IvarD); 3479 } 3480 3481 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 3482 if (E->getDecl() == IvarD) { 3483 AccessedIvar = true; 3484 return false; 3485 } 3486 return true; 3487 } 3488 3489 bool VisitObjCMessageExpr(ObjCMessageExpr *E) { 3490 if (E->getReceiverKind() == ObjCMessageExpr::Instance && 3491 S.isSelfExpr(E->getInstanceReceiver(), Method)) { 3492 InvokedSelfMethod = true; 3493 } 3494 return true; 3495 } 3496 }; 3497 } 3498 3499 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S, 3500 const ObjCImplementationDecl *ImplD) { 3501 if (S->hasUnrecoverableErrorOccurred()) 3502 return; 3503 3504 for (ObjCImplementationDecl::instmeth_iterator 3505 MI = ImplD->instmeth_begin(), 3506 ME = ImplD->instmeth_end(); MI != ME; ++MI) { 3507 const ObjCMethodDecl *CurMethod = *MI; 3508 unsigned DIAG = diag::warn_unused_property_backing_ivar; 3509 SourceLocation Loc = CurMethod->getLocation(); 3510 if (Diags.getDiagnosticLevel(DIAG, Loc) == DiagnosticsEngine::Ignored) 3511 continue; 3512 3513 const ObjCPropertyDecl *PDecl; 3514 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl); 3515 if (!IV) 3516 continue; 3517 3518 UnusedBackingIvarChecker Checker(*this, CurMethod, IV); 3519 Checker.TraverseStmt(CurMethod->getBody()); 3520 if (Checker.AccessedIvar) 3521 continue; 3522 3523 // Do not issue this warning if backing ivar is used somewhere and accessor 3524 // implementation makes a self call. This is to prevent false positive in 3525 // cases where the ivar is accessed by another method that the accessor 3526 // delegates to. 3527 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) { 3528 Diag(Loc, DIAG) << IV; 3529 Diag(PDecl->getLocation(), diag::note_property_declare); 3530 } 3531 } 3532 } 3533