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