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