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